File: | llvm/lib/Analysis/ScalarEvolution.cpp |
Warning: | line 6164, column 29 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 | |||||||||||
230 | //===----------------------------------------------------------------------===// | ||||||||||
231 | // SCEV class definitions | ||||||||||
232 | //===----------------------------------------------------------------------===// | ||||||||||
233 | |||||||||||
234 | //===----------------------------------------------------------------------===// | ||||||||||
235 | // Implementation of the SCEV class. | ||||||||||
236 | // | ||||||||||
237 | |||||||||||
238 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | ||||||||||
239 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void SCEV::dump() const { | ||||||||||
240 | print(dbgs()); | ||||||||||
241 | dbgs() << '\n'; | ||||||||||
242 | } | ||||||||||
243 | #endif | ||||||||||
244 | |||||||||||
245 | void SCEV::print(raw_ostream &OS) const { | ||||||||||
246 | switch (static_cast<SCEVTypes>(getSCEVType())) { | ||||||||||
247 | case scConstant: | ||||||||||
248 | cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); | ||||||||||
249 | return; | ||||||||||
250 | case scTruncate: { | ||||||||||
251 | const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); | ||||||||||
252 | const SCEV *Op = Trunc->getOperand(); | ||||||||||
253 | OS << "(trunc " << *Op->getType() << " " << *Op << " to " | ||||||||||
254 | << *Trunc->getType() << ")"; | ||||||||||
255 | return; | ||||||||||
256 | } | ||||||||||
257 | case scZeroExtend: { | ||||||||||
258 | const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); | ||||||||||
259 | const SCEV *Op = ZExt->getOperand(); | ||||||||||
260 | OS << "(zext " << *Op->getType() << " " << *Op << " to " | ||||||||||
261 | << *ZExt->getType() << ")"; | ||||||||||
262 | return; | ||||||||||
263 | } | ||||||||||
264 | case scSignExtend: { | ||||||||||
265 | const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); | ||||||||||
266 | const SCEV *Op = SExt->getOperand(); | ||||||||||
267 | OS << "(sext " << *Op->getType() << " " << *Op << " to " | ||||||||||
268 | << *SExt->getType() << ")"; | ||||||||||
269 | return; | ||||||||||
270 | } | ||||||||||
271 | case scAddRecExpr: { | ||||||||||
272 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); | ||||||||||
273 | OS << "{" << *AR->getOperand(0); | ||||||||||
274 | for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) | ||||||||||
275 | OS << ",+," << *AR->getOperand(i); | ||||||||||
276 | OS << "}<"; | ||||||||||
277 | if (AR->hasNoUnsignedWrap()) | ||||||||||
278 | OS << "nuw><"; | ||||||||||
279 | if (AR->hasNoSignedWrap()) | ||||||||||
280 | OS << "nsw><"; | ||||||||||
281 | if (AR->hasNoSelfWrap() && | ||||||||||
282 | !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) | ||||||||||
283 | OS << "nw><"; | ||||||||||
284 | AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
285 | OS << ">"; | ||||||||||
286 | return; | ||||||||||
287 | } | ||||||||||
288 | case scAddExpr: | ||||||||||
289 | case scMulExpr: | ||||||||||
290 | case scUMaxExpr: | ||||||||||
291 | case scSMaxExpr: | ||||||||||
292 | case scUMinExpr: | ||||||||||
293 | case scSMinExpr: { | ||||||||||
294 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); | ||||||||||
295 | const char *OpStr = nullptr; | ||||||||||
296 | switch (NAry->getSCEVType()) { | ||||||||||
297 | case scAddExpr: OpStr = " + "; break; | ||||||||||
298 | case scMulExpr: OpStr = " * "; break; | ||||||||||
299 | case scUMaxExpr: OpStr = " umax "; break; | ||||||||||
300 | case scSMaxExpr: OpStr = " smax "; break; | ||||||||||
301 | case scUMinExpr: | ||||||||||
302 | OpStr = " umin "; | ||||||||||
303 | break; | ||||||||||
304 | case scSMinExpr: | ||||||||||
305 | OpStr = " smin "; | ||||||||||
306 | break; | ||||||||||
307 | } | ||||||||||
308 | OS << "("; | ||||||||||
309 | for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); | ||||||||||
310 | I != E; ++I) { | ||||||||||
311 | OS << **I; | ||||||||||
312 | if (std::next(I) != E) | ||||||||||
313 | OS << OpStr; | ||||||||||
314 | } | ||||||||||
315 | OS << ")"; | ||||||||||
316 | switch (NAry->getSCEVType()) { | ||||||||||
317 | case scAddExpr: | ||||||||||
318 | case scMulExpr: | ||||||||||
319 | if (NAry->hasNoUnsignedWrap()) | ||||||||||
320 | OS << "<nuw>"; | ||||||||||
321 | if (NAry->hasNoSignedWrap()) | ||||||||||
322 | OS << "<nsw>"; | ||||||||||
323 | } | ||||||||||
324 | return; | ||||||||||
325 | } | ||||||||||
326 | case scUDivExpr: { | ||||||||||
327 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); | ||||||||||
328 | OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; | ||||||||||
329 | return; | ||||||||||
330 | } | ||||||||||
331 | case scUnknown: { | ||||||||||
332 | const SCEVUnknown *U = cast<SCEVUnknown>(this); | ||||||||||
333 | Type *AllocTy; | ||||||||||
334 | if (U->isSizeOf(AllocTy)) { | ||||||||||
335 | OS << "sizeof(" << *AllocTy << ")"; | ||||||||||
336 | return; | ||||||||||
337 | } | ||||||||||
338 | if (U->isAlignOf(AllocTy)) { | ||||||||||
339 | OS << "alignof(" << *AllocTy << ")"; | ||||||||||
340 | return; | ||||||||||
341 | } | ||||||||||
342 | |||||||||||
343 | Type *CTy; | ||||||||||
344 | Constant *FieldNo; | ||||||||||
345 | if (U->isOffsetOf(CTy, FieldNo)) { | ||||||||||
346 | OS << "offsetof(" << *CTy << ", "; | ||||||||||
347 | FieldNo->printAsOperand(OS, false); | ||||||||||
348 | OS << ")"; | ||||||||||
349 | return; | ||||||||||
350 | } | ||||||||||
351 | |||||||||||
352 | // Otherwise just print it normally. | ||||||||||
353 | U->getValue()->printAsOperand(OS, false); | ||||||||||
354 | return; | ||||||||||
355 | } | ||||||||||
356 | case scCouldNotCompute: | ||||||||||
357 | OS << "***COULDNOTCOMPUTE***"; | ||||||||||
358 | return; | ||||||||||
359 | } | ||||||||||
360 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 360); | ||||||||||
361 | } | ||||||||||
362 | |||||||||||
363 | Type *SCEV::getType() const { | ||||||||||
364 | switch (static_cast<SCEVTypes>(getSCEVType())) { | ||||||||||
365 | case scConstant: | ||||||||||
366 | return cast<SCEVConstant>(this)->getType(); | ||||||||||
367 | case scTruncate: | ||||||||||
368 | case scZeroExtend: | ||||||||||
369 | case scSignExtend: | ||||||||||
370 | return cast<SCEVCastExpr>(this)->getType(); | ||||||||||
371 | case scAddRecExpr: | ||||||||||
372 | case scMulExpr: | ||||||||||
373 | case scUMaxExpr: | ||||||||||
374 | case scSMaxExpr: | ||||||||||
375 | case scUMinExpr: | ||||||||||
376 | case scSMinExpr: | ||||||||||
377 | return cast<SCEVNAryExpr>(this)->getType(); | ||||||||||
378 | case scAddExpr: | ||||||||||
379 | return cast<SCEVAddExpr>(this)->getType(); | ||||||||||
380 | case scUDivExpr: | ||||||||||
381 | return cast<SCEVUDivExpr>(this)->getType(); | ||||||||||
382 | case scUnknown: | ||||||||||
383 | return cast<SCEVUnknown>(this)->getType(); | ||||||||||
384 | case scCouldNotCompute: | ||||||||||
385 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 385); | ||||||||||
386 | } | ||||||||||
387 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 387); | ||||||||||
388 | } | ||||||||||
389 | |||||||||||
390 | bool SCEV::isZero() const { | ||||||||||
391 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) | ||||||||||
392 | return SC->getValue()->isZero(); | ||||||||||
393 | return false; | ||||||||||
394 | } | ||||||||||
395 | |||||||||||
396 | bool SCEV::isOne() const { | ||||||||||
397 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) | ||||||||||
398 | return SC->getValue()->isOne(); | ||||||||||
399 | return false; | ||||||||||
400 | } | ||||||||||
401 | |||||||||||
402 | bool SCEV::isAllOnesValue() const { | ||||||||||
403 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) | ||||||||||
404 | return SC->getValue()->isMinusOne(); | ||||||||||
405 | return false; | ||||||||||
406 | } | ||||||||||
407 | |||||||||||
408 | bool SCEV::isNonConstantNegative() const { | ||||||||||
409 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); | ||||||||||
410 | if (!Mul) return false; | ||||||||||
411 | |||||||||||
412 | // If there is a constant factor, it will be first. | ||||||||||
413 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); | ||||||||||
414 | if (!SC) return false; | ||||||||||
415 | |||||||||||
416 | // Return true if the value is negative, this matches things like (-42 * V). | ||||||||||
417 | return SC->getAPInt().isNegative(); | ||||||||||
418 | } | ||||||||||
419 | |||||||||||
420 | SCEVCouldNotCompute::SCEVCouldNotCompute() : | ||||||||||
421 | SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} | ||||||||||
422 | |||||||||||
423 | bool SCEVCouldNotCompute::classof(const SCEV *S) { | ||||||||||
424 | return S->getSCEVType() == scCouldNotCompute; | ||||||||||
425 | } | ||||||||||
426 | |||||||||||
427 | const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { | ||||||||||
428 | FoldingSetNodeID ID; | ||||||||||
429 | ID.AddInteger(scConstant); | ||||||||||
430 | ID.AddPointer(V); | ||||||||||
431 | void *IP = nullptr; | ||||||||||
432 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
433 | SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); | ||||||||||
434 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
435 | return S; | ||||||||||
436 | } | ||||||||||
437 | |||||||||||
438 | const SCEV *ScalarEvolution::getConstant(const APInt &Val) { | ||||||||||
439 | return getConstant(ConstantInt::get(getContext(), Val)); | ||||||||||
440 | } | ||||||||||
441 | |||||||||||
442 | const SCEV * | ||||||||||
443 | ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { | ||||||||||
444 | IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); | ||||||||||
445 | return getConstant(ConstantInt::get(ITy, V, isSigned)); | ||||||||||
446 | } | ||||||||||
447 | |||||||||||
448 | SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, | ||||||||||
449 | unsigned SCEVTy, const SCEV *op, Type *ty) | ||||||||||
450 | : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { | ||||||||||
451 | Operands[0] = op; | ||||||||||
452 | } | ||||||||||
453 | |||||||||||
454 | SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, | ||||||||||
455 | const SCEV *op, Type *ty) | ||||||||||
456 | : SCEVCastExpr(ID, scTruncate, op, ty) { | ||||||||||
457 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 458, __PRETTY_FUNCTION__)) | ||||||||||
458 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 458, __PRETTY_FUNCTION__)); | ||||||||||
459 | } | ||||||||||
460 | |||||||||||
461 | SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, | ||||||||||
462 | const SCEV *op, Type *ty) | ||||||||||
463 | : SCEVCastExpr(ID, scZeroExtend, op, ty) { | ||||||||||
464 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 465, __PRETTY_FUNCTION__)) | ||||||||||
465 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 465, __PRETTY_FUNCTION__)); | ||||||||||
466 | } | ||||||||||
467 | |||||||||||
468 | SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, | ||||||||||
469 | const SCEV *op, Type *ty) | ||||||||||
470 | : SCEVCastExpr(ID, scSignExtend, op, ty) { | ||||||||||
471 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 472, __PRETTY_FUNCTION__)) | ||||||||||
472 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 472, __PRETTY_FUNCTION__)); | ||||||||||
473 | } | ||||||||||
474 | |||||||||||
475 | void SCEVUnknown::deleted() { | ||||||||||
476 | // Clear this SCEVUnknown from various maps. | ||||||||||
477 | SE->forgetMemoizedResults(this); | ||||||||||
478 | |||||||||||
479 | // Remove this SCEVUnknown from the uniquing map. | ||||||||||
480 | SE->UniqueSCEVs.RemoveNode(this); | ||||||||||
481 | |||||||||||
482 | // Release the value. | ||||||||||
483 | setValPtr(nullptr); | ||||||||||
484 | } | ||||||||||
485 | |||||||||||
486 | void SCEVUnknown::allUsesReplacedWith(Value *New) { | ||||||||||
487 | // Remove this SCEVUnknown from the uniquing map. | ||||||||||
488 | SE->UniqueSCEVs.RemoveNode(this); | ||||||||||
489 | |||||||||||
490 | // Update this SCEVUnknown to point to the new value. This is needed | ||||||||||
491 | // because there may still be outstanding SCEVs which still point to | ||||||||||
492 | // this SCEVUnknown. | ||||||||||
493 | setValPtr(New); | ||||||||||
494 | } | ||||||||||
495 | |||||||||||
496 | bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { | ||||||||||
497 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) | ||||||||||
498 | if (VCE->getOpcode() == Instruction::PtrToInt) | ||||||||||
499 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) | ||||||||||
500 | if (CE->getOpcode() == Instruction::GetElementPtr && | ||||||||||
501 | CE->getOperand(0)->isNullValue() && | ||||||||||
502 | CE->getNumOperands() == 2) | ||||||||||
503 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) | ||||||||||
504 | if (CI->isOne()) { | ||||||||||
505 | AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) | ||||||||||
506 | ->getElementType(); | ||||||||||
507 | return true; | ||||||||||
508 | } | ||||||||||
509 | |||||||||||
510 | return false; | ||||||||||
511 | } | ||||||||||
512 | |||||||||||
513 | bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { | ||||||||||
514 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) | ||||||||||
515 | if (VCE->getOpcode() == Instruction::PtrToInt) | ||||||||||
516 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) | ||||||||||
517 | if (CE->getOpcode() == Instruction::GetElementPtr && | ||||||||||
518 | CE->getOperand(0)->isNullValue()) { | ||||||||||
519 | Type *Ty = | ||||||||||
520 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); | ||||||||||
521 | if (StructType *STy = dyn_cast<StructType>(Ty)) | ||||||||||
522 | if (!STy->isPacked() && | ||||||||||
523 | CE->getNumOperands() == 3 && | ||||||||||
524 | CE->getOperand(1)->isNullValue()) { | ||||||||||
525 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) | ||||||||||
526 | if (CI->isOne() && | ||||||||||
527 | STy->getNumElements() == 2 && | ||||||||||
528 | STy->getElementType(0)->isIntegerTy(1)) { | ||||||||||
529 | AllocTy = STy->getElementType(1); | ||||||||||
530 | return true; | ||||||||||
531 | } | ||||||||||
532 | } | ||||||||||
533 | } | ||||||||||
534 | |||||||||||
535 | return false; | ||||||||||
536 | } | ||||||||||
537 | |||||||||||
538 | bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { | ||||||||||
539 | if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) | ||||||||||
540 | if (VCE->getOpcode() == Instruction::PtrToInt) | ||||||||||
541 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) | ||||||||||
542 | if (CE->getOpcode() == Instruction::GetElementPtr && | ||||||||||
543 | CE->getNumOperands() == 3 && | ||||||||||
544 | CE->getOperand(0)->isNullValue() && | ||||||||||
545 | CE->getOperand(1)->isNullValue()) { | ||||||||||
546 | Type *Ty = | ||||||||||
547 | cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); | ||||||||||
548 | // Ignore vector types here so that ScalarEvolutionExpander doesn't | ||||||||||
549 | // emit getelementptrs that index into vectors. | ||||||||||
550 | if (Ty->isStructTy() || Ty->isArrayTy()) { | ||||||||||
551 | CTy = Ty; | ||||||||||
552 | FieldNo = CE->getOperand(2); | ||||||||||
553 | return true; | ||||||||||
554 | } | ||||||||||
555 | } | ||||||||||
556 | |||||||||||
557 | return false; | ||||||||||
558 | } | ||||||||||
559 | |||||||||||
560 | //===----------------------------------------------------------------------===// | ||||||||||
561 | // SCEV Utilities | ||||||||||
562 | //===----------------------------------------------------------------------===// | ||||||||||
563 | |||||||||||
564 | /// Compare the two values \p LV and \p RV in terms of their "complexity" where | ||||||||||
565 | /// "complexity" is a partial (and somewhat ad-hoc) relation used to order | ||||||||||
566 | /// operands in SCEV expressions. \p EqCache is a set of pairs of values that | ||||||||||
567 | /// have been previously deemed to be "equally complex" by this routine. It is | ||||||||||
568 | /// intended to avoid exponential time complexity in cases like: | ||||||||||
569 | /// | ||||||||||
570 | /// %a = f(%x, %y) | ||||||||||
571 | /// %b = f(%a, %a) | ||||||||||
572 | /// %c = f(%b, %b) | ||||||||||
573 | /// | ||||||||||
574 | /// %d = f(%x, %y) | ||||||||||
575 | /// %e = f(%d, %d) | ||||||||||
576 | /// %f = f(%e, %e) | ||||||||||
577 | /// | ||||||||||
578 | /// CompareValueComplexity(%f, %c) | ||||||||||
579 | /// | ||||||||||
580 | /// Since we do not continue running this routine on expression trees once we | ||||||||||
581 | /// have seen unequal values, there is no need to track them in the cache. | ||||||||||
582 | static int | ||||||||||
583 | CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, | ||||||||||
584 | const LoopInfo *const LI, Value *LV, Value *RV, | ||||||||||
585 | unsigned Depth) { | ||||||||||
586 | if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) | ||||||||||
587 | return 0; | ||||||||||
588 | |||||||||||
589 | // Order pointer values after integer values. This helps SCEVExpander form | ||||||||||
590 | // GEPs. | ||||||||||
591 | bool LIsPointer = LV->getType()->isPointerTy(), | ||||||||||
592 | RIsPointer = RV->getType()->isPointerTy(); | ||||||||||
593 | if (LIsPointer != RIsPointer) | ||||||||||
594 | return (int)LIsPointer - (int)RIsPointer; | ||||||||||
595 | |||||||||||
596 | // Compare getValueID values. | ||||||||||
597 | unsigned LID = LV->getValueID(), RID = RV->getValueID(); | ||||||||||
598 | if (LID != RID) | ||||||||||
599 | return (int)LID - (int)RID; | ||||||||||
600 | |||||||||||
601 | // Sort arguments by their position. | ||||||||||
602 | if (const auto *LA = dyn_cast<Argument>(LV)) { | ||||||||||
603 | const auto *RA = cast<Argument>(RV); | ||||||||||
604 | unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); | ||||||||||
605 | return (int)LArgNo - (int)RArgNo; | ||||||||||
606 | } | ||||||||||
607 | |||||||||||
608 | if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { | ||||||||||
609 | const auto *RGV = cast<GlobalValue>(RV); | ||||||||||
610 | |||||||||||
611 | const auto IsGVNameSemantic = [&](const GlobalValue *GV) { | ||||||||||
612 | auto LT = GV->getLinkage(); | ||||||||||
613 | return !(GlobalValue::isPrivateLinkage(LT) || | ||||||||||
614 | GlobalValue::isInternalLinkage(LT)); | ||||||||||
615 | }; | ||||||||||
616 | |||||||||||
617 | // Use the names to distinguish the two values, but only if the | ||||||||||
618 | // names are semantically important. | ||||||||||
619 | if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) | ||||||||||
620 | return LGV->getName().compare(RGV->getName()); | ||||||||||
621 | } | ||||||||||
622 | |||||||||||
623 | // For instructions, compare their loop depth, and their operand count. This | ||||||||||
624 | // is pretty loose. | ||||||||||
625 | if (const auto *LInst = dyn_cast<Instruction>(LV)) { | ||||||||||
626 | const auto *RInst = cast<Instruction>(RV); | ||||||||||
627 | |||||||||||
628 | // Compare loop depths. | ||||||||||
629 | const BasicBlock *LParent = LInst->getParent(), | ||||||||||
630 | *RParent = RInst->getParent(); | ||||||||||
631 | if (LParent != RParent) { | ||||||||||
632 | unsigned LDepth = LI->getLoopDepth(LParent), | ||||||||||
633 | RDepth = LI->getLoopDepth(RParent); | ||||||||||
634 | if (LDepth != RDepth) | ||||||||||
635 | return (int)LDepth - (int)RDepth; | ||||||||||
636 | } | ||||||||||
637 | |||||||||||
638 | // Compare the number of operands. | ||||||||||
639 | unsigned LNumOps = LInst->getNumOperands(), | ||||||||||
640 | RNumOps = RInst->getNumOperands(); | ||||||||||
641 | if (LNumOps != RNumOps) | ||||||||||
642 | return (int)LNumOps - (int)RNumOps; | ||||||||||
643 | |||||||||||
644 | for (unsigned Idx : seq(0u, LNumOps)) { | ||||||||||
645 | int Result = | ||||||||||
646 | CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), | ||||||||||
647 | RInst->getOperand(Idx), Depth + 1); | ||||||||||
648 | if (Result != 0) | ||||||||||
649 | return Result; | ||||||||||
650 | } | ||||||||||
651 | } | ||||||||||
652 | |||||||||||
653 | EqCacheValue.unionSets(LV, RV); | ||||||||||
654 | return 0; | ||||||||||
655 | } | ||||||||||
656 | |||||||||||
657 | // Return negative, zero, or positive, if LHS is less than, equal to, or greater | ||||||||||
658 | // than RHS, respectively. A three-way result allows recursive comparisons to be | ||||||||||
659 | // more efficient. | ||||||||||
660 | static int CompareSCEVComplexity( | ||||||||||
661 | EquivalenceClasses<const SCEV *> &EqCacheSCEV, | ||||||||||
662 | EquivalenceClasses<const Value *> &EqCacheValue, | ||||||||||
663 | const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, | ||||||||||
664 | DominatorTree &DT, unsigned Depth = 0) { | ||||||||||
665 | // Fast-path: SCEVs are uniqued so we can do a quick equality check. | ||||||||||
666 | if (LHS == RHS) | ||||||||||
667 | return 0; | ||||||||||
668 | |||||||||||
669 | // Primarily, sort the SCEVs by their getSCEVType(). | ||||||||||
670 | unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); | ||||||||||
671 | if (LType != RType) | ||||||||||
672 | return (int)LType - (int)RType; | ||||||||||
673 | |||||||||||
674 | if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) | ||||||||||
675 | return 0; | ||||||||||
676 | // Aside from the getSCEVType() ordering, the particular ordering | ||||||||||
677 | // isn't very important except that it's beneficial to be consistent, | ||||||||||
678 | // so that (a + b) and (b + a) don't end up as different expressions. | ||||||||||
679 | switch (static_cast<SCEVTypes>(LType)) { | ||||||||||
680 | case scUnknown: { | ||||||||||
681 | const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); | ||||||||||
682 | const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); | ||||||||||
683 | |||||||||||
684 | int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), | ||||||||||
685 | RU->getValue(), Depth + 1); | ||||||||||
686 | if (X == 0) | ||||||||||
687 | EqCacheSCEV.unionSets(LHS, RHS); | ||||||||||
688 | return X; | ||||||||||
689 | } | ||||||||||
690 | |||||||||||
691 | case scConstant: { | ||||||||||
692 | const SCEVConstant *LC = cast<SCEVConstant>(LHS); | ||||||||||
693 | const SCEVConstant *RC = cast<SCEVConstant>(RHS); | ||||||||||
694 | |||||||||||
695 | // Compare constant values. | ||||||||||
696 | const APInt &LA = LC->getAPInt(); | ||||||||||
697 | const APInt &RA = RC->getAPInt(); | ||||||||||
698 | unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); | ||||||||||
699 | if (LBitWidth != RBitWidth) | ||||||||||
700 | return (int)LBitWidth - (int)RBitWidth; | ||||||||||
701 | return LA.ult(RA) ? -1 : 1; | ||||||||||
702 | } | ||||||||||
703 | |||||||||||
704 | case scAddRecExpr: { | ||||||||||
705 | const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); | ||||||||||
706 | const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); | ||||||||||
707 | |||||||||||
708 | // There is always a dominance between two recs that are used by one SCEV, | ||||||||||
709 | // so we can safely sort recs by loop header dominance. We require such | ||||||||||
710 | // order in getAddExpr. | ||||||||||
711 | const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); | ||||||||||
712 | if (LLoop != RLoop) { | ||||||||||
713 | const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); | ||||||||||
714 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 714, __PRETTY_FUNCTION__)); | ||||||||||
715 | if (DT.dominates(LHead, RHead)) | ||||||||||
716 | return 1; | ||||||||||
717 | else | ||||||||||
718 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 719, __PRETTY_FUNCTION__)) | ||||||||||
719 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 719, __PRETTY_FUNCTION__)); | ||||||||||
720 | return -1; | ||||||||||
721 | } | ||||||||||
722 | |||||||||||
723 | // Addrec complexity grows with operand count. | ||||||||||
724 | unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); | ||||||||||
725 | if (LNumOps != RNumOps) | ||||||||||
726 | return (int)LNumOps - (int)RNumOps; | ||||||||||
727 | |||||||||||
728 | // Lexicographically compare. | ||||||||||
729 | for (unsigned i = 0; i != LNumOps; ++i) { | ||||||||||
730 | int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, | ||||||||||
731 | LA->getOperand(i), RA->getOperand(i), DT, | ||||||||||
732 | Depth + 1); | ||||||||||
733 | if (X != 0) | ||||||||||
734 | return X; | ||||||||||
735 | } | ||||||||||
736 | EqCacheSCEV.unionSets(LHS, RHS); | ||||||||||
737 | return 0; | ||||||||||
738 | } | ||||||||||
739 | |||||||||||
740 | case scAddExpr: | ||||||||||
741 | case scMulExpr: | ||||||||||
742 | case scSMaxExpr: | ||||||||||
743 | case scUMaxExpr: | ||||||||||
744 | case scSMinExpr: | ||||||||||
745 | case scUMinExpr: { | ||||||||||
746 | const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); | ||||||||||
747 | const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); | ||||||||||
748 | |||||||||||
749 | // Lexicographically compare n-ary expressions. | ||||||||||
750 | unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); | ||||||||||
751 | if (LNumOps != RNumOps) | ||||||||||
752 | return (int)LNumOps - (int)RNumOps; | ||||||||||
753 | |||||||||||
754 | for (unsigned i = 0; i != LNumOps; ++i) { | ||||||||||
755 | int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, | ||||||||||
756 | LC->getOperand(i), RC->getOperand(i), DT, | ||||||||||
757 | Depth + 1); | ||||||||||
758 | if (X != 0) | ||||||||||
759 | return X; | ||||||||||
760 | } | ||||||||||
761 | EqCacheSCEV.unionSets(LHS, RHS); | ||||||||||
762 | return 0; | ||||||||||
763 | } | ||||||||||
764 | |||||||||||
765 | case scUDivExpr: { | ||||||||||
766 | const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); | ||||||||||
767 | const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); | ||||||||||
768 | |||||||||||
769 | // Lexicographically compare udiv expressions. | ||||||||||
770 | int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), | ||||||||||
771 | RC->getLHS(), DT, Depth + 1); | ||||||||||
772 | if (X != 0) | ||||||||||
773 | return X; | ||||||||||
774 | X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), | ||||||||||
775 | RC->getRHS(), DT, Depth + 1); | ||||||||||
776 | if (X == 0) | ||||||||||
777 | EqCacheSCEV.unionSets(LHS, RHS); | ||||||||||
778 | return X; | ||||||||||
779 | } | ||||||||||
780 | |||||||||||
781 | case scTruncate: | ||||||||||
782 | case scZeroExtend: | ||||||||||
783 | case scSignExtend: { | ||||||||||
784 | const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); | ||||||||||
785 | const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); | ||||||||||
786 | |||||||||||
787 | // Compare cast expressions by operand. | ||||||||||
788 | int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, | ||||||||||
789 | LC->getOperand(), RC->getOperand(), DT, | ||||||||||
790 | Depth + 1); | ||||||||||
791 | if (X == 0) | ||||||||||
792 | EqCacheSCEV.unionSets(LHS, RHS); | ||||||||||
793 | return X; | ||||||||||
794 | } | ||||||||||
795 | |||||||||||
796 | case scCouldNotCompute: | ||||||||||
797 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 797); | ||||||||||
798 | } | ||||||||||
799 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 799); | ||||||||||
800 | } | ||||||||||
801 | |||||||||||
802 | /// Given a list of SCEV objects, order them by their complexity, and group | ||||||||||
803 | /// objects of the same complexity together by value. When this routine is | ||||||||||
804 | /// finished, we know that any duplicates in the vector are consecutive and that | ||||||||||
805 | /// complexity is monotonically increasing. | ||||||||||
806 | /// | ||||||||||
807 | /// Note that we go take special precautions to ensure that we get deterministic | ||||||||||
808 | /// results from this routine. In other words, we don't want the results of | ||||||||||
809 | /// this to depend on where the addresses of various SCEV objects happened to | ||||||||||
810 | /// land in memory. | ||||||||||
811 | static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, | ||||||||||
812 | LoopInfo *LI, DominatorTree &DT) { | ||||||||||
813 | if (Ops.size() < 2) return; // Noop | ||||||||||
814 | |||||||||||
815 | EquivalenceClasses<const SCEV *> EqCacheSCEV; | ||||||||||
816 | EquivalenceClasses<const Value *> EqCacheValue; | ||||||||||
817 | if (Ops.size() == 2) { | ||||||||||
818 | // This is the common case, which also happens to be trivially simple. | ||||||||||
819 | // Special case it. | ||||||||||
820 | const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; | ||||||||||
821 | if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) | ||||||||||
822 | std::swap(LHS, RHS); | ||||||||||
823 | return; | ||||||||||
824 | } | ||||||||||
825 | |||||||||||
826 | // Do the rough sort by complexity. | ||||||||||
827 | llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { | ||||||||||
828 | return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < | ||||||||||
829 | 0; | ||||||||||
830 | }); | ||||||||||
831 | |||||||||||
832 | // Now that we are sorted by complexity, group elements of the same | ||||||||||
833 | // complexity. Note that this is, at worst, N^2, but the vector is likely to | ||||||||||
834 | // be extremely short in practice. Note that we take this approach because we | ||||||||||
835 | // do not want to depend on the addresses of the objects we are grouping. | ||||||||||
836 | for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { | ||||||||||
837 | const SCEV *S = Ops[i]; | ||||||||||
838 | unsigned Complexity = S->getSCEVType(); | ||||||||||
839 | |||||||||||
840 | // If there are any objects of the same complexity and same value as this | ||||||||||
841 | // one, group them. | ||||||||||
842 | for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { | ||||||||||
843 | if (Ops[j] == S) { // Found a duplicate. | ||||||||||
844 | // Move it to immediately after i'th element. | ||||||||||
845 | std::swap(Ops[i+1], Ops[j]); | ||||||||||
846 | ++i; // no need to rescan it. | ||||||||||
847 | if (i == e-2) return; // Done! | ||||||||||
848 | } | ||||||||||
849 | } | ||||||||||
850 | } | ||||||||||
851 | } | ||||||||||
852 | |||||||||||
853 | /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at | ||||||||||
854 | /// least HugeExprThreshold nodes). | ||||||||||
855 | static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { | ||||||||||
856 | return any_of(Ops, [](const SCEV *S) { | ||||||||||
857 | return S->getExpressionSize() >= HugeExprThreshold; | ||||||||||
858 | }); | ||||||||||
859 | } | ||||||||||
860 | |||||||||||
861 | //===----------------------------------------------------------------------===// | ||||||||||
862 | // Simple SCEV method implementations | ||||||||||
863 | //===----------------------------------------------------------------------===// | ||||||||||
864 | |||||||||||
865 | /// Compute BC(It, K). The result has width W. Assume, K > 0. | ||||||||||
866 | static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, | ||||||||||
867 | ScalarEvolution &SE, | ||||||||||
868 | Type *ResultTy) { | ||||||||||
869 | // Handle the simplest case efficiently. | ||||||||||
870 | if (K == 1) | ||||||||||
871 | return SE.getTruncateOrZeroExtend(It, ResultTy); | ||||||||||
872 | |||||||||||
873 | // We are using the following formula for BC(It, K): | ||||||||||
874 | // | ||||||||||
875 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! | ||||||||||
876 | // | ||||||||||
877 | // Suppose, W is the bitwidth of the return value. We must be prepared for | ||||||||||
878 | // overflow. Hence, we must assure that the result of our computation is | ||||||||||
879 | // equal to the accurate one modulo 2^W. Unfortunately, division isn't | ||||||||||
880 | // safe in modular arithmetic. | ||||||||||
881 | // | ||||||||||
882 | // However, this code doesn't use exactly that formula; the formula it uses | ||||||||||
883 | // is something like the following, where T is the number of factors of 2 in | ||||||||||
884 | // K! (i.e. trailing zeros in the binary representation of K!), and ^ is | ||||||||||
885 | // exponentiation: | ||||||||||
886 | // | ||||||||||
887 | // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) | ||||||||||
888 | // | ||||||||||
889 | // This formula is trivially equivalent to the previous formula. However, | ||||||||||
890 | // this formula can be implemented much more efficiently. The trick is that | ||||||||||
891 | // K! / 2^T is odd, and exact division by an odd number *is* safe in modular | ||||||||||
892 | // arithmetic. To do exact division in modular arithmetic, all we have | ||||||||||
893 | // to do is multiply by the inverse. Therefore, this step can be done at | ||||||||||
894 | // width W. | ||||||||||
895 | // | ||||||||||
896 | // The next issue is how to safely do the division by 2^T. The way this | ||||||||||
897 | // is done is by doing the multiplication step at a width of at least W + T | ||||||||||
898 | // bits. This way, the bottom W+T bits of the product are accurate. Then, | ||||||||||
899 | // when we perform the division by 2^T (which is equivalent to a right shift | ||||||||||
900 | // by T), the bottom W bits are accurate. Extra bits are okay; they'll get | ||||||||||
901 | // truncated out after the division by 2^T. | ||||||||||
902 | // | ||||||||||
903 | // In comparison to just directly using the first formula, this technique | ||||||||||
904 | // is much more efficient; using the first formula requires W * K bits, | ||||||||||
905 | // but this formula less than W + K bits. Also, the first formula requires | ||||||||||
906 | // a division step, whereas this formula only requires multiplies and shifts. | ||||||||||
907 | // | ||||||||||
908 | // It doesn't matter whether the subtraction step is done in the calculation | ||||||||||
909 | // width or the input iteration count's width; if the subtraction overflows, | ||||||||||
910 | // the result must be zero anyway. We prefer here to do it in the width of | ||||||||||
911 | // the induction variable because it helps a lot for certain cases; CodeGen | ||||||||||
912 | // isn't smart enough to ignore the overflow, which leads to much less | ||||||||||
913 | // efficient code if the width of the subtraction is wider than the native | ||||||||||
914 | // register width. | ||||||||||
915 | // | ||||||||||
916 | // (It's possible to not widen at all by pulling out factors of 2 before | ||||||||||
917 | // the multiplication; for example, K=2 can be calculated as | ||||||||||
918 | // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires | ||||||||||
919 | // extra arithmetic, so it's not an obvious win, and it gets | ||||||||||
920 | // much more complicated for K > 3.) | ||||||||||
921 | |||||||||||
922 | // Protection from insane SCEVs; this bound is conservative, | ||||||||||
923 | // but it probably doesn't matter. | ||||||||||
924 | if (K > 1000) | ||||||||||
925 | return SE.getCouldNotCompute(); | ||||||||||
926 | |||||||||||
927 | unsigned W = SE.getTypeSizeInBits(ResultTy); | ||||||||||
928 | |||||||||||
929 | // Calculate K! / 2^T and T; we divide out the factors of two before | ||||||||||
930 | // multiplying for calculating K! / 2^T to avoid overflow. | ||||||||||
931 | // Other overflow doesn't matter because we only care about the bottom | ||||||||||
932 | // W bits of the result. | ||||||||||
933 | APInt OddFactorial(W, 1); | ||||||||||
934 | unsigned T = 1; | ||||||||||
935 | for (unsigned i = 3; i <= K; ++i) { | ||||||||||
936 | APInt Mult(W, i); | ||||||||||
937 | unsigned TwoFactors = Mult.countTrailingZeros(); | ||||||||||
938 | T += TwoFactors; | ||||||||||
939 | Mult.lshrInPlace(TwoFactors); | ||||||||||
940 | OddFactorial *= Mult; | ||||||||||
941 | } | ||||||||||
942 | |||||||||||
943 | // We need at least W + T bits for the multiplication step | ||||||||||
944 | unsigned CalculationBits = W + T; | ||||||||||
945 | |||||||||||
946 | // Calculate 2^T, at width T+W. | ||||||||||
947 | APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); | ||||||||||
948 | |||||||||||
949 | // Calculate the multiplicative inverse of K! / 2^T; | ||||||||||
950 | // this multiplication factor will perform the exact division by | ||||||||||
951 | // K! / 2^T. | ||||||||||
952 | APInt Mod = APInt::getSignedMinValue(W+1); | ||||||||||
953 | APInt MultiplyFactor = OddFactorial.zext(W+1); | ||||||||||
954 | MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); | ||||||||||
955 | MultiplyFactor = MultiplyFactor.trunc(W); | ||||||||||
956 | |||||||||||
957 | // Calculate the product, at width T+W | ||||||||||
958 | IntegerType *CalculationTy = IntegerType::get(SE.getContext(), | ||||||||||
959 | CalculationBits); | ||||||||||
960 | const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); | ||||||||||
961 | for (unsigned i = 1; i != K; ++i) { | ||||||||||
962 | const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); | ||||||||||
963 | Dividend = SE.getMulExpr(Dividend, | ||||||||||
964 | SE.getTruncateOrZeroExtend(S, CalculationTy)); | ||||||||||
965 | } | ||||||||||
966 | |||||||||||
967 | // Divide by 2^T | ||||||||||
968 | const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); | ||||||||||
969 | |||||||||||
970 | // Truncate the result, and divide by K! / 2^T. | ||||||||||
971 | |||||||||||
972 | return SE.getMulExpr(SE.getConstant(MultiplyFactor), | ||||||||||
973 | SE.getTruncateOrZeroExtend(DivResult, ResultTy)); | ||||||||||
974 | } | ||||||||||
975 | |||||||||||
976 | /// Return the value of this chain of recurrences at the specified iteration | ||||||||||
977 | /// number. We can evaluate this recurrence by multiplying each element in the | ||||||||||
978 | /// chain by the binomial coefficient corresponding to it. In other words, we | ||||||||||
979 | /// can evaluate {A,+,B,+,C,+,D} as: | ||||||||||
980 | /// | ||||||||||
981 | /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) | ||||||||||
982 | /// | ||||||||||
983 | /// where BC(It, k) stands for binomial coefficient. | ||||||||||
984 | const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, | ||||||||||
985 | ScalarEvolution &SE) const { | ||||||||||
986 | const SCEV *Result = getStart(); | ||||||||||
987 | for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { | ||||||||||
988 | // The computation is correct in the face of overflow provided that the | ||||||||||
989 | // multiplication is performed _after_ the evaluation of the binomial | ||||||||||
990 | // coefficient. | ||||||||||
991 | const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); | ||||||||||
992 | if (isa<SCEVCouldNotCompute>(Coeff)) | ||||||||||
993 | return Coeff; | ||||||||||
994 | |||||||||||
995 | Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); | ||||||||||
996 | } | ||||||||||
997 | return Result; | ||||||||||
998 | } | ||||||||||
999 | |||||||||||
1000 | //===----------------------------------------------------------------------===// | ||||||||||
1001 | // SCEV Expression folder implementations | ||||||||||
1002 | //===----------------------------------------------------------------------===// | ||||||||||
1003 | |||||||||||
1004 | const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, | ||||||||||
1005 | unsigned Depth) { | ||||||||||
1006 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1007, __PRETTY_FUNCTION__)) | ||||||||||
1007 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1007, __PRETTY_FUNCTION__)); | ||||||||||
1008 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1009, __PRETTY_FUNCTION__)) | ||||||||||
1009 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1009, __PRETTY_FUNCTION__)); | ||||||||||
1010 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
1011 | |||||||||||
1012 | FoldingSetNodeID ID; | ||||||||||
1013 | ID.AddInteger(scTruncate); | ||||||||||
1014 | ID.AddPointer(Op); | ||||||||||
1015 | ID.AddPointer(Ty); | ||||||||||
1016 | void *IP = nullptr; | ||||||||||
1017 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
1018 | |||||||||||
1019 | // Fold if the operand is constant. | ||||||||||
1020 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) | ||||||||||
1021 | return getConstant( | ||||||||||
1022 | cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); | ||||||||||
1023 | |||||||||||
1024 | // trunc(trunc(x)) --> trunc(x) | ||||||||||
1025 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) | ||||||||||
1026 | return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); | ||||||||||
1027 | |||||||||||
1028 | // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing | ||||||||||
1029 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) | ||||||||||
1030 | return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); | ||||||||||
1031 | |||||||||||
1032 | // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing | ||||||||||
1033 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) | ||||||||||
1034 | return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); | ||||||||||
1035 | |||||||||||
1036 | if (Depth > MaxCastDepth) { | ||||||||||
1037 | SCEV *S = | ||||||||||
1038 | new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); | ||||||||||
1039 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1040 | addToLoopUseLists(S); | ||||||||||
1041 | return S; | ||||||||||
1042 | } | ||||||||||
1043 | |||||||||||
1044 | // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and | ||||||||||
1045 | // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), | ||||||||||
1046 | // if after transforming we have at most one truncate, not counting truncates | ||||||||||
1047 | // that replace other casts. | ||||||||||
1048 | if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { | ||||||||||
1049 | auto *CommOp = cast<SCEVCommutativeExpr>(Op); | ||||||||||
1050 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
1051 | unsigned numTruncs = 0; | ||||||||||
1052 | for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; | ||||||||||
1053 | ++i) { | ||||||||||
1054 | const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); | ||||||||||
1055 | if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) | ||||||||||
1056 | numTruncs++; | ||||||||||
1057 | Operands.push_back(S); | ||||||||||
1058 | } | ||||||||||
1059 | if (numTruncs < 2) { | ||||||||||
1060 | if (isa<SCEVAddExpr>(Op)) | ||||||||||
1061 | return getAddExpr(Operands); | ||||||||||
1062 | else if (isa<SCEVMulExpr>(Op)) | ||||||||||
1063 | return getMulExpr(Operands); | ||||||||||
1064 | else | ||||||||||
1065 | llvm_unreachable("Unexpected SCEV type for Op.")::llvm::llvm_unreachable_internal("Unexpected SCEV type for Op." , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1065); | ||||||||||
1066 | } | ||||||||||
1067 | // Although we checked in the beginning that ID is not in the cache, it is | ||||||||||
1068 | // possible that during recursion and different modification ID was inserted | ||||||||||
1069 | // into the cache. So if we find it, just return it. | ||||||||||
1070 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) | ||||||||||
1071 | return S; | ||||||||||
1072 | } | ||||||||||
1073 | |||||||||||
1074 | // If the input value is a chrec scev, truncate the chrec's operands. | ||||||||||
1075 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { | ||||||||||
1076 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
1077 | for (const SCEV *Op : AddRec->operands()) | ||||||||||
1078 | Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); | ||||||||||
1079 | return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); | ||||||||||
1080 | } | ||||||||||
1081 | |||||||||||
1082 | // The cast wasn't folded; create an explicit cast node. We can reuse | ||||||||||
1083 | // the existing insert position since if we get here, we won't have | ||||||||||
1084 | // made any changes which would invalidate it. | ||||||||||
1085 | SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), | ||||||||||
1086 | Op, Ty); | ||||||||||
1087 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1088 | addToLoopUseLists(S); | ||||||||||
1089 | return S; | ||||||||||
1090 | } | ||||||||||
1091 | |||||||||||
1092 | // Get the limit of a recurrence such that incrementing by Step cannot cause | ||||||||||
1093 | // signed overflow as long as the value of the recurrence within the | ||||||||||
1094 | // loop does not exceed this limit before incrementing. | ||||||||||
1095 | static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, | ||||||||||
1096 | ICmpInst::Predicate *Pred, | ||||||||||
1097 | ScalarEvolution *SE) { | ||||||||||
1098 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); | ||||||||||
1099 | if (SE->isKnownPositive(Step)) { | ||||||||||
1100 | *Pred = ICmpInst::ICMP_SLT; | ||||||||||
1101 | return SE->getConstant(APInt::getSignedMinValue(BitWidth) - | ||||||||||
1102 | SE->getSignedRangeMax(Step)); | ||||||||||
1103 | } | ||||||||||
1104 | if (SE->isKnownNegative(Step)) { | ||||||||||
1105 | *Pred = ICmpInst::ICMP_SGT; | ||||||||||
1106 | return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - | ||||||||||
1107 | SE->getSignedRangeMin(Step)); | ||||||||||
1108 | } | ||||||||||
1109 | return nullptr; | ||||||||||
1110 | } | ||||||||||
1111 | |||||||||||
1112 | // Get the limit of a recurrence such that incrementing by Step cannot cause | ||||||||||
1113 | // unsigned overflow as long as the value of the recurrence within the loop does | ||||||||||
1114 | // not exceed this limit before incrementing. | ||||||||||
1115 | static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, | ||||||||||
1116 | ICmpInst::Predicate *Pred, | ||||||||||
1117 | ScalarEvolution *SE) { | ||||||||||
1118 | unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); | ||||||||||
1119 | *Pred = ICmpInst::ICMP_ULT; | ||||||||||
1120 | |||||||||||
1121 | return SE->getConstant(APInt::getMinValue(BitWidth) - | ||||||||||
1122 | SE->getUnsignedRangeMax(Step)); | ||||||||||
1123 | } | ||||||||||
1124 | |||||||||||
1125 | namespace { | ||||||||||
1126 | |||||||||||
1127 | struct ExtendOpTraitsBase { | ||||||||||
1128 | typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, | ||||||||||
1129 | unsigned); | ||||||||||
1130 | }; | ||||||||||
1131 | |||||||||||
1132 | // Used to make code generic over signed and unsigned overflow. | ||||||||||
1133 | template <typename ExtendOp> struct ExtendOpTraits { | ||||||||||
1134 | // Members present: | ||||||||||
1135 | // | ||||||||||
1136 | // static const SCEV::NoWrapFlags WrapType; | ||||||||||
1137 | // | ||||||||||
1138 | // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; | ||||||||||
1139 | // | ||||||||||
1140 | // static const SCEV *getOverflowLimitForStep(const SCEV *Step, | ||||||||||
1141 | // ICmpInst::Predicate *Pred, | ||||||||||
1142 | // ScalarEvolution *SE); | ||||||||||
1143 | }; | ||||||||||
1144 | |||||||||||
1145 | template <> | ||||||||||
1146 | struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { | ||||||||||
1147 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; | ||||||||||
1148 | |||||||||||
1149 | static const GetExtendExprTy GetExtendExpr; | ||||||||||
1150 | |||||||||||
1151 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, | ||||||||||
1152 | ICmpInst::Predicate *Pred, | ||||||||||
1153 | ScalarEvolution *SE) { | ||||||||||
1154 | return getSignedOverflowLimitForStep(Step, Pred, SE); | ||||||||||
1155 | } | ||||||||||
1156 | }; | ||||||||||
1157 | |||||||||||
1158 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< | ||||||||||
1159 | SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; | ||||||||||
1160 | |||||||||||
1161 | template <> | ||||||||||
1162 | struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { | ||||||||||
1163 | static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; | ||||||||||
1164 | |||||||||||
1165 | static const GetExtendExprTy GetExtendExpr; | ||||||||||
1166 | |||||||||||
1167 | static const SCEV *getOverflowLimitForStep(const SCEV *Step, | ||||||||||
1168 | ICmpInst::Predicate *Pred, | ||||||||||
1169 | ScalarEvolution *SE) { | ||||||||||
1170 | return getUnsignedOverflowLimitForStep(Step, Pred, SE); | ||||||||||
1171 | } | ||||||||||
1172 | }; | ||||||||||
1173 | |||||||||||
1174 | const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< | ||||||||||
1175 | SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; | ||||||||||
1176 | |||||||||||
1177 | } // end anonymous namespace | ||||||||||
1178 | |||||||||||
1179 | // The recurrence AR has been shown to have no signed/unsigned wrap or something | ||||||||||
1180 | // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as | ||||||||||
1181 | // easily prove NSW/NUW for its preincrement or postincrement sibling. This | ||||||||||
1182 | // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + | ||||||||||
1183 | // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the | ||||||||||
1184 | // expression "Step + sext/zext(PreIncAR)" is congruent with | ||||||||||
1185 | // "sext/zext(PostIncAR)" | ||||||||||
1186 | template <typename ExtendOpTy> | ||||||||||
1187 | static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, | ||||||||||
1188 | ScalarEvolution *SE, unsigned Depth) { | ||||||||||
1189 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; | ||||||||||
1190 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; | ||||||||||
1191 | |||||||||||
1192 | const Loop *L = AR->getLoop(); | ||||||||||
1193 | const SCEV *Start = AR->getStart(); | ||||||||||
1194 | const SCEV *Step = AR->getStepRecurrence(*SE); | ||||||||||
1195 | |||||||||||
1196 | // Check for a simple looking step prior to loop entry. | ||||||||||
1197 | const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); | ||||||||||
1198 | if (!SA) | ||||||||||
1199 | return nullptr; | ||||||||||
1200 | |||||||||||
1201 | // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV | ||||||||||
1202 | // subtraction is expensive. For this purpose, perform a quick and dirty | ||||||||||
1203 | // difference, by checking for Step in the operand list. | ||||||||||
1204 | SmallVector<const SCEV *, 4> DiffOps; | ||||||||||
1205 | for (const SCEV *Op : SA->operands()) | ||||||||||
1206 | if (Op != Step) | ||||||||||
1207 | DiffOps.push_back(Op); | ||||||||||
1208 | |||||||||||
1209 | if (DiffOps.size() == SA->getNumOperands()) | ||||||||||
1210 | return nullptr; | ||||||||||
1211 | |||||||||||
1212 | // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + | ||||||||||
1213 | // `Step`: | ||||||||||
1214 | |||||||||||
1215 | // 1. NSW/NUW flags on the step increment. | ||||||||||
1216 | auto PreStartFlags = | ||||||||||
1217 | ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); | ||||||||||
1218 | const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); | ||||||||||
1219 | const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( | ||||||||||
1220 | SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); | ||||||||||
1221 | |||||||||||
1222 | // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies | ||||||||||
1223 | // "S+X does not sign/unsign-overflow". | ||||||||||
1224 | // | ||||||||||
1225 | |||||||||||
1226 | const SCEV *BECount = SE->getBackedgeTakenCount(L); | ||||||||||
1227 | if (PreAR && PreAR->getNoWrapFlags(WrapType) && | ||||||||||
1228 | !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) | ||||||||||
1229 | return PreStart; | ||||||||||
1230 | |||||||||||
1231 | // 2. Direct overflow check on the step operation's expression. | ||||||||||
1232 | unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); | ||||||||||
1233 | Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); | ||||||||||
1234 | const SCEV *OperandExtendedStart = | ||||||||||
1235 | SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), | ||||||||||
1236 | (SE->*GetExtendExpr)(Step, WideTy, Depth)); | ||||||||||
1237 | if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { | ||||||||||
1238 | if (PreAR && AR->getNoWrapFlags(WrapType)) { | ||||||||||
1239 | // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW | ||||||||||
1240 | // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then | ||||||||||
1241 | // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. | ||||||||||
1242 | const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); | ||||||||||
1243 | } | ||||||||||
1244 | return PreStart; | ||||||||||
1245 | } | ||||||||||
1246 | |||||||||||
1247 | // 3. Loop precondition. | ||||||||||
1248 | ICmpInst::Predicate Pred; | ||||||||||
1249 | const SCEV *OverflowLimit = | ||||||||||
1250 | ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); | ||||||||||
1251 | |||||||||||
1252 | if (OverflowLimit && | ||||||||||
1253 | SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) | ||||||||||
1254 | return PreStart; | ||||||||||
1255 | |||||||||||
1256 | return nullptr; | ||||||||||
1257 | } | ||||||||||
1258 | |||||||||||
1259 | // Get the normalized zero or sign extended expression for this AddRec's Start. | ||||||||||
1260 | template <typename ExtendOpTy> | ||||||||||
1261 | static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, | ||||||||||
1262 | ScalarEvolution *SE, | ||||||||||
1263 | unsigned Depth) { | ||||||||||
1264 | auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; | ||||||||||
1265 | |||||||||||
1266 | const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); | ||||||||||
1267 | if (!PreStart) | ||||||||||
1268 | return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); | ||||||||||
1269 | |||||||||||
1270 | return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, | ||||||||||
1271 | Depth), | ||||||||||
1272 | (SE->*GetExtendExpr)(PreStart, Ty, Depth)); | ||||||||||
1273 | } | ||||||||||
1274 | |||||||||||
1275 | // Try to prove away overflow by looking at "nearby" add recurrences. A | ||||||||||
1276 | // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it | ||||||||||
1277 | // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. | ||||||||||
1278 | // | ||||||||||
1279 | // Formally: | ||||||||||
1280 | // | ||||||||||
1281 | // {S,+,X} == {S-T,+,X} + T | ||||||||||
1282 | // => Ext({S,+,X}) == Ext({S-T,+,X} + T) | ||||||||||
1283 | // | ||||||||||
1284 | // If ({S-T,+,X} + T) does not overflow ... (1) | ||||||||||
1285 | // | ||||||||||
1286 | // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) | ||||||||||
1287 | // | ||||||||||
1288 | // If {S-T,+,X} does not overflow ... (2) | ||||||||||
1289 | // | ||||||||||
1290 | // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) | ||||||||||
1291 | // == {Ext(S-T)+Ext(T),+,Ext(X)} | ||||||||||
1292 | // | ||||||||||
1293 | // If (S-T)+T does not overflow ... (3) | ||||||||||
1294 | // | ||||||||||
1295 | // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} | ||||||||||
1296 | // == {Ext(S),+,Ext(X)} == LHS | ||||||||||
1297 | // | ||||||||||
1298 | // Thus, if (1), (2) and (3) are true for some T, then | ||||||||||
1299 | // Ext({S,+,X}) == {Ext(S),+,Ext(X)} | ||||||||||
1300 | // | ||||||||||
1301 | // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) | ||||||||||
1302 | // does not overflow" restricted to the 0th iteration. Therefore we only need | ||||||||||
1303 | // to check for (1) and (2). | ||||||||||
1304 | // | ||||||||||
1305 | // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T | ||||||||||
1306 | // is `Delta` (defined below). | ||||||||||
1307 | template <typename ExtendOpTy> | ||||||||||
1308 | bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, | ||||||||||
1309 | const SCEV *Step, | ||||||||||
1310 | const Loop *L) { | ||||||||||
1311 | auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; | ||||||||||
1312 | |||||||||||
1313 | // We restrict `Start` to a constant to prevent SCEV from spending too much | ||||||||||
1314 | // time here. It is correct (but more expensive) to continue with a | ||||||||||
1315 | // non-constant `Start` and do a general SCEV subtraction to compute | ||||||||||
1316 | // `PreStart` below. | ||||||||||
1317 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); | ||||||||||
1318 | if (!StartC) | ||||||||||
1319 | return false; | ||||||||||
1320 | |||||||||||
1321 | APInt StartAI = StartC->getAPInt(); | ||||||||||
1322 | |||||||||||
1323 | for (unsigned Delta : {-2, -1, 1, 2}) { | ||||||||||
1324 | const SCEV *PreStart = getConstant(StartAI - Delta); | ||||||||||
1325 | |||||||||||
1326 | FoldingSetNodeID ID; | ||||||||||
1327 | ID.AddInteger(scAddRecExpr); | ||||||||||
1328 | ID.AddPointer(PreStart); | ||||||||||
1329 | ID.AddPointer(Step); | ||||||||||
1330 | ID.AddPointer(L); | ||||||||||
1331 | void *IP = nullptr; | ||||||||||
1332 | const auto *PreAR = | ||||||||||
1333 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); | ||||||||||
1334 | |||||||||||
1335 | // Give up if we don't already have the add recurrence we need because | ||||||||||
1336 | // actually constructing an add recurrence is relatively expensive. | ||||||||||
1337 | if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) | ||||||||||
1338 | const SCEV *DeltaS = getConstant(StartC->getType(), Delta); | ||||||||||
1339 | ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; | ||||||||||
1340 | const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( | ||||||||||
1341 | DeltaS, &Pred, this); | ||||||||||
1342 | if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) | ||||||||||
1343 | return true; | ||||||||||
1344 | } | ||||||||||
1345 | } | ||||||||||
1346 | |||||||||||
1347 | return false; | ||||||||||
1348 | } | ||||||||||
1349 | |||||||||||
1350 | // Finds an integer D for an expression (C + x + y + ...) such that the top | ||||||||||
1351 | // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or | ||||||||||
1352 | // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is | ||||||||||
1353 | // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and | ||||||||||
1354 | // the (C + x + y + ...) expression is \p WholeAddExpr. | ||||||||||
1355 | static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, | ||||||||||
1356 | const SCEVConstant *ConstantTerm, | ||||||||||
1357 | const SCEVAddExpr *WholeAddExpr) { | ||||||||||
1358 | const APInt &C = ConstantTerm->getAPInt(); | ||||||||||
1359 | const unsigned BitWidth = C.getBitWidth(); | ||||||||||
1360 | // Find number of trailing zeros of (x + y + ...) w/o the C first: | ||||||||||
1361 | uint32_t TZ = BitWidth; | ||||||||||
1362 | for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) | ||||||||||
1363 | TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); | ||||||||||
1364 | if (TZ) { | ||||||||||
1365 | // Set D to be as many least significant bits of C as possible while still | ||||||||||
1366 | // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: | ||||||||||
1367 | return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; | ||||||||||
1368 | } | ||||||||||
1369 | return APInt(BitWidth, 0); | ||||||||||
1370 | } | ||||||||||
1371 | |||||||||||
1372 | // Finds an integer D for an affine AddRec expression {C,+,x} such that the top | ||||||||||
1373 | // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the | ||||||||||
1374 | // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p | ||||||||||
1375 | // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. | ||||||||||
1376 | static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, | ||||||||||
1377 | const APInt &ConstantStart, | ||||||||||
1378 | const SCEV *Step) { | ||||||||||
1379 | const unsigned BitWidth = ConstantStart.getBitWidth(); | ||||||||||
1380 | const uint32_t TZ = SE.GetMinTrailingZeros(Step); | ||||||||||
1381 | if (TZ) | ||||||||||
1382 | return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) | ||||||||||
1383 | : ConstantStart; | ||||||||||
1384 | return APInt(BitWidth, 0); | ||||||||||
1385 | } | ||||||||||
1386 | |||||||||||
1387 | const SCEV * | ||||||||||
1388 | ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { | ||||||||||
1389 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1390, __PRETTY_FUNCTION__)) | ||||||||||
1390 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1390, __PRETTY_FUNCTION__)); | ||||||||||
1391 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1392, __PRETTY_FUNCTION__)) | ||||||||||
1392 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1392, __PRETTY_FUNCTION__)); | ||||||||||
1393 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
1394 | |||||||||||
1395 | // Fold if the operand is constant. | ||||||||||
1396 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) | ||||||||||
1397 | return getConstant( | ||||||||||
1398 | cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); | ||||||||||
1399 | |||||||||||
1400 | // zext(zext(x)) --> zext(x) | ||||||||||
1401 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) | ||||||||||
1402 | return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); | ||||||||||
1403 | |||||||||||
1404 | // Before doing any expensive analysis, check to see if we've already | ||||||||||
1405 | // computed a SCEV for this Op and Ty. | ||||||||||
1406 | FoldingSetNodeID ID; | ||||||||||
1407 | ID.AddInteger(scZeroExtend); | ||||||||||
1408 | ID.AddPointer(Op); | ||||||||||
1409 | ID.AddPointer(Ty); | ||||||||||
1410 | void *IP = nullptr; | ||||||||||
1411 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
1412 | if (Depth > MaxCastDepth) { | ||||||||||
1413 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), | ||||||||||
1414 | Op, Ty); | ||||||||||
1415 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1416 | addToLoopUseLists(S); | ||||||||||
1417 | return S; | ||||||||||
1418 | } | ||||||||||
1419 | |||||||||||
1420 | // zext(trunc(x)) --> zext(x) or x or trunc(x) | ||||||||||
1421 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { | ||||||||||
1422 | // It's possible the bits taken off by the truncate were all zero bits. If | ||||||||||
1423 | // so, we should be able to simplify this further. | ||||||||||
1424 | const SCEV *X = ST->getOperand(); | ||||||||||
1425 | ConstantRange CR = getUnsignedRange(X); | ||||||||||
1426 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); | ||||||||||
1427 | unsigned NewBits = getTypeSizeInBits(Ty); | ||||||||||
1428 | if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( | ||||||||||
1429 | CR.zextOrTrunc(NewBits))) | ||||||||||
1430 | return getTruncateOrZeroExtend(X, Ty, Depth); | ||||||||||
1431 | } | ||||||||||
1432 | |||||||||||
1433 | // If the input value is a chrec scev, and we can prove that the value | ||||||||||
1434 | // did not overflow the old, smaller, value, we can zero extend all of the | ||||||||||
1435 | // operands (often constants). This allows analysis of something like | ||||||||||
1436 | // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } | ||||||||||
1437 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) | ||||||||||
1438 | if (AR->isAffine()) { | ||||||||||
1439 | const SCEV *Start = AR->getStart(); | ||||||||||
1440 | const SCEV *Step = AR->getStepRecurrence(*this); | ||||||||||
1441 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); | ||||||||||
1442 | const Loop *L = AR->getLoop(); | ||||||||||
1443 | |||||||||||
1444 | if (!AR->hasNoUnsignedWrap()) { | ||||||||||
1445 | auto NewFlags = proveNoWrapViaConstantRanges(AR); | ||||||||||
1446 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); | ||||||||||
1447 | } | ||||||||||
1448 | |||||||||||
1449 | // If we have special knowledge that this addrec won't overflow, | ||||||||||
1450 | // we don't need to do any further analysis. | ||||||||||
1451 | if (AR->hasNoUnsignedWrap()) | ||||||||||
1452 | return getAddRecExpr( | ||||||||||
1453 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), | ||||||||||
1454 | getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); | ||||||||||
1455 | |||||||||||
1456 | // Check whether the backedge-taken count is SCEVCouldNotCompute. | ||||||||||
1457 | // Note that this serves two purposes: It filters out loops that are | ||||||||||
1458 | // simply not analyzable, and it covers the case where this code is | ||||||||||
1459 | // being called from within backedge-taken count analysis, such that | ||||||||||
1460 | // attempting to ask for the backedge-taken count would likely result | ||||||||||
1461 | // in infinite recursion. In the later case, the analysis code will | ||||||||||
1462 | // cope with a conservative value, and it will take care to purge | ||||||||||
1463 | // that value once it has finished. | ||||||||||
1464 | const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); | ||||||||||
1465 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { | ||||||||||
1466 | // Manually compute the final value for AR, checking for | ||||||||||
1467 | // overflow. | ||||||||||
1468 | |||||||||||
1469 | // Check whether the backedge-taken count can be losslessly casted to | ||||||||||
1470 | // the addrec's type. The count is always unsigned. | ||||||||||
1471 | const SCEV *CastedMaxBECount = | ||||||||||
1472 | getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); | ||||||||||
1473 | const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( | ||||||||||
1474 | CastedMaxBECount, MaxBECount->getType(), Depth); | ||||||||||
1475 | if (MaxBECount == RecastedMaxBECount) { | ||||||||||
1476 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); | ||||||||||
1477 | // Check whether Start+Step*MaxBECount has no unsigned overflow. | ||||||||||
1478 | const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, | ||||||||||
1479 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1480 | const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, | ||||||||||
1481 | SCEV::FlagAnyWrap, | ||||||||||
1482 | Depth + 1), | ||||||||||
1483 | WideTy, Depth + 1); | ||||||||||
1484 | const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); | ||||||||||
1485 | const SCEV *WideMaxBECount = | ||||||||||
1486 | getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); | ||||||||||
1487 | const SCEV *OperandExtendedAdd = | ||||||||||
1488 | getAddExpr(WideStart, | ||||||||||
1489 | getMulExpr(WideMaxBECount, | ||||||||||
1490 | getZeroExtendExpr(Step, WideTy, Depth + 1), | ||||||||||
1491 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
1492 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1493 | if (ZAdd == OperandExtendedAdd) { | ||||||||||
1494 | // Cache knowledge of AR NUW, which is propagated to this AddRec. | ||||||||||
1495 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); | ||||||||||
1496 | // Return the expression with the addrec on the outside. | ||||||||||
1497 | return getAddRecExpr( | ||||||||||
1498 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, | ||||||||||
1499 | Depth + 1), | ||||||||||
1500 | getZeroExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1501 | AR->getNoWrapFlags()); | ||||||||||
1502 | } | ||||||||||
1503 | // Similar to above, only this time treat the step value as signed. | ||||||||||
1504 | // This covers loops that count down. | ||||||||||
1505 | OperandExtendedAdd = | ||||||||||
1506 | getAddExpr(WideStart, | ||||||||||
1507 | getMulExpr(WideMaxBECount, | ||||||||||
1508 | getSignExtendExpr(Step, WideTy, Depth + 1), | ||||||||||
1509 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
1510 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1511 | if (ZAdd == OperandExtendedAdd) { | ||||||||||
1512 | // Cache knowledge of AR NW, which is propagated to this AddRec. | ||||||||||
1513 | // Negative step causes unsigned wrap, but it still can't self-wrap. | ||||||||||
1514 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); | ||||||||||
1515 | // Return the expression with the addrec on the outside. | ||||||||||
1516 | return getAddRecExpr( | ||||||||||
1517 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, | ||||||||||
1518 | Depth + 1), | ||||||||||
1519 | getSignExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1520 | AR->getNoWrapFlags()); | ||||||||||
1521 | } | ||||||||||
1522 | } | ||||||||||
1523 | } | ||||||||||
1524 | |||||||||||
1525 | // Normally, in the cases we can prove no-overflow via a | ||||||||||
1526 | // backedge guarding condition, we can also compute a backedge | ||||||||||
1527 | // taken count for the loop. The exceptions are assumptions and | ||||||||||
1528 | // guards present in the loop -- SCEV is not great at exploiting | ||||||||||
1529 | // these to compute max backedge taken counts, but can still use | ||||||||||
1530 | // these to prove lack of overflow. Use this fact to avoid | ||||||||||
1531 | // doing extra work that may not pay off. | ||||||||||
1532 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || | ||||||||||
1533 | !AC.assumptions().empty()) { | ||||||||||
1534 | // If the backedge is guarded by a comparison with the pre-inc | ||||||||||
1535 | // value the addrec is safe. Also, if the entry is guarded by | ||||||||||
1536 | // a comparison with the start value and the backedge is | ||||||||||
1537 | // guarded by a comparison with the post-inc value, the addrec | ||||||||||
1538 | // is safe. | ||||||||||
1539 | if (isKnownPositive(Step)) { | ||||||||||
1540 | const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - | ||||||||||
1541 | getUnsignedRangeMax(Step)); | ||||||||||
1542 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || | ||||||||||
1543 | isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { | ||||||||||
1544 | // Cache knowledge of AR NUW, which is propagated to this | ||||||||||
1545 | // AddRec. | ||||||||||
1546 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); | ||||||||||
1547 | // Return the expression with the addrec on the outside. | ||||||||||
1548 | return getAddRecExpr( | ||||||||||
1549 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, | ||||||||||
1550 | Depth + 1), | ||||||||||
1551 | getZeroExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1552 | AR->getNoWrapFlags()); | ||||||||||
1553 | } | ||||||||||
1554 | } else if (isKnownNegative(Step)) { | ||||||||||
1555 | const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - | ||||||||||
1556 | getSignedRangeMin(Step)); | ||||||||||
1557 | if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || | ||||||||||
1558 | isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { | ||||||||||
1559 | // Cache knowledge of AR NW, which is propagated to this | ||||||||||
1560 | // AddRec. Negative step causes unsigned wrap, but it | ||||||||||
1561 | // still can't self-wrap. | ||||||||||
1562 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); | ||||||||||
1563 | // Return the expression with the addrec on the outside. | ||||||||||
1564 | return getAddRecExpr( | ||||||||||
1565 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, | ||||||||||
1566 | Depth + 1), | ||||||||||
1567 | getSignExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1568 | AR->getNoWrapFlags()); | ||||||||||
1569 | } | ||||||||||
1570 | } | ||||||||||
1571 | } | ||||||||||
1572 | |||||||||||
1573 | // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> | ||||||||||
1574 | // if D + (C - D + Step * n) could be proven to not unsigned wrap | ||||||||||
1575 | // where D maximizes the number of trailing zeros of (C - D + Step * n) | ||||||||||
1576 | if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { | ||||||||||
1577 | const APInt &C = SC->getAPInt(); | ||||||||||
1578 | const APInt &D = extractConstantWithoutWrapping(*this, C, Step); | ||||||||||
1579 | if (D != 0) { | ||||||||||
1580 | const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); | ||||||||||
1581 | const SCEV *SResidual = | ||||||||||
1582 | getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); | ||||||||||
1583 | const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); | ||||||||||
1584 | return getAddExpr(SZExtD, SZExtR, | ||||||||||
1585 | (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), | ||||||||||
1586 | Depth + 1); | ||||||||||
1587 | } | ||||||||||
1588 | } | ||||||||||
1589 | |||||||||||
1590 | if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { | ||||||||||
1591 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); | ||||||||||
1592 | return getAddRecExpr( | ||||||||||
1593 | getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), | ||||||||||
1594 | getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); | ||||||||||
1595 | } | ||||||||||
1596 | } | ||||||||||
1597 | |||||||||||
1598 | // zext(A % B) --> zext(A) % zext(B) | ||||||||||
1599 | { | ||||||||||
1600 | const SCEV *LHS; | ||||||||||
1601 | const SCEV *RHS; | ||||||||||
1602 | if (matchURem(Op, LHS, RHS)) | ||||||||||
1603 | return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), | ||||||||||
1604 | getZeroExtendExpr(RHS, Ty, Depth + 1)); | ||||||||||
1605 | } | ||||||||||
1606 | |||||||||||
1607 | // zext(A / B) --> zext(A) / zext(B). | ||||||||||
1608 | if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) | ||||||||||
1609 | return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), | ||||||||||
1610 | getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); | ||||||||||
1611 | |||||||||||
1612 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { | ||||||||||
1613 | // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> | ||||||||||
1614 | if (SA->hasNoUnsignedWrap()) { | ||||||||||
1615 | // If the addition does not unsign overflow then we can, by definition, | ||||||||||
1616 | // commute the zero extension with the addition operation. | ||||||||||
1617 | SmallVector<const SCEV *, 4> Ops; | ||||||||||
1618 | for (const auto *Op : SA->operands()) | ||||||||||
1619 | Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); | ||||||||||
1620 | return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); | ||||||||||
1621 | } | ||||||||||
1622 | |||||||||||
1623 | // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) | ||||||||||
1624 | // if D + (C - D + x + y + ...) could be proven to not unsigned wrap | ||||||||||
1625 | // where D maximizes the number of trailing zeros of (C - D + x + y + ...) | ||||||||||
1626 | // | ||||||||||
1627 | // Often address arithmetics contain expressions like | ||||||||||
1628 | // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). | ||||||||||
1629 | // This transformation is useful while proving that such expressions are | ||||||||||
1630 | // equal or differ by a small constant amount, see LoadStoreVectorizer pass. | ||||||||||
1631 | if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { | ||||||||||
1632 | const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); | ||||||||||
1633 | if (D != 0) { | ||||||||||
1634 | const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); | ||||||||||
1635 | const SCEV *SResidual = | ||||||||||
1636 | getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); | ||||||||||
1637 | const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); | ||||||||||
1638 | return getAddExpr(SZExtD, SZExtR, | ||||||||||
1639 | (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), | ||||||||||
1640 | Depth + 1); | ||||||||||
1641 | } | ||||||||||
1642 | } | ||||||||||
1643 | } | ||||||||||
1644 | |||||||||||
1645 | if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { | ||||||||||
1646 | // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> | ||||||||||
1647 | if (SM->hasNoUnsignedWrap()) { | ||||||||||
1648 | // If the multiply does not unsign overflow then we can, by definition, | ||||||||||
1649 | // commute the zero extension with the multiply operation. | ||||||||||
1650 | SmallVector<const SCEV *, 4> Ops; | ||||||||||
1651 | for (const auto *Op : SM->operands()) | ||||||||||
1652 | Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); | ||||||||||
1653 | return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); | ||||||||||
1654 | } | ||||||||||
1655 | |||||||||||
1656 | // zext(2^K * (trunc X to iN)) to iM -> | ||||||||||
1657 | // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> | ||||||||||
1658 | // | ||||||||||
1659 | // Proof: | ||||||||||
1660 | // | ||||||||||
1661 | // zext(2^K * (trunc X to iN)) to iM | ||||||||||
1662 | // = zext((trunc X to iN) << K) to iM | ||||||||||
1663 | // = zext((trunc X to i{N-K}) << K)<nuw> to iM | ||||||||||
1664 | // (because shl removes the top K bits) | ||||||||||
1665 | // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM | ||||||||||
1666 | // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. | ||||||||||
1667 | // | ||||||||||
1668 | if (SM->getNumOperands() == 2) | ||||||||||
1669 | if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) | ||||||||||
1670 | if (MulLHS->getAPInt().isPowerOf2()) | ||||||||||
1671 | if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { | ||||||||||
1672 | int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - | ||||||||||
1673 | MulLHS->getAPInt().logBase2(); | ||||||||||
1674 | Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); | ||||||||||
1675 | return getMulExpr( | ||||||||||
1676 | getZeroExtendExpr(MulLHS, Ty), | ||||||||||
1677 | getZeroExtendExpr( | ||||||||||
1678 | getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), | ||||||||||
1679 | SCEV::FlagNUW, Depth + 1); | ||||||||||
1680 | } | ||||||||||
1681 | } | ||||||||||
1682 | |||||||||||
1683 | // The cast wasn't folded; create an explicit cast node. | ||||||||||
1684 | // Recompute the insert position, as it may have been invalidated. | ||||||||||
1685 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
1686 | SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), | ||||||||||
1687 | Op, Ty); | ||||||||||
1688 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1689 | addToLoopUseLists(S); | ||||||||||
1690 | return S; | ||||||||||
1691 | } | ||||||||||
1692 | |||||||||||
1693 | const SCEV * | ||||||||||
1694 | ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { | ||||||||||
1695 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1696, __PRETTY_FUNCTION__)) | ||||||||||
1696 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1696, __PRETTY_FUNCTION__)); | ||||||||||
1697 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1698, __PRETTY_FUNCTION__)) | ||||||||||
1698 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1698, __PRETTY_FUNCTION__)); | ||||||||||
1699 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
1700 | |||||||||||
1701 | // Fold if the operand is constant. | ||||||||||
1702 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) | ||||||||||
1703 | return getConstant( | ||||||||||
1704 | cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); | ||||||||||
1705 | |||||||||||
1706 | // sext(sext(x)) --> sext(x) | ||||||||||
1707 | if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) | ||||||||||
1708 | return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); | ||||||||||
1709 | |||||||||||
1710 | // sext(zext(x)) --> zext(x) | ||||||||||
1711 | if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) | ||||||||||
1712 | return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); | ||||||||||
1713 | |||||||||||
1714 | // Before doing any expensive analysis, check to see if we've already | ||||||||||
1715 | // computed a SCEV for this Op and Ty. | ||||||||||
1716 | FoldingSetNodeID ID; | ||||||||||
1717 | ID.AddInteger(scSignExtend); | ||||||||||
1718 | ID.AddPointer(Op); | ||||||||||
1719 | ID.AddPointer(Ty); | ||||||||||
1720 | void *IP = nullptr; | ||||||||||
1721 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
1722 | // Limit recursion depth. | ||||||||||
1723 | if (Depth > MaxCastDepth) { | ||||||||||
1724 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), | ||||||||||
1725 | Op, Ty); | ||||||||||
1726 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1727 | addToLoopUseLists(S); | ||||||||||
1728 | return S; | ||||||||||
1729 | } | ||||||||||
1730 | |||||||||||
1731 | // sext(trunc(x)) --> sext(x) or x or trunc(x) | ||||||||||
1732 | if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { | ||||||||||
1733 | // It's possible the bits taken off by the truncate were all sign bits. If | ||||||||||
1734 | // so, we should be able to simplify this further. | ||||||||||
1735 | const SCEV *X = ST->getOperand(); | ||||||||||
1736 | ConstantRange CR = getSignedRange(X); | ||||||||||
1737 | unsigned TruncBits = getTypeSizeInBits(ST->getType()); | ||||||||||
1738 | unsigned NewBits = getTypeSizeInBits(Ty); | ||||||||||
1739 | if (CR.truncate(TruncBits).signExtend(NewBits).contains( | ||||||||||
1740 | CR.sextOrTrunc(NewBits))) | ||||||||||
1741 | return getTruncateOrSignExtend(X, Ty, Depth); | ||||||||||
1742 | } | ||||||||||
1743 | |||||||||||
1744 | if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { | ||||||||||
1745 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> | ||||||||||
1746 | if (SA->hasNoSignedWrap()) { | ||||||||||
1747 | // If the addition does not sign overflow then we can, by definition, | ||||||||||
1748 | // commute the sign extension with the addition operation. | ||||||||||
1749 | SmallVector<const SCEV *, 4> Ops; | ||||||||||
1750 | for (const auto *Op : SA->operands()) | ||||||||||
1751 | Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); | ||||||||||
1752 | return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); | ||||||||||
1753 | } | ||||||||||
1754 | |||||||||||
1755 | // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) | ||||||||||
1756 | // if D + (C - D + x + y + ...) could be proven to not signed wrap | ||||||||||
1757 | // where D maximizes the number of trailing zeros of (C - D + x + y + ...) | ||||||||||
1758 | // | ||||||||||
1759 | // For instance, this will bring two seemingly different expressions: | ||||||||||
1760 | // 1 + sext(5 + 20 * %x + 24 * %y) and | ||||||||||
1761 | // sext(6 + 20 * %x + 24 * %y) | ||||||||||
1762 | // to the same form: | ||||||||||
1763 | // 2 + sext(4 + 20 * %x + 24 * %y) | ||||||||||
1764 | if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { | ||||||||||
1765 | const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); | ||||||||||
1766 | if (D != 0) { | ||||||||||
1767 | const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); | ||||||||||
1768 | const SCEV *SResidual = | ||||||||||
1769 | getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); | ||||||||||
1770 | const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); | ||||||||||
1771 | return getAddExpr(SSExtD, SSExtR, | ||||||||||
1772 | (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), | ||||||||||
1773 | Depth + 1); | ||||||||||
1774 | } | ||||||||||
1775 | } | ||||||||||
1776 | } | ||||||||||
1777 | // If the input value is a chrec scev, and we can prove that the value | ||||||||||
1778 | // did not overflow the old, smaller, value, we can sign extend all of the | ||||||||||
1779 | // operands (often constants). This allows analysis of something like | ||||||||||
1780 | // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } | ||||||||||
1781 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) | ||||||||||
1782 | if (AR->isAffine()) { | ||||||||||
1783 | const SCEV *Start = AR->getStart(); | ||||||||||
1784 | const SCEV *Step = AR->getStepRecurrence(*this); | ||||||||||
1785 | unsigned BitWidth = getTypeSizeInBits(AR->getType()); | ||||||||||
1786 | const Loop *L = AR->getLoop(); | ||||||||||
1787 | |||||||||||
1788 | if (!AR->hasNoSignedWrap()) { | ||||||||||
1789 | auto NewFlags = proveNoWrapViaConstantRanges(AR); | ||||||||||
1790 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); | ||||||||||
1791 | } | ||||||||||
1792 | |||||||||||
1793 | // If we have special knowledge that this addrec won't overflow, | ||||||||||
1794 | // we don't need to do any further analysis. | ||||||||||
1795 | if (AR->hasNoSignedWrap()) | ||||||||||
1796 | return getAddRecExpr( | ||||||||||
1797 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), | ||||||||||
1798 | getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); | ||||||||||
1799 | |||||||||||
1800 | // Check whether the backedge-taken count is SCEVCouldNotCompute. | ||||||||||
1801 | // Note that this serves two purposes: It filters out loops that are | ||||||||||
1802 | // simply not analyzable, and it covers the case where this code is | ||||||||||
1803 | // being called from within backedge-taken count analysis, such that | ||||||||||
1804 | // attempting to ask for the backedge-taken count would likely result | ||||||||||
1805 | // in infinite recursion. In the later case, the analysis code will | ||||||||||
1806 | // cope with a conservative value, and it will take care to purge | ||||||||||
1807 | // that value once it has finished. | ||||||||||
1808 | const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); | ||||||||||
1809 | if (!isa<SCEVCouldNotCompute>(MaxBECount)) { | ||||||||||
1810 | // Manually compute the final value for AR, checking for | ||||||||||
1811 | // overflow. | ||||||||||
1812 | |||||||||||
1813 | // Check whether the backedge-taken count can be losslessly casted to | ||||||||||
1814 | // the addrec's type. The count is always unsigned. | ||||||||||
1815 | const SCEV *CastedMaxBECount = | ||||||||||
1816 | getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); | ||||||||||
1817 | const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( | ||||||||||
1818 | CastedMaxBECount, MaxBECount->getType(), Depth); | ||||||||||
1819 | if (MaxBECount == RecastedMaxBECount) { | ||||||||||
1820 | Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); | ||||||||||
1821 | // Check whether Start+Step*MaxBECount has no signed overflow. | ||||||||||
1822 | const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, | ||||||||||
1823 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1824 | const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, | ||||||||||
1825 | SCEV::FlagAnyWrap, | ||||||||||
1826 | Depth + 1), | ||||||||||
1827 | WideTy, Depth + 1); | ||||||||||
1828 | const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); | ||||||||||
1829 | const SCEV *WideMaxBECount = | ||||||||||
1830 | getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); | ||||||||||
1831 | const SCEV *OperandExtendedAdd = | ||||||||||
1832 | getAddExpr(WideStart, | ||||||||||
1833 | getMulExpr(WideMaxBECount, | ||||||||||
1834 | getSignExtendExpr(Step, WideTy, Depth + 1), | ||||||||||
1835 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
1836 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1837 | if (SAdd == OperandExtendedAdd) { | ||||||||||
1838 | // Cache knowledge of AR NSW, which is propagated to this AddRec. | ||||||||||
1839 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); | ||||||||||
1840 | // Return the expression with the addrec on the outside. | ||||||||||
1841 | return getAddRecExpr( | ||||||||||
1842 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, | ||||||||||
1843 | Depth + 1), | ||||||||||
1844 | getSignExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1845 | AR->getNoWrapFlags()); | ||||||||||
1846 | } | ||||||||||
1847 | // Similar to above, only this time treat the step value as unsigned. | ||||||||||
1848 | // This covers loops that count up with an unsigned step. | ||||||||||
1849 | OperandExtendedAdd = | ||||||||||
1850 | getAddExpr(WideStart, | ||||||||||
1851 | getMulExpr(WideMaxBECount, | ||||||||||
1852 | getZeroExtendExpr(Step, WideTy, Depth + 1), | ||||||||||
1853 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
1854 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
1855 | if (SAdd == OperandExtendedAdd) { | ||||||||||
1856 | // If AR wraps around then | ||||||||||
1857 | // | ||||||||||
1858 | // abs(Step) * MaxBECount > unsigned-max(AR->getType()) | ||||||||||
1859 | // => SAdd != OperandExtendedAdd | ||||||||||
1860 | // | ||||||||||
1861 | // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> | ||||||||||
1862 | // (SAdd == OperandExtendedAdd => AR is NW) | ||||||||||
1863 | |||||||||||
1864 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); | ||||||||||
1865 | |||||||||||
1866 | // Return the expression with the addrec on the outside. | ||||||||||
1867 | return getAddRecExpr( | ||||||||||
1868 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, | ||||||||||
1869 | Depth + 1), | ||||||||||
1870 | getZeroExtendExpr(Step, Ty, Depth + 1), L, | ||||||||||
1871 | AR->getNoWrapFlags()); | ||||||||||
1872 | } | ||||||||||
1873 | } | ||||||||||
1874 | } | ||||||||||
1875 | |||||||||||
1876 | // Normally, in the cases we can prove no-overflow via a | ||||||||||
1877 | // backedge guarding condition, we can also compute a backedge | ||||||||||
1878 | // taken count for the loop. The exceptions are assumptions and | ||||||||||
1879 | // guards present in the loop -- SCEV is not great at exploiting | ||||||||||
1880 | // these to compute max backedge taken counts, but can still use | ||||||||||
1881 | // these to prove lack of overflow. Use this fact to avoid | ||||||||||
1882 | // doing extra work that may not pay off. | ||||||||||
1883 | |||||||||||
1884 | if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || | ||||||||||
1885 | !AC.assumptions().empty()) { | ||||||||||
1886 | // If the backedge is guarded by a comparison with the pre-inc | ||||||||||
1887 | // value the addrec is safe. Also, if the entry is guarded by | ||||||||||
1888 | // a comparison with the start value and the backedge is | ||||||||||
1889 | // guarded by a comparison with the post-inc value, the addrec | ||||||||||
1890 | // is safe. | ||||||||||
1891 | ICmpInst::Predicate Pred; | ||||||||||
1892 | const SCEV *OverflowLimit = | ||||||||||
1893 | getSignedOverflowLimitForStep(Step, &Pred, this); | ||||||||||
1894 | if (OverflowLimit && | ||||||||||
1895 | (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || | ||||||||||
1896 | isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { | ||||||||||
1897 | // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. | ||||||||||
1898 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); | ||||||||||
1899 | return getAddRecExpr( | ||||||||||
1900 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), | ||||||||||
1901 | getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); | ||||||||||
1902 | } | ||||||||||
1903 | } | ||||||||||
1904 | |||||||||||
1905 | // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> | ||||||||||
1906 | // if D + (C - D + Step * n) could be proven to not signed wrap | ||||||||||
1907 | // where D maximizes the number of trailing zeros of (C - D + Step * n) | ||||||||||
1908 | if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { | ||||||||||
1909 | const APInt &C = SC->getAPInt(); | ||||||||||
1910 | const APInt &D = extractConstantWithoutWrapping(*this, C, Step); | ||||||||||
1911 | if (D != 0) { | ||||||||||
1912 | const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); | ||||||||||
1913 | const SCEV *SResidual = | ||||||||||
1914 | getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); | ||||||||||
1915 | const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); | ||||||||||
1916 | return getAddExpr(SSExtD, SSExtR, | ||||||||||
1917 | (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), | ||||||||||
1918 | Depth + 1); | ||||||||||
1919 | } | ||||||||||
1920 | } | ||||||||||
1921 | |||||||||||
1922 | if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { | ||||||||||
1923 | const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); | ||||||||||
1924 | return getAddRecExpr( | ||||||||||
1925 | getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), | ||||||||||
1926 | getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); | ||||||||||
1927 | } | ||||||||||
1928 | } | ||||||||||
1929 | |||||||||||
1930 | // If the input value is provably positive and we could not simplify | ||||||||||
1931 | // away the sext build a zext instead. | ||||||||||
1932 | if (isKnownNonNegative(Op)) | ||||||||||
1933 | return getZeroExtendExpr(Op, Ty, Depth + 1); | ||||||||||
1934 | |||||||||||
1935 | // The cast wasn't folded; create an explicit cast node. | ||||||||||
1936 | // Recompute the insert position, as it may have been invalidated. | ||||||||||
1937 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
1938 | SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), | ||||||||||
1939 | Op, Ty); | ||||||||||
1940 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
1941 | addToLoopUseLists(S); | ||||||||||
1942 | return S; | ||||||||||
1943 | } | ||||||||||
1944 | |||||||||||
1945 | /// getAnyExtendExpr - Return a SCEV for the given operand extended with | ||||||||||
1946 | /// unspecified bits out to the given type. | ||||||||||
1947 | const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, | ||||||||||
1948 | Type *Ty) { | ||||||||||
1949 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1950, __PRETTY_FUNCTION__)) | ||||||||||
1950 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1950, __PRETTY_FUNCTION__)); | ||||||||||
1951 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1952, __PRETTY_FUNCTION__)) | ||||||||||
1952 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 1952, __PRETTY_FUNCTION__)); | ||||||||||
1953 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
1954 | |||||||||||
1955 | // Sign-extend negative constants. | ||||||||||
1956 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) | ||||||||||
1957 | if (SC->getAPInt().isNegative()) | ||||||||||
1958 | return getSignExtendExpr(Op, Ty); | ||||||||||
1959 | |||||||||||
1960 | // Peel off a truncate cast. | ||||||||||
1961 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { | ||||||||||
1962 | const SCEV *NewOp = T->getOperand(); | ||||||||||
1963 | if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) | ||||||||||
1964 | return getAnyExtendExpr(NewOp, Ty); | ||||||||||
1965 | return getTruncateOrNoop(NewOp, Ty); | ||||||||||
1966 | } | ||||||||||
1967 | |||||||||||
1968 | // Next try a zext cast. If the cast is folded, use it. | ||||||||||
1969 | const SCEV *ZExt = getZeroExtendExpr(Op, Ty); | ||||||||||
1970 | if (!isa<SCEVZeroExtendExpr>(ZExt)) | ||||||||||
1971 | return ZExt; | ||||||||||
1972 | |||||||||||
1973 | // Next try a sext cast. If the cast is folded, use it. | ||||||||||
1974 | const SCEV *SExt = getSignExtendExpr(Op, Ty); | ||||||||||
1975 | if (!isa<SCEVSignExtendExpr>(SExt)) | ||||||||||
1976 | return SExt; | ||||||||||
1977 | |||||||||||
1978 | // Force the cast to be folded into the operands of an addrec. | ||||||||||
1979 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { | ||||||||||
1980 | SmallVector<const SCEV *, 4> Ops; | ||||||||||
1981 | for (const SCEV *Op : AR->operands()) | ||||||||||
1982 | Ops.push_back(getAnyExtendExpr(Op, Ty)); | ||||||||||
1983 | return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); | ||||||||||
1984 | } | ||||||||||
1985 | |||||||||||
1986 | // If the expression is obviously signed, use the sext cast value. | ||||||||||
1987 | if (isa<SCEVSMaxExpr>(Op)) | ||||||||||
1988 | return SExt; | ||||||||||
1989 | |||||||||||
1990 | // Absent any other information, use the zext cast value. | ||||||||||
1991 | return ZExt; | ||||||||||
1992 | } | ||||||||||
1993 | |||||||||||
1994 | /// Process the given Ops list, which is a list of operands to be added under | ||||||||||
1995 | /// the given scale, update the given map. This is a helper function for | ||||||||||
1996 | /// getAddRecExpr. As an example of what it does, given a sequence of operands | ||||||||||
1997 | /// that would form an add expression like this: | ||||||||||
1998 | /// | ||||||||||
1999 | /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) | ||||||||||
2000 | /// | ||||||||||
2001 | /// where A and B are constants, update the map with these values: | ||||||||||
2002 | /// | ||||||||||
2003 | /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) | ||||||||||
2004 | /// | ||||||||||
2005 | /// and add 13 + A*B*29 to AccumulatedConstant. | ||||||||||
2006 | /// This will allow getAddRecExpr to produce this: | ||||||||||
2007 | /// | ||||||||||
2008 | /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) | ||||||||||
2009 | /// | ||||||||||
2010 | /// This form often exposes folding opportunities that are hidden in | ||||||||||
2011 | /// the original operand list. | ||||||||||
2012 | /// | ||||||||||
2013 | /// Return true iff it appears that any interesting folding opportunities | ||||||||||
2014 | /// may be exposed. This helps getAddRecExpr short-circuit extra work in | ||||||||||
2015 | /// the common case where no interesting opportunities are present, and | ||||||||||
2016 | /// is also used as a check to avoid infinite recursion. | ||||||||||
2017 | static bool | ||||||||||
2018 | CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, | ||||||||||
2019 | SmallVectorImpl<const SCEV *> &NewOps, | ||||||||||
2020 | APInt &AccumulatedConstant, | ||||||||||
2021 | const SCEV *const *Ops, size_t NumOperands, | ||||||||||
2022 | const APInt &Scale, | ||||||||||
2023 | ScalarEvolution &SE) { | ||||||||||
2024 | bool Interesting = false; | ||||||||||
2025 | |||||||||||
2026 | // Iterate over the add operands. They are sorted, with constants first. | ||||||||||
2027 | unsigned i = 0; | ||||||||||
2028 | while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { | ||||||||||
2029 | ++i; | ||||||||||
2030 | // Pull a buried constant out to the outside. | ||||||||||
2031 | if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) | ||||||||||
2032 | Interesting = true; | ||||||||||
2033 | AccumulatedConstant += Scale * C->getAPInt(); | ||||||||||
2034 | } | ||||||||||
2035 | |||||||||||
2036 | // Next comes everything else. We're especially interested in multiplies | ||||||||||
2037 | // here, but they're in the middle, so just visit the rest with one loop. | ||||||||||
2038 | for (; i != NumOperands; ++i) { | ||||||||||
2039 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); | ||||||||||
2040 | if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { | ||||||||||
2041 | APInt NewScale = | ||||||||||
2042 | Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); | ||||||||||
2043 | if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { | ||||||||||
2044 | // A multiplication of a constant with another add; recurse. | ||||||||||
2045 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); | ||||||||||
2046 | Interesting |= | ||||||||||
2047 | CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, | ||||||||||
2048 | Add->op_begin(), Add->getNumOperands(), | ||||||||||
2049 | NewScale, SE); | ||||||||||
2050 | } else { | ||||||||||
2051 | // A multiplication of a constant with some other value. Update | ||||||||||
2052 | // the map. | ||||||||||
2053 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); | ||||||||||
2054 | const SCEV *Key = SE.getMulExpr(MulOps); | ||||||||||
2055 | auto Pair = M.insert({Key, NewScale}); | ||||||||||
2056 | if (Pair.second) { | ||||||||||
2057 | NewOps.push_back(Pair.first->first); | ||||||||||
2058 | } else { | ||||||||||
2059 | Pair.first->second += NewScale; | ||||||||||
2060 | // The map already had an entry for this value, which may indicate | ||||||||||
2061 | // a folding opportunity. | ||||||||||
2062 | Interesting = true; | ||||||||||
2063 | } | ||||||||||
2064 | } | ||||||||||
2065 | } else { | ||||||||||
2066 | // An ordinary operand. Update the map. | ||||||||||
2067 | std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = | ||||||||||
2068 | M.insert({Ops[i], Scale}); | ||||||||||
2069 | if (Pair.second) { | ||||||||||
2070 | NewOps.push_back(Pair.first->first); | ||||||||||
2071 | } else { | ||||||||||
2072 | Pair.first->second += Scale; | ||||||||||
2073 | // The map already had an entry for this value, which may indicate | ||||||||||
2074 | // a folding opportunity. | ||||||||||
2075 | Interesting = true; | ||||||||||
2076 | } | ||||||||||
2077 | } | ||||||||||
2078 | } | ||||||||||
2079 | |||||||||||
2080 | return Interesting; | ||||||||||
2081 | } | ||||||||||
2082 | |||||||||||
2083 | // We're trying to construct a SCEV of type `Type' with `Ops' as operands and | ||||||||||
2084 | // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of | ||||||||||
2085 | // can't-overflow flags for the operation if possible. | ||||||||||
2086 | static SCEV::NoWrapFlags | ||||||||||
2087 | StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, | ||||||||||
2088 | const ArrayRef<const SCEV *> Ops, | ||||||||||
2089 | SCEV::NoWrapFlags Flags) { | ||||||||||
2090 | using namespace std::placeholders; | ||||||||||
2091 | |||||||||||
2092 | using OBO = OverflowingBinaryOperator; | ||||||||||
2093 | |||||||||||
2094 | bool CanAnalyze = | ||||||||||
2095 | Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; | ||||||||||
2096 | (void)CanAnalyze; | ||||||||||
2097 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2097, __PRETTY_FUNCTION__)); | ||||||||||
2098 | |||||||||||
2099 | int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; | ||||||||||
2100 | SCEV::NoWrapFlags SignOrUnsignWrap = | ||||||||||
2101 | ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); | ||||||||||
2102 | |||||||||||
2103 | // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. | ||||||||||
2104 | auto IsKnownNonNegative = [&](const SCEV *S) { | ||||||||||
2105 | return SE->isKnownNonNegative(S); | ||||||||||
2106 | }; | ||||||||||
2107 | |||||||||||
2108 | if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) | ||||||||||
2109 | Flags = | ||||||||||
2110 | ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); | ||||||||||
2111 | |||||||||||
2112 | SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); | ||||||||||
2113 | |||||||||||
2114 | if (SignOrUnsignWrap != SignOrUnsignMask && | ||||||||||
2115 | (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && | ||||||||||
2116 | isa<SCEVConstant>(Ops[0])) { | ||||||||||
2117 | |||||||||||
2118 | auto Opcode = [&] { | ||||||||||
2119 | switch (Type) { | ||||||||||
2120 | case scAddExpr: | ||||||||||
2121 | return Instruction::Add; | ||||||||||
2122 | case scMulExpr: | ||||||||||
2123 | return Instruction::Mul; | ||||||||||
2124 | default: | ||||||||||
2125 | llvm_unreachable("Unexpected SCEV op.")::llvm::llvm_unreachable_internal("Unexpected SCEV op.", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2125); | ||||||||||
2126 | } | ||||||||||
2127 | }(); | ||||||||||
2128 | |||||||||||
2129 | const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); | ||||||||||
2130 | |||||||||||
2131 | // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. | ||||||||||
2132 | if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { | ||||||||||
2133 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( | ||||||||||
2134 | Opcode, C, OBO::NoSignedWrap); | ||||||||||
2135 | if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) | ||||||||||
2136 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); | ||||||||||
2137 | } | ||||||||||
2138 | |||||||||||
2139 | // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. | ||||||||||
2140 | if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { | ||||||||||
2141 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( | ||||||||||
2142 | Opcode, C, OBO::NoUnsignedWrap); | ||||||||||
2143 | if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) | ||||||||||
2144 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); | ||||||||||
2145 | } | ||||||||||
2146 | } | ||||||||||
2147 | |||||||||||
2148 | return Flags; | ||||||||||
2149 | } | ||||||||||
2150 | |||||||||||
2151 | bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { | ||||||||||
2152 | return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); | ||||||||||
2153 | } | ||||||||||
2154 | |||||||||||
2155 | /// Get a canonical add expression, or something simpler if possible. | ||||||||||
2156 | const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, | ||||||||||
2157 | SCEV::NoWrapFlags Flags, | ||||||||||
2158 | unsigned Depth) { | ||||||||||
2159 | assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed" ) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2160, __PRETTY_FUNCTION__)) | ||||||||||
2160 | "only nuw or nsw allowed")((!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && "only nuw or nsw allowed" ) ? static_cast<void> (0) : __assert_fail ("!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && \"only nuw or nsw allowed\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2160, __PRETTY_FUNCTION__)); | ||||||||||
2161 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2161, __PRETTY_FUNCTION__)); | ||||||||||
2162 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
2163 | #ifndef NDEBUG | ||||||||||
2164 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); | ||||||||||
2165 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) | ||||||||||
2166 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2167, __PRETTY_FUNCTION__)) | ||||||||||
2167 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2167, __PRETTY_FUNCTION__)); | ||||||||||
2168 | #endif | ||||||||||
2169 | |||||||||||
2170 | // Sort by complexity, this groups all similar expression types together. | ||||||||||
2171 | GroupByComplexity(Ops, &LI, DT); | ||||||||||
2172 | |||||||||||
2173 | Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); | ||||||||||
2174 | |||||||||||
2175 | // If there are any constants, fold them together. | ||||||||||
2176 | unsigned Idx = 0; | ||||||||||
2177 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { | ||||||||||
2178 | ++Idx; | ||||||||||
2179 | assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail ("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2179, __PRETTY_FUNCTION__)); | ||||||||||
2180 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { | ||||||||||
2181 | // We found two constants, fold them together! | ||||||||||
2182 | Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); | ||||||||||
2183 | if (Ops.size() == 2) return Ops[0]; | ||||||||||
2184 | Ops.erase(Ops.begin()+1); // Erase the folded element | ||||||||||
2185 | LHSC = cast<SCEVConstant>(Ops[0]); | ||||||||||
2186 | } | ||||||||||
2187 | |||||||||||
2188 | // If we are left with a constant zero being added, strip it off. | ||||||||||
2189 | if (LHSC->getValue()->isZero()) { | ||||||||||
2190 | Ops.erase(Ops.begin()); | ||||||||||
2191 | --Idx; | ||||||||||
2192 | } | ||||||||||
2193 | |||||||||||
2194 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
2195 | } | ||||||||||
2196 | |||||||||||
2197 | // Limit recursion calls depth. | ||||||||||
2198 | if (Depth > MaxArithDepth || hasHugeExpression(Ops)) | ||||||||||
2199 | return getOrCreateAddExpr(Ops, Flags); | ||||||||||
2200 | |||||||||||
2201 | if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { | ||||||||||
2202 | static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); | ||||||||||
2203 | return S; | ||||||||||
2204 | } | ||||||||||
2205 | |||||||||||
2206 | // Okay, check to see if the same value occurs in the operand list more than | ||||||||||
2207 | // once. If so, merge them together into an multiply expression. Since we | ||||||||||
2208 | // sorted the list, these values are required to be adjacent. | ||||||||||
2209 | Type *Ty = Ops[0]->getType(); | ||||||||||
2210 | bool FoundMatch = false; | ||||||||||
2211 | for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) | ||||||||||
2212 | if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 | ||||||||||
2213 | // Scan ahead to count how many equal operands there are. | ||||||||||
2214 | unsigned Count = 2; | ||||||||||
2215 | while (i+Count != e && Ops[i+Count] == Ops[i]) | ||||||||||
2216 | ++Count; | ||||||||||
2217 | // Merge the values into a multiply. | ||||||||||
2218 | const SCEV *Scale = getConstant(Ty, Count); | ||||||||||
2219 | const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2220 | if (Ops.size() == Count) | ||||||||||
2221 | return Mul; | ||||||||||
2222 | Ops[i] = Mul; | ||||||||||
2223 | Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); | ||||||||||
2224 | --i; e -= Count - 1; | ||||||||||
2225 | FoundMatch = true; | ||||||||||
2226 | } | ||||||||||
2227 | if (FoundMatch) | ||||||||||
2228 | return getAddExpr(Ops, Flags, Depth + 1); | ||||||||||
2229 | |||||||||||
2230 | // Check for truncates. If all the operands are truncated from the same | ||||||||||
2231 | // type, see if factoring out the truncate would permit the result to be | ||||||||||
2232 | // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) | ||||||||||
2233 | // if the contents of the resulting outer trunc fold to something simple. | ||||||||||
2234 | auto FindTruncSrcType = [&]() -> Type * { | ||||||||||
2235 | // We're ultimately looking to fold an addrec of truncs and muls of only | ||||||||||
2236 | // constants and truncs, so if we find any other types of SCEV | ||||||||||
2237 | // as operands of the addrec then we bail and return nullptr here. | ||||||||||
2238 | // Otherwise, we return the type of the operand of a trunc that we find. | ||||||||||
2239 | if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) | ||||||||||
2240 | return T->getOperand()->getType(); | ||||||||||
2241 | if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { | ||||||||||
2242 | const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); | ||||||||||
2243 | if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) | ||||||||||
2244 | return T->getOperand()->getType(); | ||||||||||
2245 | } | ||||||||||
2246 | return nullptr; | ||||||||||
2247 | }; | ||||||||||
2248 | if (auto *SrcType = FindTruncSrcType()) { | ||||||||||
2249 | SmallVector<const SCEV *, 8> LargeOps; | ||||||||||
2250 | bool Ok = true; | ||||||||||
2251 | // Check all the operands to see if they can be represented in the | ||||||||||
2252 | // source type of the truncate. | ||||||||||
2253 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) { | ||||||||||
2254 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { | ||||||||||
2255 | if (T->getOperand()->getType() != SrcType) { | ||||||||||
2256 | Ok = false; | ||||||||||
2257 | break; | ||||||||||
2258 | } | ||||||||||
2259 | LargeOps.push_back(T->getOperand()); | ||||||||||
2260 | } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { | ||||||||||
2261 | LargeOps.push_back(getAnyExtendExpr(C, SrcType)); | ||||||||||
2262 | } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { | ||||||||||
2263 | SmallVector<const SCEV *, 8> LargeMulOps; | ||||||||||
2264 | for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { | ||||||||||
2265 | if (const SCEVTruncateExpr *T = | ||||||||||
2266 | dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { | ||||||||||
2267 | if (T->getOperand()->getType() != SrcType) { | ||||||||||
2268 | Ok = false; | ||||||||||
2269 | break; | ||||||||||
2270 | } | ||||||||||
2271 | LargeMulOps.push_back(T->getOperand()); | ||||||||||
2272 | } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { | ||||||||||
2273 | LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); | ||||||||||
2274 | } else { | ||||||||||
2275 | Ok = false; | ||||||||||
2276 | break; | ||||||||||
2277 | } | ||||||||||
2278 | } | ||||||||||
2279 | if (Ok) | ||||||||||
2280 | LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); | ||||||||||
2281 | } else { | ||||||||||
2282 | Ok = false; | ||||||||||
2283 | break; | ||||||||||
2284 | } | ||||||||||
2285 | } | ||||||||||
2286 | if (Ok) { | ||||||||||
2287 | // Evaluate the expression in the larger type. | ||||||||||
2288 | const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2289 | // If it folds to something simple, use it. Otherwise, don't. | ||||||||||
2290 | if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) | ||||||||||
2291 | return getTruncateExpr(Fold, Ty); | ||||||||||
2292 | } | ||||||||||
2293 | } | ||||||||||
2294 | |||||||||||
2295 | // Skip past any other cast SCEVs. | ||||||||||
2296 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) | ||||||||||
2297 | ++Idx; | ||||||||||
2298 | |||||||||||
2299 | // If there are add operands they would be next. | ||||||||||
2300 | if (Idx < Ops.size()) { | ||||||||||
2301 | bool DeletedAdd = false; | ||||||||||
2302 | while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { | ||||||||||
2303 | if (Ops.size() > AddOpsInlineThreshold || | ||||||||||
2304 | Add->getNumOperands() > AddOpsInlineThreshold) | ||||||||||
2305 | break; | ||||||||||
2306 | // If we have an add, expand the add operands onto the end of the operands | ||||||||||
2307 | // list. | ||||||||||
2308 | Ops.erase(Ops.begin()+Idx); | ||||||||||
2309 | Ops.append(Add->op_begin(), Add->op_end()); | ||||||||||
2310 | DeletedAdd = true; | ||||||||||
2311 | } | ||||||||||
2312 | |||||||||||
2313 | // If we deleted at least one add, we added operands to the end of the list, | ||||||||||
2314 | // and they are not necessarily sorted. Recurse to resort and resimplify | ||||||||||
2315 | // any operands we just acquired. | ||||||||||
2316 | if (DeletedAdd) | ||||||||||
2317 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2318 | } | ||||||||||
2319 | |||||||||||
2320 | // Skip over the add expression until we get to a multiply. | ||||||||||
2321 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) | ||||||||||
2322 | ++Idx; | ||||||||||
2323 | |||||||||||
2324 | // Check to see if there are any folding opportunities present with | ||||||||||
2325 | // operands multiplied by constant values. | ||||||||||
2326 | if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { | ||||||||||
2327 | uint64_t BitWidth = getTypeSizeInBits(Ty); | ||||||||||
2328 | DenseMap<const SCEV *, APInt> M; | ||||||||||
2329 | SmallVector<const SCEV *, 8> NewOps; | ||||||||||
2330 | APInt AccumulatedConstant(BitWidth, 0); | ||||||||||
2331 | if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, | ||||||||||
2332 | Ops.data(), Ops.size(), | ||||||||||
2333 | APInt(BitWidth, 1), *this)) { | ||||||||||
2334 | struct APIntCompare { | ||||||||||
2335 | bool operator()(const APInt &LHS, const APInt &RHS) const { | ||||||||||
2336 | return LHS.ult(RHS); | ||||||||||
2337 | } | ||||||||||
2338 | }; | ||||||||||
2339 | |||||||||||
2340 | // Some interesting folding opportunity is present, so its worthwhile to | ||||||||||
2341 | // re-generate the operands list. Group the operands by constant scale, | ||||||||||
2342 | // to avoid multiplying by the same constant scale multiple times. | ||||||||||
2343 | std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; | ||||||||||
2344 | for (const SCEV *NewOp : NewOps) | ||||||||||
2345 | MulOpLists[M.find(NewOp)->second].push_back(NewOp); | ||||||||||
2346 | // Re-generate the operands list. | ||||||||||
2347 | Ops.clear(); | ||||||||||
2348 | if (AccumulatedConstant != 0) | ||||||||||
2349 | Ops.push_back(getConstant(AccumulatedConstant)); | ||||||||||
2350 | for (auto &MulOp : MulOpLists) | ||||||||||
2351 | if (MulOp.first != 0) | ||||||||||
2352 | Ops.push_back(getMulExpr( | ||||||||||
2353 | getConstant(MulOp.first), | ||||||||||
2354 | getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
2355 | SCEV::FlagAnyWrap, Depth + 1)); | ||||||||||
2356 | if (Ops.empty()) | ||||||||||
2357 | return getZero(Ty); | ||||||||||
2358 | if (Ops.size() == 1) | ||||||||||
2359 | return Ops[0]; | ||||||||||
2360 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2361 | } | ||||||||||
2362 | } | ||||||||||
2363 | |||||||||||
2364 | // If we are adding something to a multiply expression, make sure the | ||||||||||
2365 | // something is not already an operand of the multiply. If so, merge it into | ||||||||||
2366 | // the multiply. | ||||||||||
2367 | for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { | ||||||||||
2368 | const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); | ||||||||||
2369 | for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { | ||||||||||
2370 | const SCEV *MulOpSCEV = Mul->getOperand(MulOp); | ||||||||||
2371 | if (isa<SCEVConstant>(MulOpSCEV)) | ||||||||||
2372 | continue; | ||||||||||
2373 | for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) | ||||||||||
2374 | if (MulOpSCEV == Ops[AddOp]) { | ||||||||||
2375 | // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) | ||||||||||
2376 | const SCEV *InnerMul = Mul->getOperand(MulOp == 0); | ||||||||||
2377 | if (Mul->getNumOperands() != 2) { | ||||||||||
2378 | // If the multiply has more than two operands, we must get the | ||||||||||
2379 | // Y*Z term. | ||||||||||
2380 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), | ||||||||||
2381 | Mul->op_begin()+MulOp); | ||||||||||
2382 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); | ||||||||||
2383 | InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2384 | } | ||||||||||
2385 | SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; | ||||||||||
2386 | const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2387 | const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, | ||||||||||
2388 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2389 | if (Ops.size() == 2) return OuterMul; | ||||||||||
2390 | if (AddOp < Idx) { | ||||||||||
2391 | Ops.erase(Ops.begin()+AddOp); | ||||||||||
2392 | Ops.erase(Ops.begin()+Idx-1); | ||||||||||
2393 | } else { | ||||||||||
2394 | Ops.erase(Ops.begin()+Idx); | ||||||||||
2395 | Ops.erase(Ops.begin()+AddOp-1); | ||||||||||
2396 | } | ||||||||||
2397 | Ops.push_back(OuterMul); | ||||||||||
2398 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2399 | } | ||||||||||
2400 | |||||||||||
2401 | // Check this multiply against other multiplies being added together. | ||||||||||
2402 | for (unsigned OtherMulIdx = Idx+1; | ||||||||||
2403 | OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); | ||||||||||
2404 | ++OtherMulIdx) { | ||||||||||
2405 | const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); | ||||||||||
2406 | // If MulOp occurs in OtherMul, we can fold the two multiplies | ||||||||||
2407 | // together. | ||||||||||
2408 | for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); | ||||||||||
2409 | OMulOp != e; ++OMulOp) | ||||||||||
2410 | if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { | ||||||||||
2411 | // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) | ||||||||||
2412 | const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); | ||||||||||
2413 | if (Mul->getNumOperands() != 2) { | ||||||||||
2414 | SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), | ||||||||||
2415 | Mul->op_begin()+MulOp); | ||||||||||
2416 | MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); | ||||||||||
2417 | InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2418 | } | ||||||||||
2419 | const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); | ||||||||||
2420 | if (OtherMul->getNumOperands() != 2) { | ||||||||||
2421 | SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), | ||||||||||
2422 | OtherMul->op_begin()+OMulOp); | ||||||||||
2423 | MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); | ||||||||||
2424 | InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2425 | } | ||||||||||
2426 | SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; | ||||||||||
2427 | const SCEV *InnerMulSum = | ||||||||||
2428 | getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2429 | const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, | ||||||||||
2430 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2431 | if (Ops.size() == 2) return OuterMul; | ||||||||||
2432 | Ops.erase(Ops.begin()+Idx); | ||||||||||
2433 | Ops.erase(Ops.begin()+OtherMulIdx-1); | ||||||||||
2434 | Ops.push_back(OuterMul); | ||||||||||
2435 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2436 | } | ||||||||||
2437 | } | ||||||||||
2438 | } | ||||||||||
2439 | } | ||||||||||
2440 | |||||||||||
2441 | // If there are any add recurrences in the operands list, see if any other | ||||||||||
2442 | // added values are loop invariant. If so, we can fold them into the | ||||||||||
2443 | // recurrence. | ||||||||||
2444 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) | ||||||||||
2445 | ++Idx; | ||||||||||
2446 | |||||||||||
2447 | // Scan over all recurrences, trying to fold loop invariants into them. | ||||||||||
2448 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { | ||||||||||
2449 | // Scan all of the other operands to this add and add them to the vector if | ||||||||||
2450 | // they are loop invariant w.r.t. the recurrence. | ||||||||||
2451 | SmallVector<const SCEV *, 8> LIOps; | ||||||||||
2452 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); | ||||||||||
2453 | const Loop *AddRecLoop = AddRec->getLoop(); | ||||||||||
2454 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) | ||||||||||
2455 | if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { | ||||||||||
2456 | LIOps.push_back(Ops[i]); | ||||||||||
2457 | Ops.erase(Ops.begin()+i); | ||||||||||
2458 | --i; --e; | ||||||||||
2459 | } | ||||||||||
2460 | |||||||||||
2461 | // If we found some loop invariants, fold them into the recurrence. | ||||||||||
2462 | if (!LIOps.empty()) { | ||||||||||
2463 | // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} | ||||||||||
2464 | LIOps.push_back(AddRec->getStart()); | ||||||||||
2465 | |||||||||||
2466 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), | ||||||||||
2467 | AddRec->op_end()); | ||||||||||
2468 | // This follows from the fact that the no-wrap flags on the outer add | ||||||||||
2469 | // expression are applicable on the 0th iteration, when the add recurrence | ||||||||||
2470 | // will be equal to its start value. | ||||||||||
2471 | AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); | ||||||||||
2472 | |||||||||||
2473 | // Build the new addrec. Propagate the NUW and NSW flags if both the | ||||||||||
2474 | // outer add and the inner addrec are guaranteed to have no overflow. | ||||||||||
2475 | // Always propagate NW. | ||||||||||
2476 | Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); | ||||||||||
2477 | const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); | ||||||||||
2478 | |||||||||||
2479 | // If all of the other operands were loop invariant, we are done. | ||||||||||
2480 | if (Ops.size() == 1) return NewRec; | ||||||||||
2481 | |||||||||||
2482 | // Otherwise, add the folded AddRec by the non-invariant parts. | ||||||||||
2483 | for (unsigned i = 0;; ++i) | ||||||||||
2484 | if (Ops[i] == AddRec) { | ||||||||||
2485 | Ops[i] = NewRec; | ||||||||||
2486 | break; | ||||||||||
2487 | } | ||||||||||
2488 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2489 | } | ||||||||||
2490 | |||||||||||
2491 | // Okay, if there weren't any loop invariants to be folded, check to see if | ||||||||||
2492 | // there are multiple AddRec's with the same loop induction variable being | ||||||||||
2493 | // added together. If so, we can fold them. | ||||||||||
2494 | for (unsigned OtherIdx = Idx+1; | ||||||||||
2495 | OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); | ||||||||||
2496 | ++OtherIdx) { | ||||||||||
2497 | // We expect the AddRecExpr's to be sorted in reverse dominance order, | ||||||||||
2498 | // so that the 1st found AddRecExpr is dominated by all others. | ||||||||||
2499 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2502, __PRETTY_FUNCTION__)) | ||||||||||
2500 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2502, __PRETTY_FUNCTION__)) | ||||||||||
2501 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2502, __PRETTY_FUNCTION__)) | ||||||||||
2502 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2502, __PRETTY_FUNCTION__)); | ||||||||||
2503 | if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { | ||||||||||
2504 | // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> | ||||||||||
2505 | SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), | ||||||||||
2506 | AddRec->op_end()); | ||||||||||
2507 | for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); | ||||||||||
2508 | ++OtherIdx) { | ||||||||||
2509 | const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); | ||||||||||
2510 | if (OtherAddRec->getLoop() == AddRecLoop) { | ||||||||||
2511 | for (unsigned i = 0, e = OtherAddRec->getNumOperands(); | ||||||||||
2512 | i != e; ++i) { | ||||||||||
2513 | if (i >= AddRecOps.size()) { | ||||||||||
2514 | AddRecOps.append(OtherAddRec->op_begin()+i, | ||||||||||
2515 | OtherAddRec->op_end()); | ||||||||||
2516 | break; | ||||||||||
2517 | } | ||||||||||
2518 | SmallVector<const SCEV *, 2> TwoOps = { | ||||||||||
2519 | AddRecOps[i], OtherAddRec->getOperand(i)}; | ||||||||||
2520 | AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2521 | } | ||||||||||
2522 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; | ||||||||||
2523 | } | ||||||||||
2524 | } | ||||||||||
2525 | // Step size has changed, so we cannot guarantee no self-wraparound. | ||||||||||
2526 | Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); | ||||||||||
2527 | return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2528 | } | ||||||||||
2529 | } | ||||||||||
2530 | |||||||||||
2531 | // Otherwise couldn't fold anything into this recurrence. Move onto the | ||||||||||
2532 | // next one. | ||||||||||
2533 | } | ||||||||||
2534 | |||||||||||
2535 | // Okay, it looks like we really DO need an add expr. Check to see if we | ||||||||||
2536 | // already have one, otherwise create a new one. | ||||||||||
2537 | return getOrCreateAddExpr(Ops, Flags); | ||||||||||
2538 | } | ||||||||||
2539 | |||||||||||
2540 | const SCEV * | ||||||||||
2541 | ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, | ||||||||||
2542 | SCEV::NoWrapFlags Flags) { | ||||||||||
2543 | FoldingSetNodeID ID; | ||||||||||
2544 | ID.AddInteger(scAddExpr); | ||||||||||
2545 | for (const SCEV *Op : Ops) | ||||||||||
2546 | ID.AddPointer(Op); | ||||||||||
2547 | void *IP = nullptr; | ||||||||||
2548 | SCEVAddExpr *S = | ||||||||||
2549 | static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); | ||||||||||
2550 | if (!S) { | ||||||||||
2551 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); | ||||||||||
2552 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); | ||||||||||
2553 | S = new (SCEVAllocator) | ||||||||||
2554 | SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); | ||||||||||
2555 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
2556 | addToLoopUseLists(S); | ||||||||||
2557 | } | ||||||||||
2558 | S->setNoWrapFlags(Flags); | ||||||||||
2559 | return S; | ||||||||||
2560 | } | ||||||||||
2561 | |||||||||||
2562 | const SCEV * | ||||||||||
2563 | ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, | ||||||||||
2564 | const Loop *L, SCEV::NoWrapFlags Flags) { | ||||||||||
2565 | FoldingSetNodeID ID; | ||||||||||
2566 | ID.AddInteger(scAddRecExpr); | ||||||||||
2567 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) | ||||||||||
2568 | ID.AddPointer(Ops[i]); | ||||||||||
2569 | ID.AddPointer(L); | ||||||||||
2570 | void *IP = nullptr; | ||||||||||
2571 | SCEVAddRecExpr *S = | ||||||||||
2572 | static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); | ||||||||||
2573 | if (!S) { | ||||||||||
2574 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); | ||||||||||
2575 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); | ||||||||||
2576 | S = new (SCEVAllocator) | ||||||||||
2577 | SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); | ||||||||||
2578 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
2579 | addToLoopUseLists(S); | ||||||||||
2580 | } | ||||||||||
2581 | S->setNoWrapFlags(Flags); | ||||||||||
2582 | return S; | ||||||||||
2583 | } | ||||||||||
2584 | |||||||||||
2585 | const SCEV * | ||||||||||
2586 | ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, | ||||||||||
2587 | SCEV::NoWrapFlags Flags) { | ||||||||||
2588 | FoldingSetNodeID ID; | ||||||||||
2589 | ID.AddInteger(scMulExpr); | ||||||||||
2590 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) | ||||||||||
2591 | ID.AddPointer(Ops[i]); | ||||||||||
2592 | void *IP = nullptr; | ||||||||||
2593 | SCEVMulExpr *S = | ||||||||||
2594 | static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); | ||||||||||
2595 | if (!S) { | ||||||||||
2596 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); | ||||||||||
2597 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); | ||||||||||
2598 | S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), | ||||||||||
2599 | O, Ops.size()); | ||||||||||
2600 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
2601 | addToLoopUseLists(S); | ||||||||||
2602 | } | ||||||||||
2603 | S->setNoWrapFlags(Flags); | ||||||||||
2604 | return S; | ||||||||||
2605 | } | ||||||||||
2606 | |||||||||||
2607 | static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { | ||||||||||
2608 | uint64_t k = i*j; | ||||||||||
2609 | if (j > 1 && k / j != i) Overflow = true; | ||||||||||
2610 | return k; | ||||||||||
2611 | } | ||||||||||
2612 | |||||||||||
2613 | /// Compute the result of "n choose k", the binomial coefficient. If an | ||||||||||
2614 | /// intermediate computation overflows, Overflow will be set and the return will | ||||||||||
2615 | /// be garbage. Overflow is not cleared on absence of overflow. | ||||||||||
2616 | static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { | ||||||||||
2617 | // We use the multiplicative formula: | ||||||||||
2618 | // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . | ||||||||||
2619 | // At each iteration, we take the n-th term of the numeral and divide by the | ||||||||||
2620 | // (k-n)th term of the denominator. This division will always produce an | ||||||||||
2621 | // integral result, and helps reduce the chance of overflow in the | ||||||||||
2622 | // intermediate computations. However, we can still overflow even when the | ||||||||||
2623 | // final result would fit. | ||||||||||
2624 | |||||||||||
2625 | if (n == 0 || n == k) return 1; | ||||||||||
2626 | if (k > n) return 0; | ||||||||||
2627 | |||||||||||
2628 | if (k > n/2) | ||||||||||
2629 | k = n-k; | ||||||||||
2630 | |||||||||||
2631 | uint64_t r = 1; | ||||||||||
2632 | for (uint64_t i = 1; i <= k; ++i) { | ||||||||||
2633 | r = umul_ov(r, n-(i-1), Overflow); | ||||||||||
2634 | r /= i; | ||||||||||
2635 | } | ||||||||||
2636 | return r; | ||||||||||
2637 | } | ||||||||||
2638 | |||||||||||
2639 | /// Determine if any of the operands in this SCEV are a constant or if | ||||||||||
2640 | /// any of the add or multiply expressions in this SCEV contain a constant. | ||||||||||
2641 | static bool containsConstantInAddMulChain(const SCEV *StartExpr) { | ||||||||||
2642 | struct FindConstantInAddMulChain { | ||||||||||
2643 | bool FoundConstant = false; | ||||||||||
2644 | |||||||||||
2645 | bool follow(const SCEV *S) { | ||||||||||
2646 | FoundConstant |= isa<SCEVConstant>(S); | ||||||||||
2647 | return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); | ||||||||||
2648 | } | ||||||||||
2649 | |||||||||||
2650 | bool isDone() const { | ||||||||||
2651 | return FoundConstant; | ||||||||||
2652 | } | ||||||||||
2653 | }; | ||||||||||
2654 | |||||||||||
2655 | FindConstantInAddMulChain F; | ||||||||||
2656 | SCEVTraversal<FindConstantInAddMulChain> ST(F); | ||||||||||
2657 | ST.visitAll(StartExpr); | ||||||||||
2658 | return F.FoundConstant; | ||||||||||
2659 | } | ||||||||||
2660 | |||||||||||
2661 | /// Get a canonical multiply expression, or something simpler if possible. | ||||||||||
2662 | const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, | ||||||||||
2663 | SCEV::NoWrapFlags Flags, | ||||||||||
2664 | unsigned Depth) { | ||||||||||
2665 | assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && "only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail ("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2666, __PRETTY_FUNCTION__)) | ||||||||||
2666 | "only nuw or nsw allowed")((Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && "only nuw or nsw allowed") ? static_cast<void> (0) : __assert_fail ("Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && \"only nuw or nsw allowed\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2666, __PRETTY_FUNCTION__)); | ||||||||||
2667 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2667, __PRETTY_FUNCTION__)); | ||||||||||
2668 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
2669 | #ifndef NDEBUG | ||||||||||
2670 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); | ||||||||||
2671 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) | ||||||||||
2672 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2673, __PRETTY_FUNCTION__)) | ||||||||||
2673 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2673, __PRETTY_FUNCTION__)); | ||||||||||
2674 | #endif | ||||||||||
2675 | |||||||||||
2676 | // Sort by complexity, this groups all similar expression types together. | ||||||||||
2677 | GroupByComplexity(Ops, &LI, DT); | ||||||||||
2678 | |||||||||||
2679 | Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); | ||||||||||
2680 | |||||||||||
2681 | // Limit recursion calls depth, but fold all-constant expressions. | ||||||||||
2682 | // `Ops` is sorted, so it's enough to check just last one. | ||||||||||
2683 | if ((Depth > MaxArithDepth || hasHugeExpression(Ops)) && | ||||||||||
2684 | !isa<SCEVConstant>(Ops.back())) | ||||||||||
2685 | return getOrCreateMulExpr(Ops, Flags); | ||||||||||
2686 | |||||||||||
2687 | if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { | ||||||||||
2688 | static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); | ||||||||||
2689 | return S; | ||||||||||
2690 | } | ||||||||||
2691 | |||||||||||
2692 | // If there are any constants, fold them together. | ||||||||||
2693 | unsigned Idx = 0; | ||||||||||
2694 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { | ||||||||||
2695 | |||||||||||
2696 | if (Ops.size() == 2) | ||||||||||
2697 | // C1*(C2+V) -> C1*C2 + C1*V | ||||||||||
2698 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) | ||||||||||
2699 | // If any of Add's ops are Adds or Muls with a constant, apply this | ||||||||||
2700 | // transformation as well. | ||||||||||
2701 | // | ||||||||||
2702 | // TODO: There are some cases where this transformation is not | ||||||||||
2703 | // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of | ||||||||||
2704 | // this transformation should be narrowed down. | ||||||||||
2705 | if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) | ||||||||||
2706 | return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), | ||||||||||
2707 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
2708 | getMulExpr(LHSC, Add->getOperand(1), | ||||||||||
2709 | SCEV::FlagAnyWrap, Depth + 1), | ||||||||||
2710 | SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2711 | |||||||||||
2712 | ++Idx; | ||||||||||
2713 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { | ||||||||||
2714 | // We found two constants, fold them together! | ||||||||||
2715 | ConstantInt *Fold = | ||||||||||
2716 | ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); | ||||||||||
2717 | Ops[0] = getConstant(Fold); | ||||||||||
2718 | Ops.erase(Ops.begin()+1); // Erase the folded element | ||||||||||
2719 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
2720 | LHSC = cast<SCEVConstant>(Ops[0]); | ||||||||||
2721 | } | ||||||||||
2722 | |||||||||||
2723 | // If we are left with a constant one being multiplied, strip it off. | ||||||||||
2724 | if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { | ||||||||||
2725 | Ops.erase(Ops.begin()); | ||||||||||
2726 | --Idx; | ||||||||||
2727 | } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { | ||||||||||
2728 | // If we have a multiply of zero, it will always be zero. | ||||||||||
2729 | return Ops[0]; | ||||||||||
2730 | } else if (Ops[0]->isAllOnesValue()) { | ||||||||||
2731 | // If we have a mul by -1 of an add, try distributing the -1 among the | ||||||||||
2732 | // add operands. | ||||||||||
2733 | if (Ops.size() == 2) { | ||||||||||
2734 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { | ||||||||||
2735 | SmallVector<const SCEV *, 4> NewOps; | ||||||||||
2736 | bool AnyFolded = false; | ||||||||||
2737 | for (const SCEV *AddOp : Add->operands()) { | ||||||||||
2738 | const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, | ||||||||||
2739 | Depth + 1); | ||||||||||
2740 | if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; | ||||||||||
2741 | NewOps.push_back(Mul); | ||||||||||
2742 | } | ||||||||||
2743 | if (AnyFolded) | ||||||||||
2744 | return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2745 | } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { | ||||||||||
2746 | // Negation preserves a recurrence's no self-wrap property. | ||||||||||
2747 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
2748 | for (const SCEV *AddRecOp : AddRec->operands()) | ||||||||||
2749 | Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, | ||||||||||
2750 | Depth + 1)); | ||||||||||
2751 | |||||||||||
2752 | return getAddRecExpr(Operands, AddRec->getLoop(), | ||||||||||
2753 | AddRec->getNoWrapFlags(SCEV::FlagNW)); | ||||||||||
2754 | } | ||||||||||
2755 | } | ||||||||||
2756 | } | ||||||||||
2757 | |||||||||||
2758 | if (Ops.size() == 1) | ||||||||||
2759 | return Ops[0]; | ||||||||||
2760 | } | ||||||||||
2761 | |||||||||||
2762 | // Skip over the add expression until we get to a multiply. | ||||||||||
2763 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) | ||||||||||
2764 | ++Idx; | ||||||||||
2765 | |||||||||||
2766 | // If there are mul operands inline them all into this expression. | ||||||||||
2767 | if (Idx < Ops.size()) { | ||||||||||
2768 | bool DeletedMul = false; | ||||||||||
2769 | while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { | ||||||||||
2770 | if (Ops.size() > MulOpsInlineThreshold) | ||||||||||
2771 | break; | ||||||||||
2772 | // If we have an mul, expand the mul operands onto the end of the | ||||||||||
2773 | // operands list. | ||||||||||
2774 | Ops.erase(Ops.begin()+Idx); | ||||||||||
2775 | Ops.append(Mul->op_begin(), Mul->op_end()); | ||||||||||
2776 | DeletedMul = true; | ||||||||||
2777 | } | ||||||||||
2778 | |||||||||||
2779 | // If we deleted at least one mul, we added operands to the end of the | ||||||||||
2780 | // list, and they are not necessarily sorted. Recurse to resort and | ||||||||||
2781 | // resimplify any operands we just acquired. | ||||||||||
2782 | if (DeletedMul) | ||||||||||
2783 | return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2784 | } | ||||||||||
2785 | |||||||||||
2786 | // If there are any add recurrences in the operands list, see if any other | ||||||||||
2787 | // added values are loop invariant. If so, we can fold them into the | ||||||||||
2788 | // recurrence. | ||||||||||
2789 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) | ||||||||||
2790 | ++Idx; | ||||||||||
2791 | |||||||||||
2792 | // Scan over all recurrences, trying to fold loop invariants into them. | ||||||||||
2793 | for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { | ||||||||||
2794 | // Scan all of the other operands to this mul and add them to the vector | ||||||||||
2795 | // if they are loop invariant w.r.t. the recurrence. | ||||||||||
2796 | SmallVector<const SCEV *, 8> LIOps; | ||||||||||
2797 | const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); | ||||||||||
2798 | const Loop *AddRecLoop = AddRec->getLoop(); | ||||||||||
2799 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) | ||||||||||
2800 | if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { | ||||||||||
2801 | LIOps.push_back(Ops[i]); | ||||||||||
2802 | Ops.erase(Ops.begin()+i); | ||||||||||
2803 | --i; --e; | ||||||||||
2804 | } | ||||||||||
2805 | |||||||||||
2806 | // If we found some loop invariants, fold them into the recurrence. | ||||||||||
2807 | if (!LIOps.empty()) { | ||||||||||
2808 | // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} | ||||||||||
2809 | SmallVector<const SCEV *, 4> NewOps; | ||||||||||
2810 | NewOps.reserve(AddRec->getNumOperands()); | ||||||||||
2811 | const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2812 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) | ||||||||||
2813 | NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), | ||||||||||
2814 | SCEV::FlagAnyWrap, Depth + 1)); | ||||||||||
2815 | |||||||||||
2816 | // Build the new addrec. Propagate the NUW and NSW flags if both the | ||||||||||
2817 | // outer mul and the inner addrec are guaranteed to have no overflow. | ||||||||||
2818 | // | ||||||||||
2819 | // No self-wrap cannot be guaranteed after changing the step size, but | ||||||||||
2820 | // will be inferred if either NUW or NSW is true. | ||||||||||
2821 | Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); | ||||||||||
2822 | const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); | ||||||||||
2823 | |||||||||||
2824 | // If all of the other operands were loop invariant, we are done. | ||||||||||
2825 | if (Ops.size() == 1) return NewRec; | ||||||||||
2826 | |||||||||||
2827 | // Otherwise, multiply the folded AddRec by the non-invariant parts. | ||||||||||
2828 | for (unsigned i = 0;; ++i) | ||||||||||
2829 | if (Ops[i] == AddRec) { | ||||||||||
2830 | Ops[i] = NewRec; | ||||||||||
2831 | break; | ||||||||||
2832 | } | ||||||||||
2833 | return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2834 | } | ||||||||||
2835 | |||||||||||
2836 | // Okay, if there weren't any loop invariants to be folded, check to see | ||||||||||
2837 | // if there are multiple AddRec's with the same loop induction variable | ||||||||||
2838 | // being multiplied together. If so, we can fold them. | ||||||||||
2839 | |||||||||||
2840 | // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> | ||||||||||
2841 | // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ | ||||||||||
2842 | // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z | ||||||||||
2843 | // ]]],+,...up to x=2n}. | ||||||||||
2844 | // Note that the arguments to choose() are always integers with values | ||||||||||
2845 | // known at compile time, never SCEV objects. | ||||||||||
2846 | // | ||||||||||
2847 | // The implementation avoids pointless extra computations when the two | ||||||||||
2848 | // addrec's are of different length (mathematically, it's equivalent to | ||||||||||
2849 | // an infinite stream of zeros on the right). | ||||||||||
2850 | bool OpsModified = false; | ||||||||||
2851 | for (unsigned OtherIdx = Idx+1; | ||||||||||
2852 | OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); | ||||||||||
2853 | ++OtherIdx) { | ||||||||||
2854 | const SCEVAddRecExpr *OtherAddRec = | ||||||||||
2855 | dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); | ||||||||||
2856 | if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) | ||||||||||
2857 | continue; | ||||||||||
2858 | |||||||||||
2859 | // Limit max number of arguments to avoid creation of unreasonably big | ||||||||||
2860 | // SCEVAddRecs with very complex operands. | ||||||||||
2861 | if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > | ||||||||||
2862 | MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) | ||||||||||
2863 | continue; | ||||||||||
2864 | |||||||||||
2865 | bool Overflow = false; | ||||||||||
2866 | Type *Ty = AddRec->getType(); | ||||||||||
2867 | bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; | ||||||||||
2868 | SmallVector<const SCEV*, 7> AddRecOps; | ||||||||||
2869 | for (int x = 0, xe = AddRec->getNumOperands() + | ||||||||||
2870 | OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { | ||||||||||
2871 | SmallVector <const SCEV *, 7> SumOps; | ||||||||||
2872 | for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { | ||||||||||
2873 | uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); | ||||||||||
2874 | for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), | ||||||||||
2875 | ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); | ||||||||||
2876 | z < ze && !Overflow; ++z) { | ||||||||||
2877 | uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); | ||||||||||
2878 | uint64_t Coeff; | ||||||||||
2879 | if (LargerThan64Bits) | ||||||||||
2880 | Coeff = umul_ov(Coeff1, Coeff2, Overflow); | ||||||||||
2881 | else | ||||||||||
2882 | Coeff = Coeff1*Coeff2; | ||||||||||
2883 | const SCEV *CoeffTerm = getConstant(Ty, Coeff); | ||||||||||
2884 | const SCEV *Term1 = AddRec->getOperand(y-z); | ||||||||||
2885 | const SCEV *Term2 = OtherAddRec->getOperand(z); | ||||||||||
2886 | SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, | ||||||||||
2887 | SCEV::FlagAnyWrap, Depth + 1)); | ||||||||||
2888 | } | ||||||||||
2889 | } | ||||||||||
2890 | if (SumOps.empty()) | ||||||||||
2891 | SumOps.push_back(getZero(Ty)); | ||||||||||
2892 | AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); | ||||||||||
2893 | } | ||||||||||
2894 | if (!Overflow) { | ||||||||||
2895 | const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, | ||||||||||
2896 | SCEV::FlagAnyWrap); | ||||||||||
2897 | if (Ops.size() == 2) return NewAddRec; | ||||||||||
2898 | Ops[Idx] = NewAddRec; | ||||||||||
2899 | Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; | ||||||||||
2900 | OpsModified = true; | ||||||||||
2901 | AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); | ||||||||||
2902 | if (!AddRec) | ||||||||||
2903 | break; | ||||||||||
2904 | } | ||||||||||
2905 | } | ||||||||||
2906 | if (OpsModified) | ||||||||||
2907 | return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); | ||||||||||
2908 | |||||||||||
2909 | // Otherwise couldn't fold anything into this recurrence. Move onto the | ||||||||||
2910 | // next one. | ||||||||||
2911 | } | ||||||||||
2912 | |||||||||||
2913 | // Okay, it looks like we really DO need an mul expr. Check to see if we | ||||||||||
2914 | // already have one, otherwise create a new one. | ||||||||||
2915 | return getOrCreateMulExpr(Ops, Flags); | ||||||||||
2916 | } | ||||||||||
2917 | |||||||||||
2918 | /// Represents an unsigned remainder expression based on unsigned division. | ||||||||||
2919 | const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, | ||||||||||
2920 | const SCEV *RHS) { | ||||||||||
2921 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2923, __PRETTY_FUNCTION__)) | ||||||||||
2922 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2923, __PRETTY_FUNCTION__)) | ||||||||||
2923 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2923, __PRETTY_FUNCTION__)); | ||||||||||
2924 | |||||||||||
2925 | // Short-circuit easy cases | ||||||||||
2926 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { | ||||||||||
2927 | // If constant is one, the result is trivial | ||||||||||
2928 | if (RHSC->getValue()->isOne()) | ||||||||||
2929 | return getZero(LHS->getType()); // X urem 1 --> 0 | ||||||||||
2930 | |||||||||||
2931 | // If constant is a power of two, fold into a zext(trunc(LHS)). | ||||||||||
2932 | if (RHSC->getAPInt().isPowerOf2()) { | ||||||||||
2933 | Type *FullTy = LHS->getType(); | ||||||||||
2934 | Type *TruncTy = | ||||||||||
2935 | IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); | ||||||||||
2936 | return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); | ||||||||||
2937 | } | ||||||||||
2938 | } | ||||||||||
2939 | |||||||||||
2940 | // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) | ||||||||||
2941 | const SCEV *UDiv = getUDivExpr(LHS, RHS); | ||||||||||
2942 | const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); | ||||||||||
2943 | return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); | ||||||||||
2944 | } | ||||||||||
2945 | |||||||||||
2946 | /// Get a canonical unsigned division expression, or something simpler if | ||||||||||
2947 | /// possible. | ||||||||||
2948 | const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, | ||||||||||
2949 | const SCEV *RHS) { | ||||||||||
2950 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2952, __PRETTY_FUNCTION__)) | ||||||||||
2951 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2952, __PRETTY_FUNCTION__)) | ||||||||||
2952 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 2952, __PRETTY_FUNCTION__)); | ||||||||||
2953 | |||||||||||
2954 | FoldingSetNodeID ID; | ||||||||||
2955 | ID.AddInteger(scUDivExpr); | ||||||||||
2956 | ID.AddPointer(LHS); | ||||||||||
2957 | ID.AddPointer(RHS); | ||||||||||
2958 | void *IP = nullptr; | ||||||||||
2959 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) | ||||||||||
2960 | return S; | ||||||||||
2961 | |||||||||||
2962 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { | ||||||||||
2963 | if (RHSC->getValue()->isOne()) | ||||||||||
2964 | return LHS; // X udiv 1 --> x | ||||||||||
2965 | // If the denominator is zero, the result of the udiv is undefined. Don't | ||||||||||
2966 | // try to analyze it, because the resolution chosen here may differ from | ||||||||||
2967 | // the resolution chosen in other parts of the compiler. | ||||||||||
2968 | if (!RHSC->getValue()->isZero()) { | ||||||||||
2969 | // Determine if the division can be folded into the operands of | ||||||||||
2970 | // its operands. | ||||||||||
2971 | // TODO: Generalize this to non-constants by using known-bits information. | ||||||||||
2972 | Type *Ty = LHS->getType(); | ||||||||||
2973 | unsigned LZ = RHSC->getAPInt().countLeadingZeros(); | ||||||||||
2974 | unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; | ||||||||||
2975 | // For non-power-of-two values, effectively round the value up to the | ||||||||||
2976 | // nearest power of two. | ||||||||||
2977 | if (!RHSC->getAPInt().isPowerOf2()) | ||||||||||
2978 | ++MaxShiftAmt; | ||||||||||
2979 | IntegerType *ExtTy = | ||||||||||
2980 | IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); | ||||||||||
2981 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) | ||||||||||
2982 | if (const SCEVConstant *Step = | ||||||||||
2983 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { | ||||||||||
2984 | // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. | ||||||||||
2985 | const APInt &StepInt = Step->getAPInt(); | ||||||||||
2986 | const APInt &DivInt = RHSC->getAPInt(); | ||||||||||
2987 | if (!StepInt.urem(DivInt) && | ||||||||||
2988 | getZeroExtendExpr(AR, ExtTy) == | ||||||||||
2989 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), | ||||||||||
2990 | getZeroExtendExpr(Step, ExtTy), | ||||||||||
2991 | AR->getLoop(), SCEV::FlagAnyWrap)) { | ||||||||||
2992 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
2993 | for (const SCEV *Op : AR->operands()) | ||||||||||
2994 | Operands.push_back(getUDivExpr(Op, RHS)); | ||||||||||
2995 | return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); | ||||||||||
2996 | } | ||||||||||
2997 | /// Get a canonical UDivExpr for a recurrence. | ||||||||||
2998 | /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. | ||||||||||
2999 | // We can currently only fold X%N if X is constant. | ||||||||||
3000 | const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); | ||||||||||
3001 | if (StartC && !DivInt.urem(StepInt) && | ||||||||||
3002 | getZeroExtendExpr(AR, ExtTy) == | ||||||||||
3003 | getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), | ||||||||||
3004 | getZeroExtendExpr(Step, ExtTy), | ||||||||||
3005 | AR->getLoop(), SCEV::FlagAnyWrap)) { | ||||||||||
3006 | const APInt &StartInt = StartC->getAPInt(); | ||||||||||
3007 | const APInt &StartRem = StartInt.urem(StepInt); | ||||||||||
3008 | if (StartRem != 0) { | ||||||||||
3009 | const SCEV *NewLHS = | ||||||||||
3010 | getAddRecExpr(getConstant(StartInt - StartRem), Step, | ||||||||||
3011 | AR->getLoop(), SCEV::FlagNW); | ||||||||||
3012 | if (LHS != NewLHS) { | ||||||||||
3013 | LHS = NewLHS; | ||||||||||
3014 | |||||||||||
3015 | // Reset the ID to include the new LHS, and check if it is | ||||||||||
3016 | // already cached. | ||||||||||
3017 | ID.clear(); | ||||||||||
3018 | ID.AddInteger(scUDivExpr); | ||||||||||
3019 | ID.AddPointer(LHS); | ||||||||||
3020 | ID.AddPointer(RHS); | ||||||||||
3021 | IP = nullptr; | ||||||||||
3022 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) | ||||||||||
3023 | return S; | ||||||||||
3024 | } | ||||||||||
3025 | } | ||||||||||
3026 | } | ||||||||||
3027 | } | ||||||||||
3028 | // (A*B)/C --> A*(B/C) if safe and B/C can be folded. | ||||||||||
3029 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { | ||||||||||
3030 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
3031 | for (const SCEV *Op : M->operands()) | ||||||||||
3032 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); | ||||||||||
3033 | if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) | ||||||||||
3034 | // Find an operand that's safely divisible. | ||||||||||
3035 | for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { | ||||||||||
3036 | const SCEV *Op = M->getOperand(i); | ||||||||||
3037 | const SCEV *Div = getUDivExpr(Op, RHSC); | ||||||||||
3038 | if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { | ||||||||||
3039 | Operands = SmallVector<const SCEV *, 4>(M->op_begin(), | ||||||||||
3040 | M->op_end()); | ||||||||||
3041 | Operands[i] = Div; | ||||||||||
3042 | return getMulExpr(Operands); | ||||||||||
3043 | } | ||||||||||
3044 | } | ||||||||||
3045 | } | ||||||||||
3046 | |||||||||||
3047 | // (A/B)/C --> A/(B*C) if safe and B*C can be folded. | ||||||||||
3048 | if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { | ||||||||||
3049 | if (auto *DivisorConstant = | ||||||||||
3050 | dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { | ||||||||||
3051 | bool Overflow = false; | ||||||||||
3052 | APInt NewRHS = | ||||||||||
3053 | DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); | ||||||||||
3054 | if (Overflow) { | ||||||||||
3055 | return getConstant(RHSC->getType(), 0, false); | ||||||||||
3056 | } | ||||||||||
3057 | return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); | ||||||||||
3058 | } | ||||||||||
3059 | } | ||||||||||
3060 | |||||||||||
3061 | // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. | ||||||||||
3062 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { | ||||||||||
3063 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
3064 | for (const SCEV *Op : A->operands()) | ||||||||||
3065 | Operands.push_back(getZeroExtendExpr(Op, ExtTy)); | ||||||||||
3066 | if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { | ||||||||||
3067 | Operands.clear(); | ||||||||||
3068 | for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { | ||||||||||
3069 | const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); | ||||||||||
3070 | if (isa<SCEVUDivExpr>(Op) || | ||||||||||
3071 | getMulExpr(Op, RHS) != A->getOperand(i)) | ||||||||||
3072 | break; | ||||||||||
3073 | Operands.push_back(Op); | ||||||||||
3074 | } | ||||||||||
3075 | if (Operands.size() == A->getNumOperands()) | ||||||||||
3076 | return getAddExpr(Operands); | ||||||||||
3077 | } | ||||||||||
3078 | } | ||||||||||
3079 | |||||||||||
3080 | // Fold if both operands are constant. | ||||||||||
3081 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { | ||||||||||
3082 | Constant *LHSCV = LHSC->getValue(); | ||||||||||
3083 | Constant *RHSCV = RHSC->getValue(); | ||||||||||
3084 | return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, | ||||||||||
3085 | RHSCV))); | ||||||||||
3086 | } | ||||||||||
3087 | } | ||||||||||
3088 | } | ||||||||||
3089 | |||||||||||
3090 | // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs | ||||||||||
3091 | // changes). Make sure we get a new one. | ||||||||||
3092 | IP = nullptr; | ||||||||||
3093 | if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; | ||||||||||
3094 | SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), | ||||||||||
3095 | LHS, RHS); | ||||||||||
3096 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
3097 | addToLoopUseLists(S); | ||||||||||
3098 | return S; | ||||||||||
3099 | } | ||||||||||
3100 | |||||||||||
3101 | static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { | ||||||||||
3102 | APInt A = C1->getAPInt().abs(); | ||||||||||
3103 | APInt B = C2->getAPInt().abs(); | ||||||||||
3104 | uint32_t ABW = A.getBitWidth(); | ||||||||||
3105 | uint32_t BBW = B.getBitWidth(); | ||||||||||
3106 | |||||||||||
3107 | if (ABW > BBW) | ||||||||||
3108 | B = B.zext(ABW); | ||||||||||
3109 | else if (ABW < BBW) | ||||||||||
3110 | A = A.zext(BBW); | ||||||||||
3111 | |||||||||||
3112 | return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); | ||||||||||
3113 | } | ||||||||||
3114 | |||||||||||
3115 | /// Get a canonical unsigned division expression, or something simpler if | ||||||||||
3116 | /// possible. There is no representation for an exact udiv in SCEV IR, but we | ||||||||||
3117 | /// can attempt to remove factors from the LHS and RHS. We can't do this when | ||||||||||
3118 | /// it's not exact because the udiv may be clearing bits. | ||||||||||
3119 | const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, | ||||||||||
3120 | const SCEV *RHS) { | ||||||||||
3121 | // TODO: we could try to find factors in all sorts of things, but for now we | ||||||||||
3122 | // just deal with u/exact (multiply, constant). See SCEVDivision towards the | ||||||||||
3123 | // end of this file for inspiration. | ||||||||||
3124 | |||||||||||
3125 | const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); | ||||||||||
3126 | if (!Mul || !Mul->hasNoUnsignedWrap()) | ||||||||||
3127 | return getUDivExpr(LHS, RHS); | ||||||||||
3128 | |||||||||||
3129 | if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { | ||||||||||
3130 | // If the mulexpr multiplies by a constant, then that constant must be the | ||||||||||
3131 | // first element of the mulexpr. | ||||||||||
3132 | if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { | ||||||||||
3133 | if (LHSCst == RHSCst) { | ||||||||||
3134 | SmallVector<const SCEV *, 2> Operands; | ||||||||||
3135 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); | ||||||||||
3136 | return getMulExpr(Operands); | ||||||||||
3137 | } | ||||||||||
3138 | |||||||||||
3139 | // We can't just assume that LHSCst divides RHSCst cleanly, it could be | ||||||||||
3140 | // that there's a factor provided by one of the other terms. We need to | ||||||||||
3141 | // check. | ||||||||||
3142 | APInt Factor = gcd(LHSCst, RHSCst); | ||||||||||
3143 | if (!Factor.isIntN(1)) { | ||||||||||
3144 | LHSCst = | ||||||||||
3145 | cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); | ||||||||||
3146 | RHSCst = | ||||||||||
3147 | cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); | ||||||||||
3148 | SmallVector<const SCEV *, 2> Operands; | ||||||||||
3149 | Operands.push_back(LHSCst); | ||||||||||
3150 | Operands.append(Mul->op_begin() + 1, Mul->op_end()); | ||||||||||
3151 | LHS = getMulExpr(Operands); | ||||||||||
3152 | RHS = RHSCst; | ||||||||||
3153 | Mul = dyn_cast<SCEVMulExpr>(LHS); | ||||||||||
3154 | if (!Mul) | ||||||||||
3155 | return getUDivExactExpr(LHS, RHS); | ||||||||||
3156 | } | ||||||||||
3157 | } | ||||||||||
3158 | } | ||||||||||
3159 | |||||||||||
3160 | for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { | ||||||||||
3161 | if (Mul->getOperand(i) == RHS) { | ||||||||||
3162 | SmallVector<const SCEV *, 2> Operands; | ||||||||||
3163 | Operands.append(Mul->op_begin(), Mul->op_begin() + i); | ||||||||||
3164 | Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); | ||||||||||
3165 | return getMulExpr(Operands); | ||||||||||
3166 | } | ||||||||||
3167 | } | ||||||||||
3168 | |||||||||||
3169 | return getUDivExpr(LHS, RHS); | ||||||||||
3170 | } | ||||||||||
3171 | |||||||||||
3172 | /// Get an add recurrence expression for the specified loop. Simplify the | ||||||||||
3173 | /// expression as much as possible. | ||||||||||
3174 | const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, | ||||||||||
3175 | const Loop *L, | ||||||||||
3176 | SCEV::NoWrapFlags Flags) { | ||||||||||
3177 | SmallVector<const SCEV *, 4> Operands; | ||||||||||
3178 | Operands.push_back(Start); | ||||||||||
3179 | if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) | ||||||||||
3180 | if (StepChrec->getLoop() == L) { | ||||||||||
3181 | Operands.append(StepChrec->op_begin(), StepChrec->op_end()); | ||||||||||
3182 | return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); | ||||||||||
3183 | } | ||||||||||
3184 | |||||||||||
3185 | Operands.push_back(Step); | ||||||||||
3186 | return getAddRecExpr(Operands, L, Flags); | ||||||||||
3187 | } | ||||||||||
3188 | |||||||||||
3189 | /// Get an add recurrence expression for the specified loop. Simplify the | ||||||||||
3190 | /// expression as much as possible. | ||||||||||
3191 | const SCEV * | ||||||||||
3192 | ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, | ||||||||||
3193 | const Loop *L, SCEV::NoWrapFlags Flags) { | ||||||||||
3194 | if (Operands.size() == 1) return Operands[0]; | ||||||||||
3195 | #ifndef NDEBUG | ||||||||||
3196 | Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); | ||||||||||
3197 | for (unsigned i = 1, e = Operands.size(); i != e; ++i) | ||||||||||
3198 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3199, __PRETTY_FUNCTION__)) | ||||||||||
3199 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3199, __PRETTY_FUNCTION__)); | ||||||||||
3200 | for (unsigned i = 0, e = Operands.size(); i != e; ++i) | ||||||||||
3201 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3202, __PRETTY_FUNCTION__)) | ||||||||||
3202 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3202, __PRETTY_FUNCTION__)); | ||||||||||
3203 | #endif | ||||||||||
3204 | |||||||||||
3205 | if (Operands.back()->isZero()) { | ||||||||||
3206 | Operands.pop_back(); | ||||||||||
3207 | return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X | ||||||||||
3208 | } | ||||||||||
3209 | |||||||||||
3210 | // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and | ||||||||||
3211 | // use that information to infer NUW and NSW flags. However, computing a | ||||||||||
3212 | // BE count requires calling getAddRecExpr, so we may not yet have a | ||||||||||
3213 | // meaningful BE count at this point (and if we don't, we'd be stuck | ||||||||||
3214 | // with a SCEVCouldNotCompute as the cached BE count). | ||||||||||
3215 | |||||||||||
3216 | Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); | ||||||||||
3217 | |||||||||||
3218 | // Canonicalize nested AddRecs in by nesting them in order of loop depth. | ||||||||||
3219 | if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { | ||||||||||
3220 | const Loop *NestedLoop = NestedAR->getLoop(); | ||||||||||
3221 | if (L->contains(NestedLoop) | ||||||||||
3222 | ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) | ||||||||||
3223 | : (!NestedLoop->contains(L) && | ||||||||||
3224 | DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { | ||||||||||
3225 | SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), | ||||||||||
3226 | NestedAR->op_end()); | ||||||||||
3227 | Operands[0] = NestedAR->getStart(); | ||||||||||
3228 | // AddRecs require their operands be loop-invariant with respect to their | ||||||||||
3229 | // loops. Don't perform this transformation if it would break this | ||||||||||
3230 | // requirement. | ||||||||||
3231 | bool AllInvariant = all_of( | ||||||||||
3232 | Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); | ||||||||||
3233 | |||||||||||
3234 | if (AllInvariant) { | ||||||||||
3235 | // Create a recurrence for the outer loop with the same step size. | ||||||||||
3236 | // | ||||||||||
3237 | // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the | ||||||||||
3238 | // inner recurrence has the same property. | ||||||||||
3239 | SCEV::NoWrapFlags OuterFlags = | ||||||||||
3240 | maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); | ||||||||||
3241 | |||||||||||
3242 | NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); | ||||||||||
3243 | AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { | ||||||||||
3244 | return isLoopInvariant(Op, NestedLoop); | ||||||||||
3245 | }); | ||||||||||
3246 | |||||||||||
3247 | if (AllInvariant) { | ||||||||||
3248 | // Ok, both add recurrences are valid after the transformation. | ||||||||||
3249 | // | ||||||||||
3250 | // The inner recurrence keeps its NW flag but only keeps NUW/NSW if | ||||||||||
3251 | // the outer recurrence has the same property. | ||||||||||
3252 | SCEV::NoWrapFlags InnerFlags = | ||||||||||
3253 | maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); | ||||||||||
3254 | return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); | ||||||||||
3255 | } | ||||||||||
3256 | } | ||||||||||
3257 | // Reset Operands to its original state. | ||||||||||
3258 | Operands[0] = NestedAR; | ||||||||||
3259 | } | ||||||||||
3260 | } | ||||||||||
3261 | |||||||||||
3262 | // Okay, it looks like we really DO need an addrec expr. Check to see if we | ||||||||||
3263 | // already have one, otherwise create a new one. | ||||||||||
3264 | return getOrCreateAddRecExpr(Operands, L, Flags); | ||||||||||
3265 | } | ||||||||||
3266 | |||||||||||
3267 | const SCEV * | ||||||||||
3268 | ScalarEvolution::getGEPExpr(GEPOperator *GEP, | ||||||||||
3269 | const SmallVectorImpl<const SCEV *> &IndexExprs) { | ||||||||||
3270 | const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); | ||||||||||
3271 | // getSCEV(Base)->getType() has the same address space as Base->getType() | ||||||||||
3272 | // because SCEV::getType() preserves the address space. | ||||||||||
3273 | Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); | ||||||||||
3274 | // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP | ||||||||||
3275 | // instruction to its SCEV, because the Instruction may be guarded by control | ||||||||||
3276 | // flow and the no-overflow bits may not be valid for the expression in any | ||||||||||
3277 | // context. This can be fixed similarly to how these flags are handled for | ||||||||||
3278 | // adds. | ||||||||||
3279 | SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW | ||||||||||
3280 | : SCEV::FlagAnyWrap; | ||||||||||
3281 | |||||||||||
3282 | const SCEV *TotalOffset = getZero(IntIdxTy); | ||||||||||
3283 | Type *CurTy = GEP->getType(); | ||||||||||
3284 | bool FirstIter = true; | ||||||||||
3285 | for (const SCEV *IndexExpr : IndexExprs) { | ||||||||||
3286 | // Compute the (potentially symbolic) offset in bytes for this index. | ||||||||||
3287 | if (StructType *STy = dyn_cast<StructType>(CurTy)) { | ||||||||||
3288 | // For a struct, add the member offset. | ||||||||||
3289 | ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); | ||||||||||
3290 | unsigned FieldNo = Index->getZExtValue(); | ||||||||||
3291 | const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); | ||||||||||
3292 | |||||||||||
3293 | // Add the field offset to the running total offset. | ||||||||||
3294 | TotalOffset = getAddExpr(TotalOffset, FieldOffset); | ||||||||||
3295 | |||||||||||
3296 | // Update CurTy to the type of the field at Index. | ||||||||||
3297 | CurTy = STy->getTypeAtIndex(Index); | ||||||||||
3298 | } else { | ||||||||||
3299 | // Update CurTy to its element type. | ||||||||||
3300 | if (FirstIter) { | ||||||||||
3301 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3302, __PRETTY_FUNCTION__)) | ||||||||||
3302 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3302, __PRETTY_FUNCTION__)); | ||||||||||
3303 | CurTy = GEP->getSourceElementType(); | ||||||||||
3304 | FirstIter = false; | ||||||||||
3305 | } else { | ||||||||||
3306 | CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); | ||||||||||
3307 | } | ||||||||||
3308 | // For an array, add the element offset, explicitly scaled. | ||||||||||
3309 | const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); | ||||||||||
3310 | // Getelementptr indices are signed. | ||||||||||
3311 | IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); | ||||||||||
3312 | |||||||||||
3313 | // Multiply the index by the element size to compute the element offset. | ||||||||||
3314 | const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); | ||||||||||
3315 | |||||||||||
3316 | // Add the element offset to the running total offset. | ||||||||||
3317 | TotalOffset = getAddExpr(TotalOffset, LocalOffset); | ||||||||||
3318 | } | ||||||||||
3319 | } | ||||||||||
3320 | |||||||||||
3321 | // Add the total offset from all the GEP indices to the base. | ||||||||||
3322 | return getAddExpr(BaseExpr, TotalOffset, Wrap); | ||||||||||
3323 | } | ||||||||||
3324 | |||||||||||
3325 | std::tuple<SCEV *, FoldingSetNodeID, void *> | ||||||||||
3326 | ScalarEvolution::findExistingSCEVInCache(int SCEVType, | ||||||||||
3327 | ArrayRef<const SCEV *> Ops) { | ||||||||||
3328 | FoldingSetNodeID ID; | ||||||||||
3329 | void *IP = nullptr; | ||||||||||
3330 | ID.AddInteger(SCEVType); | ||||||||||
3331 | for (unsigned i = 0, e = Ops.size(); i != e; ++i) | ||||||||||
3332 | ID.AddPointer(Ops[i]); | ||||||||||
3333 | return std::tuple<SCEV *, FoldingSetNodeID, void *>( | ||||||||||
3334 | UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); | ||||||||||
3335 | } | ||||||||||
3336 | |||||||||||
3337 | const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, | ||||||||||
3338 | SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3339 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3339, __PRETTY_FUNCTION__)); | ||||||||||
3340 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
3341 | #ifndef NDEBUG | ||||||||||
3342 | Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); | ||||||||||
3343 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) | ||||||||||
3344 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3345, __PRETTY_FUNCTION__)) | ||||||||||
3345 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3345, __PRETTY_FUNCTION__)); | ||||||||||
3346 | #endif | ||||||||||
3347 | |||||||||||
3348 | bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; | ||||||||||
3349 | bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; | ||||||||||
3350 | |||||||||||
3351 | // Sort by complexity, this groups all similar expression types together. | ||||||||||
3352 | GroupByComplexity(Ops, &LI, DT); | ||||||||||
3353 | |||||||||||
3354 | // Check if we have created the same expression before. | ||||||||||
3355 | if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { | ||||||||||
3356 | return S; | ||||||||||
3357 | } | ||||||||||
3358 | |||||||||||
3359 | // If there are any constants, fold them together. | ||||||||||
3360 | unsigned Idx = 0; | ||||||||||
3361 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { | ||||||||||
3362 | ++Idx; | ||||||||||
3363 | assert(Idx < Ops.size())((Idx < Ops.size()) ? static_cast<void> (0) : __assert_fail ("Idx < Ops.size()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3363, __PRETTY_FUNCTION__)); | ||||||||||
3364 | auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { | ||||||||||
3365 | if (Kind == scSMaxExpr) | ||||||||||
3366 | return APIntOps::smax(LHS, RHS); | ||||||||||
3367 | else if (Kind == scSMinExpr) | ||||||||||
3368 | return APIntOps::smin(LHS, RHS); | ||||||||||
3369 | else if (Kind == scUMaxExpr) | ||||||||||
3370 | return APIntOps::umax(LHS, RHS); | ||||||||||
3371 | else if (Kind == scUMinExpr) | ||||||||||
3372 | return APIntOps::umin(LHS, RHS); | ||||||||||
3373 | llvm_unreachable("Unknown SCEV min/max opcode")::llvm::llvm_unreachable_internal("Unknown SCEV min/max opcode" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3373); | ||||||||||
3374 | }; | ||||||||||
3375 | |||||||||||
3376 | while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { | ||||||||||
3377 | // We found two constants, fold them together! | ||||||||||
3378 | ConstantInt *Fold = ConstantInt::get( | ||||||||||
3379 | getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); | ||||||||||
3380 | Ops[0] = getConstant(Fold); | ||||||||||
3381 | Ops.erase(Ops.begin()+1); // Erase the folded element | ||||||||||
3382 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
3383 | LHSC = cast<SCEVConstant>(Ops[0]); | ||||||||||
3384 | } | ||||||||||
3385 | |||||||||||
3386 | bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); | ||||||||||
3387 | bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); | ||||||||||
3388 | |||||||||||
3389 | if (IsMax ? IsMinV : IsMaxV) { | ||||||||||
3390 | // If we are left with a constant minimum(/maximum)-int, strip it off. | ||||||||||
3391 | Ops.erase(Ops.begin()); | ||||||||||
3392 | --Idx; | ||||||||||
3393 | } else if (IsMax ? IsMaxV : IsMinV) { | ||||||||||
3394 | // If we have a max(/min) with a constant maximum(/minimum)-int, | ||||||||||
3395 | // it will always be the extremum. | ||||||||||
3396 | return LHSC; | ||||||||||
3397 | } | ||||||||||
3398 | |||||||||||
3399 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
3400 | } | ||||||||||
3401 | |||||||||||
3402 | // Find the first operation of the same kind | ||||||||||
3403 | while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) | ||||||||||
3404 | ++Idx; | ||||||||||
3405 | |||||||||||
3406 | // Check to see if one of the operands is of the same kind. If so, expand its | ||||||||||
3407 | // operands onto our operand list, and recurse to simplify. | ||||||||||
3408 | if (Idx < Ops.size()) { | ||||||||||
3409 | bool DeletedAny = false; | ||||||||||
3410 | while (Ops[Idx]->getSCEVType() == Kind) { | ||||||||||
3411 | const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); | ||||||||||
3412 | Ops.erase(Ops.begin()+Idx); | ||||||||||
3413 | Ops.append(SMME->op_begin(), SMME->op_end()); | ||||||||||
3414 | DeletedAny = true; | ||||||||||
3415 | } | ||||||||||
3416 | |||||||||||
3417 | if (DeletedAny) | ||||||||||
3418 | return getMinMaxExpr(Kind, Ops); | ||||||||||
3419 | } | ||||||||||
3420 | |||||||||||
3421 | // Okay, check to see if the same value occurs in the operand list twice. If | ||||||||||
3422 | // so, delete one. Since we sorted the list, these values are required to | ||||||||||
3423 | // be adjacent. | ||||||||||
3424 | llvm::CmpInst::Predicate GEPred = | ||||||||||
3425 | IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; | ||||||||||
3426 | llvm::CmpInst::Predicate LEPred = | ||||||||||
3427 | IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; | ||||||||||
3428 | llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; | ||||||||||
3429 | llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; | ||||||||||
3430 | for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { | ||||||||||
3431 | if (Ops[i] == Ops[i + 1] || | ||||||||||
3432 | isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { | ||||||||||
3433 | // X op Y op Y --> X op Y | ||||||||||
3434 | // X op Y --> X, if we know X, Y are ordered appropriately | ||||||||||
3435 | Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); | ||||||||||
3436 | --i; | ||||||||||
3437 | --e; | ||||||||||
3438 | } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], | ||||||||||
3439 | Ops[i + 1])) { | ||||||||||
3440 | // X op Y --> Y, if we know X, Y are ordered appropriately | ||||||||||
3441 | Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); | ||||||||||
3442 | --i; | ||||||||||
3443 | --e; | ||||||||||
3444 | } | ||||||||||
3445 | } | ||||||||||
3446 | |||||||||||
3447 | if (Ops.size() == 1) return Ops[0]; | ||||||||||
3448 | |||||||||||
3449 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3449, __PRETTY_FUNCTION__)); | ||||||||||
3450 | |||||||||||
3451 | // Okay, it looks like we really DO need an expr. Check to see if we | ||||||||||
3452 | // already have one, otherwise create a new one. | ||||||||||
3453 | const SCEV *ExistingSCEV; | ||||||||||
3454 | FoldingSetNodeID ID; | ||||||||||
3455 | void *IP; | ||||||||||
3456 | std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); | ||||||||||
3457 | if (ExistingSCEV) | ||||||||||
3458 | return ExistingSCEV; | ||||||||||
3459 | const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); | ||||||||||
3460 | std::uninitialized_copy(Ops.begin(), Ops.end(), O); | ||||||||||
3461 | SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( | ||||||||||
3462 | ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); | ||||||||||
3463 | |||||||||||
3464 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
3465 | addToLoopUseLists(S); | ||||||||||
3466 | return S; | ||||||||||
3467 | } | ||||||||||
3468 | |||||||||||
3469 | const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { | ||||||||||
3470 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; | ||||||||||
3471 | return getSMaxExpr(Ops); | ||||||||||
3472 | } | ||||||||||
3473 | |||||||||||
3474 | const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3475 | return getMinMaxExpr(scSMaxExpr, Ops); | ||||||||||
3476 | } | ||||||||||
3477 | |||||||||||
3478 | const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { | ||||||||||
3479 | SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; | ||||||||||
3480 | return getUMaxExpr(Ops); | ||||||||||
3481 | } | ||||||||||
3482 | |||||||||||
3483 | const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3484 | return getMinMaxExpr(scUMaxExpr, Ops); | ||||||||||
3485 | } | ||||||||||
3486 | |||||||||||
3487 | const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, | ||||||||||
3488 | const SCEV *RHS) { | ||||||||||
3489 | SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; | ||||||||||
3490 | return getSMinExpr(Ops); | ||||||||||
3491 | } | ||||||||||
3492 | |||||||||||
3493 | const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3494 | return getMinMaxExpr(scSMinExpr, Ops); | ||||||||||
3495 | } | ||||||||||
3496 | |||||||||||
3497 | const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, | ||||||||||
3498 | const SCEV *RHS) { | ||||||||||
3499 | SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; | ||||||||||
3500 | return getUMinExpr(Ops); | ||||||||||
3501 | } | ||||||||||
3502 | |||||||||||
3503 | const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3504 | return getMinMaxExpr(scUMinExpr, Ops); | ||||||||||
3505 | } | ||||||||||
3506 | |||||||||||
3507 | const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { | ||||||||||
3508 | // We can bypass creating a target-independent | ||||||||||
3509 | // constant expression and then folding it back into a ConstantInt. | ||||||||||
3510 | // This is just a compile-time optimization. | ||||||||||
3511 | if (isa<ScalableVectorType>(AllocTy)) { | ||||||||||
3512 | Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); | ||||||||||
3513 | Constant *One = ConstantInt::get(IntTy, 1); | ||||||||||
3514 | Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); | ||||||||||
3515 | return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); | ||||||||||
3516 | } | ||||||||||
3517 | return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); | ||||||||||
3518 | } | ||||||||||
3519 | |||||||||||
3520 | const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, | ||||||||||
3521 | StructType *STy, | ||||||||||
3522 | unsigned FieldNo) { | ||||||||||
3523 | // We can bypass creating a target-independent | ||||||||||
3524 | // constant expression and then folding it back into a ConstantInt. | ||||||||||
3525 | // This is just a compile-time optimization. | ||||||||||
3526 | return getConstant( | ||||||||||
3527 | IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); | ||||||||||
3528 | } | ||||||||||
3529 | |||||||||||
3530 | const SCEV *ScalarEvolution::getUnknown(Value *V) { | ||||||||||
3531 | // Don't attempt to do anything other than create a SCEVUnknown object | ||||||||||
3532 | // here. createSCEV only calls getUnknown after checking for all other | ||||||||||
3533 | // interesting possibilities, and any other code that calls getUnknown | ||||||||||
3534 | // is doing so in order to hide a value from SCEV canonicalization. | ||||||||||
3535 | |||||||||||
3536 | FoldingSetNodeID ID; | ||||||||||
3537 | ID.AddInteger(scUnknown); | ||||||||||
3538 | ID.AddPointer(V); | ||||||||||
3539 | void *IP = nullptr; | ||||||||||
3540 | if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { | ||||||||||
3541 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3542, __PRETTY_FUNCTION__)) | ||||||||||
3542 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3542, __PRETTY_FUNCTION__)); | ||||||||||
3543 | return S; | ||||||||||
3544 | } | ||||||||||
3545 | SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, | ||||||||||
3546 | FirstUnknown); | ||||||||||
3547 | FirstUnknown = cast<SCEVUnknown>(S); | ||||||||||
3548 | UniqueSCEVs.InsertNode(S, IP); | ||||||||||
3549 | return S; | ||||||||||
3550 | } | ||||||||||
3551 | |||||||||||
3552 | //===----------------------------------------------------------------------===// | ||||||||||
3553 | // Basic SCEV Analysis and PHI Idiom Recognition Code | ||||||||||
3554 | // | ||||||||||
3555 | |||||||||||
3556 | /// Test if values of the given type are analyzable within the SCEV | ||||||||||
3557 | /// framework. This primarily includes integer types, and it can optionally | ||||||||||
3558 | /// include pointer types if the ScalarEvolution class has access to | ||||||||||
3559 | /// target-specific information. | ||||||||||
3560 | bool ScalarEvolution::isSCEVable(Type *Ty) const { | ||||||||||
3561 | // Integers and pointers are always SCEVable. | ||||||||||
3562 | return Ty->isIntOrPtrTy(); | ||||||||||
3563 | } | ||||||||||
3564 | |||||||||||
3565 | /// Return the size in bits of the specified type, for which isSCEVable must | ||||||||||
3566 | /// return true. | ||||||||||
3567 | uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { | ||||||||||
3568 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3568, __PRETTY_FUNCTION__)); | ||||||||||
3569 | if (Ty->isPointerTy()) | ||||||||||
3570 | return getDataLayout().getIndexTypeSizeInBits(Ty); | ||||||||||
3571 | return getDataLayout().getTypeSizeInBits(Ty); | ||||||||||
3572 | } | ||||||||||
3573 | |||||||||||
3574 | /// Return a type with the same bitwidth as the given type and which represents | ||||||||||
3575 | /// how SCEV will treat the given type, for which isSCEVable must return | ||||||||||
3576 | /// true. For pointer types, this is the pointer index sized integer type. | ||||||||||
3577 | Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { | ||||||||||
3578 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3578, __PRETTY_FUNCTION__)); | ||||||||||
3579 | |||||||||||
3580 | if (Ty->isIntegerTy()) | ||||||||||
3581 | return Ty; | ||||||||||
3582 | |||||||||||
3583 | // The only other support type is pointer. | ||||||||||
3584 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3584, __PRETTY_FUNCTION__)); | ||||||||||
3585 | return getDataLayout().getIndexType(Ty); | ||||||||||
3586 | } | ||||||||||
3587 | |||||||||||
3588 | Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { | ||||||||||
3589 | return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; | ||||||||||
3590 | } | ||||||||||
3591 | |||||||||||
3592 | const SCEV *ScalarEvolution::getCouldNotCompute() { | ||||||||||
3593 | return CouldNotCompute.get(); | ||||||||||
3594 | } | ||||||||||
3595 | |||||||||||
3596 | bool ScalarEvolution::checkValidity(const SCEV *S) const { | ||||||||||
3597 | bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { | ||||||||||
3598 | auto *SU = dyn_cast<SCEVUnknown>(S); | ||||||||||
3599 | return SU && SU->getValue() == nullptr; | ||||||||||
3600 | }); | ||||||||||
3601 | |||||||||||
3602 | return !ContainsNulls; | ||||||||||
3603 | } | ||||||||||
3604 | |||||||||||
3605 | bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { | ||||||||||
3606 | HasRecMapType::iterator I = HasRecMap.find(S); | ||||||||||
3607 | if (I != HasRecMap.end()) | ||||||||||
3608 | return I->second; | ||||||||||
3609 | |||||||||||
3610 | bool FoundAddRec = | ||||||||||
3611 | SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); | ||||||||||
3612 | HasRecMap.insert({S, FoundAddRec}); | ||||||||||
3613 | return FoundAddRec; | ||||||||||
3614 | } | ||||||||||
3615 | |||||||||||
3616 | /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. | ||||||||||
3617 | /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an | ||||||||||
3618 | /// offset I, then return {S', I}, else return {\p S, nullptr}. | ||||||||||
3619 | static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { | ||||||||||
3620 | const auto *Add = dyn_cast<SCEVAddExpr>(S); | ||||||||||
3621 | if (!Add) | ||||||||||
3622 | return {S, nullptr}; | ||||||||||
3623 | |||||||||||
3624 | if (Add->getNumOperands() != 2) | ||||||||||
3625 | return {S, nullptr}; | ||||||||||
3626 | |||||||||||
3627 | auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); | ||||||||||
3628 | if (!ConstOp) | ||||||||||
3629 | return {S, nullptr}; | ||||||||||
3630 | |||||||||||
3631 | return {Add->getOperand(1), ConstOp->getValue()}; | ||||||||||
3632 | } | ||||||||||
3633 | |||||||||||
3634 | /// Return the ValueOffsetPair set for \p S. \p S can be represented | ||||||||||
3635 | /// by the value and offset from any ValueOffsetPair in the set. | ||||||||||
3636 | SetVector<ScalarEvolution::ValueOffsetPair> * | ||||||||||
3637 | ScalarEvolution::getSCEVValues(const SCEV *S) { | ||||||||||
3638 | ExprValueMapType::iterator SI = ExprValueMap.find_as(S); | ||||||||||
3639 | if (SI == ExprValueMap.end()) | ||||||||||
3640 | return nullptr; | ||||||||||
3641 | #ifndef NDEBUG | ||||||||||
3642 | if (VerifySCEVMap) { | ||||||||||
3643 | // Check there is no dangling Value in the set returned. | ||||||||||
3644 | for (const auto &VE : SI->second) | ||||||||||
3645 | assert(ValueExprMap.count(VE.first))((ValueExprMap.count(VE.first)) ? static_cast<void> (0) : __assert_fail ("ValueExprMap.count(VE.first)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3645, __PRETTY_FUNCTION__)); | ||||||||||
3646 | } | ||||||||||
3647 | #endif | ||||||||||
3648 | return &SI->second; | ||||||||||
3649 | } | ||||||||||
3650 | |||||||||||
3651 | /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) | ||||||||||
3652 | /// cannot be used separately. eraseValueFromMap should be used to remove | ||||||||||
3653 | /// V from ValueExprMap and ExprValueMap at the same time. | ||||||||||
3654 | void ScalarEvolution::eraseValueFromMap(Value *V) { | ||||||||||
3655 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); | ||||||||||
3656 | if (I != ValueExprMap.end()) { | ||||||||||
3657 | const SCEV *S = I->second; | ||||||||||
3658 | // Remove {V, 0} from the set of ExprValueMap[S] | ||||||||||
3659 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) | ||||||||||
3660 | SV->remove({V, nullptr}); | ||||||||||
3661 | |||||||||||
3662 | // Remove {V, Offset} from the set of ExprValueMap[Stripped] | ||||||||||
3663 | const SCEV *Stripped; | ||||||||||
3664 | ConstantInt *Offset; | ||||||||||
3665 | std::tie(Stripped, Offset) = splitAddExpr(S); | ||||||||||
3666 | if (Offset != nullptr) { | ||||||||||
3667 | if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) | ||||||||||
3668 | SV->remove({V, Offset}); | ||||||||||
3669 | } | ||||||||||
3670 | ValueExprMap.erase(V); | ||||||||||
3671 | } | ||||||||||
3672 | } | ||||||||||
3673 | |||||||||||
3674 | /// Check whether value has nuw/nsw/exact set but SCEV does not. | ||||||||||
3675 | /// TODO: In reality it is better to check the poison recursively | ||||||||||
3676 | /// but this is better than nothing. | ||||||||||
3677 | static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { | ||||||||||
3678 | if (auto *I = dyn_cast<Instruction>(V)) { | ||||||||||
3679 | if (isa<OverflowingBinaryOperator>(I)) { | ||||||||||
3680 | if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { | ||||||||||
3681 | if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) | ||||||||||
3682 | return true; | ||||||||||
3683 | if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) | ||||||||||
3684 | return true; | ||||||||||
3685 | } | ||||||||||
3686 | } else if (isa<PossiblyExactOperator>(I) && I->isExact()) | ||||||||||
3687 | return true; | ||||||||||
3688 | } | ||||||||||
3689 | return false; | ||||||||||
3690 | } | ||||||||||
3691 | |||||||||||
3692 | /// Return an existing SCEV if it exists, otherwise analyze the expression and | ||||||||||
3693 | /// create a new one. | ||||||||||
3694 | const SCEV *ScalarEvolution::getSCEV(Value *V) { | ||||||||||
3695 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3695, __PRETTY_FUNCTION__)); | ||||||||||
3696 | |||||||||||
3697 | const SCEV *S = getExistingSCEV(V); | ||||||||||
3698 | if (S == nullptr) { | ||||||||||
3699 | S = createSCEV(V); | ||||||||||
3700 | // During PHI resolution, it is possible to create two SCEVs for the same | ||||||||||
3701 | // V, so it is needed to double check whether V->S is inserted into | ||||||||||
3702 | // ValueExprMap before insert S->{V, 0} into ExprValueMap. | ||||||||||
3703 | std::pair<ValueExprMapType::iterator, bool> Pair = | ||||||||||
3704 | ValueExprMap.insert({SCEVCallbackVH(V, this), S}); | ||||||||||
3705 | if (Pair.second && !SCEVLostPoisonFlags(S, V)) { | ||||||||||
3706 | ExprValueMap[S].insert({V, nullptr}); | ||||||||||
3707 | |||||||||||
3708 | // If S == Stripped + Offset, add Stripped -> {V, Offset} into | ||||||||||
3709 | // ExprValueMap. | ||||||||||
3710 | const SCEV *Stripped = S; | ||||||||||
3711 | ConstantInt *Offset = nullptr; | ||||||||||
3712 | std::tie(Stripped, Offset) = splitAddExpr(S); | ||||||||||
3713 | // If stripped is SCEVUnknown, don't bother to save | ||||||||||
3714 | // Stripped -> {V, offset}. It doesn't simplify and sometimes even | ||||||||||
3715 | // increase the complexity of the expansion code. | ||||||||||
3716 | // If V is GetElementPtrInst, don't save Stripped -> {V, offset} | ||||||||||
3717 | // because it may generate add/sub instead of GEP in SCEV expansion. | ||||||||||
3718 | if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && | ||||||||||
3719 | !isa<GetElementPtrInst>(V)) | ||||||||||
3720 | ExprValueMap[Stripped].insert({V, Offset}); | ||||||||||
3721 | } | ||||||||||
3722 | } | ||||||||||
3723 | return S; | ||||||||||
3724 | } | ||||||||||
3725 | |||||||||||
3726 | const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { | ||||||||||
3727 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3727, __PRETTY_FUNCTION__)); | ||||||||||
3728 | |||||||||||
3729 | ValueExprMapType::iterator I = ValueExprMap.find_as(V); | ||||||||||
3730 | if (I != ValueExprMap.end()) { | ||||||||||
3731 | const SCEV *S = I->second; | ||||||||||
3732 | if (checkValidity(S)) | ||||||||||
3733 | return S; | ||||||||||
3734 | eraseValueFromMap(V); | ||||||||||
3735 | forgetMemoizedResults(S); | ||||||||||
3736 | } | ||||||||||
3737 | return nullptr; | ||||||||||
3738 | } | ||||||||||
3739 | |||||||||||
3740 | /// Return a SCEV corresponding to -V = -1*V | ||||||||||
3741 | const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, | ||||||||||
3742 | SCEV::NoWrapFlags Flags) { | ||||||||||
3743 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) | ||||||||||
3744 | return getConstant( | ||||||||||
3745 | cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); | ||||||||||
3746 | |||||||||||
3747 | Type *Ty = V->getType(); | ||||||||||
3748 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
3749 | return getMulExpr( | ||||||||||
3750 | V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); | ||||||||||
3751 | } | ||||||||||
3752 | |||||||||||
3753 | /// If Expr computes ~A, return A else return nullptr | ||||||||||
3754 | static const SCEV *MatchNotExpr(const SCEV *Expr) { | ||||||||||
3755 | const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); | ||||||||||
3756 | if (!Add || Add->getNumOperands() != 2 || | ||||||||||
3757 | !Add->getOperand(0)->isAllOnesValue()) | ||||||||||
3758 | return nullptr; | ||||||||||
3759 | |||||||||||
3760 | const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); | ||||||||||
3761 | if (!AddRHS || AddRHS->getNumOperands() != 2 || | ||||||||||
3762 | !AddRHS->getOperand(0)->isAllOnesValue()) | ||||||||||
3763 | return nullptr; | ||||||||||
3764 | |||||||||||
3765 | return AddRHS->getOperand(1); | ||||||||||
3766 | } | ||||||||||
3767 | |||||||||||
3768 | /// Return a SCEV corresponding to ~V = -1-V | ||||||||||
3769 | const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { | ||||||||||
3770 | if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) | ||||||||||
3771 | return getConstant( | ||||||||||
3772 | cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); | ||||||||||
3773 | |||||||||||
3774 | // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) | ||||||||||
3775 | if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { | ||||||||||
3776 | auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { | ||||||||||
3777 | SmallVector<const SCEV *, 2> MatchedOperands; | ||||||||||
3778 | for (const SCEV *Operand : MME->operands()) { | ||||||||||
3779 | const SCEV *Matched = MatchNotExpr(Operand); | ||||||||||
3780 | if (!Matched) | ||||||||||
3781 | return (const SCEV *)nullptr; | ||||||||||
3782 | MatchedOperands.push_back(Matched); | ||||||||||
3783 | } | ||||||||||
3784 | return getMinMaxExpr( | ||||||||||
3785 | SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), | ||||||||||
3786 | MatchedOperands); | ||||||||||
3787 | }; | ||||||||||
3788 | if (const SCEV *Replaced = MatchMinMaxNegation(MME)) | ||||||||||
3789 | return Replaced; | ||||||||||
3790 | } | ||||||||||
3791 | |||||||||||
3792 | Type *Ty = V->getType(); | ||||||||||
3793 | Ty = getEffectiveSCEVType(Ty); | ||||||||||
3794 | const SCEV *AllOnes = | ||||||||||
3795 | getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); | ||||||||||
3796 | return getMinusSCEV(AllOnes, V); | ||||||||||
3797 | } | ||||||||||
3798 | |||||||||||
3799 | const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, | ||||||||||
3800 | SCEV::NoWrapFlags Flags, | ||||||||||
3801 | unsigned Depth) { | ||||||||||
3802 | // Fast path: X - X --> 0. | ||||||||||
3803 | if (LHS == RHS) | ||||||||||
3804 | return getZero(LHS->getType()); | ||||||||||
3805 | |||||||||||
3806 | // We represent LHS - RHS as LHS + (-1)*RHS. This transformation | ||||||||||
3807 | // makes it so that we cannot make much use of NUW. | ||||||||||
3808 | auto AddFlags = SCEV::FlagAnyWrap; | ||||||||||
3809 | const bool RHSIsNotMinSigned = | ||||||||||
3810 | !getSignedRangeMin(RHS).isMinSignedValue(); | ||||||||||
3811 | if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { | ||||||||||
3812 | // Let M be the minimum representable signed value. Then (-1)*RHS | ||||||||||
3813 | // signed-wraps if and only if RHS is M. That can happen even for | ||||||||||
3814 | // a NSW subtraction because e.g. (-1)*M signed-wraps even though | ||||||||||
3815 | // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + | ||||||||||
3816 | // (-1)*RHS, we need to prove that RHS != M. | ||||||||||
3817 | // | ||||||||||
3818 | // If LHS is non-negative and we know that LHS - RHS does not | ||||||||||
3819 | // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap | ||||||||||
3820 | // either by proving that RHS > M or that LHS >= 0. | ||||||||||
3821 | if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { | ||||||||||
3822 | AddFlags = SCEV::FlagNSW; | ||||||||||
3823 | } | ||||||||||
3824 | } | ||||||||||
3825 | |||||||||||
3826 | // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - | ||||||||||
3827 | // RHS is NSW and LHS >= 0. | ||||||||||
3828 | // | ||||||||||
3829 | // The difficulty here is that the NSW flag may have been proven | ||||||||||
3830 | // relative to a loop that is to be found in a recurrence in LHS and | ||||||||||
3831 | // not in RHS. Applying NSW to (-1)*M may then let the NSW have a | ||||||||||
3832 | // larger scope than intended. | ||||||||||
3833 | auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; | ||||||||||
3834 | |||||||||||
3835 | return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); | ||||||||||
3836 | } | ||||||||||
3837 | |||||||||||
3838 | const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, | ||||||||||
3839 | unsigned Depth) { | ||||||||||
3840 | Type *SrcTy = V->getType(); | ||||||||||
3841 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3842, __PRETTY_FUNCTION__)) | ||||||||||
3842 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3842, __PRETTY_FUNCTION__)); | ||||||||||
3843 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3844 | return V; // No conversion | ||||||||||
3845 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) | ||||||||||
3846 | return getTruncateExpr(V, Ty, Depth); | ||||||||||
3847 | return getZeroExtendExpr(V, Ty, Depth); | ||||||||||
3848 | } | ||||||||||
3849 | |||||||||||
3850 | const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, | ||||||||||
3851 | unsigned Depth) { | ||||||||||
3852 | Type *SrcTy = V->getType(); | ||||||||||
3853 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3854, __PRETTY_FUNCTION__)) | ||||||||||
3854 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3854, __PRETTY_FUNCTION__)); | ||||||||||
3855 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3856 | return V; // No conversion | ||||||||||
3857 | if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) | ||||||||||
3858 | return getTruncateExpr(V, Ty, Depth); | ||||||||||
3859 | return getSignExtendExpr(V, Ty, Depth); | ||||||||||
3860 | } | ||||||||||
3861 | |||||||||||
3862 | const SCEV * | ||||||||||
3863 | ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { | ||||||||||
3864 | Type *SrcTy = V->getType(); | ||||||||||
3865 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3866, __PRETTY_FUNCTION__)) | ||||||||||
3866 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3866, __PRETTY_FUNCTION__)); | ||||||||||
3867 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3868, __PRETTY_FUNCTION__)) | ||||||||||
3868 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3868, __PRETTY_FUNCTION__)); | ||||||||||
3869 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3870 | return V; // No conversion | ||||||||||
3871 | return getZeroExtendExpr(V, Ty); | ||||||||||
3872 | } | ||||||||||
3873 | |||||||||||
3874 | const SCEV * | ||||||||||
3875 | ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { | ||||||||||
3876 | Type *SrcTy = V->getType(); | ||||||||||
3877 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3878, __PRETTY_FUNCTION__)) | ||||||||||
3878 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3878, __PRETTY_FUNCTION__)); | ||||||||||
3879 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3880, __PRETTY_FUNCTION__)) | ||||||||||
3880 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3880, __PRETTY_FUNCTION__)); | ||||||||||
3881 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3882 | return V; // No conversion | ||||||||||
3883 | return getSignExtendExpr(V, Ty); | ||||||||||
3884 | } | ||||||||||
3885 | |||||||||||
3886 | const SCEV * | ||||||||||
3887 | ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { | ||||||||||
3888 | Type *SrcTy = V->getType(); | ||||||||||
3889 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3890, __PRETTY_FUNCTION__)) | ||||||||||
3890 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3890, __PRETTY_FUNCTION__)); | ||||||||||
3891 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3892, __PRETTY_FUNCTION__)) | ||||||||||
3892 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3892, __PRETTY_FUNCTION__)); | ||||||||||
3893 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3894 | return V; // No conversion | ||||||||||
3895 | return getAnyExtendExpr(V, Ty); | ||||||||||
3896 | } | ||||||||||
3897 | |||||||||||
3898 | const SCEV * | ||||||||||
3899 | ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { | ||||||||||
3900 | Type *SrcTy = V->getType(); | ||||||||||
3901 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3902, __PRETTY_FUNCTION__)) | ||||||||||
3902 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3902, __PRETTY_FUNCTION__)); | ||||||||||
3903 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3904, __PRETTY_FUNCTION__)) | ||||||||||
3904 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3904, __PRETTY_FUNCTION__)); | ||||||||||
3905 | if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) | ||||||||||
3906 | return V; // No conversion | ||||||||||
3907 | return getTruncateExpr(V, Ty); | ||||||||||
3908 | } | ||||||||||
3909 | |||||||||||
3910 | const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, | ||||||||||
3911 | const SCEV *RHS) { | ||||||||||
3912 | const SCEV *PromotedLHS = LHS; | ||||||||||
3913 | const SCEV *PromotedRHS = RHS; | ||||||||||
3914 | |||||||||||
3915 | if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) | ||||||||||
3916 | PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); | ||||||||||
3917 | else | ||||||||||
3918 | PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); | ||||||||||
3919 | |||||||||||
3920 | return getUMaxExpr(PromotedLHS, PromotedRHS); | ||||||||||
3921 | } | ||||||||||
3922 | |||||||||||
3923 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, | ||||||||||
3924 | const SCEV *RHS) { | ||||||||||
3925 | SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; | ||||||||||
3926 | return getUMinFromMismatchedTypes(Ops); | ||||||||||
3927 | } | ||||||||||
3928 | |||||||||||
3929 | const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( | ||||||||||
3930 | SmallVectorImpl<const SCEV *> &Ops) { | ||||||||||
3931 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 3931, __PRETTY_FUNCTION__)); | ||||||||||
3932 | // Trivial case. | ||||||||||
3933 | if (Ops.size() == 1) | ||||||||||
3934 | return Ops[0]; | ||||||||||
3935 | |||||||||||
3936 | // Find the max type first. | ||||||||||
3937 | Type *MaxType = nullptr; | ||||||||||
3938 | for (auto *S : Ops) | ||||||||||
3939 | if (MaxType) | ||||||||||
3940 | MaxType = getWiderType(MaxType, S->getType()); | ||||||||||
3941 | else | ||||||||||
3942 | MaxType = S->getType(); | ||||||||||
3943 | |||||||||||
3944 | // Extend all ops to max type. | ||||||||||
3945 | SmallVector<const SCEV *, 2> PromotedOps; | ||||||||||
3946 | for (auto *S : Ops) | ||||||||||
3947 | PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); | ||||||||||
3948 | |||||||||||
3949 | // Generate umin. | ||||||||||
3950 | return getUMinExpr(PromotedOps); | ||||||||||
3951 | } | ||||||||||
3952 | |||||||||||
3953 | const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { | ||||||||||
3954 | // A pointer operand may evaluate to a nonpointer expression, such as null. | ||||||||||
3955 | if (!V->getType()->isPointerTy()) | ||||||||||
3956 | return V; | ||||||||||
3957 | |||||||||||
3958 | while (true) { | ||||||||||
3959 | if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { | ||||||||||
3960 | V = Cast->getOperand(); | ||||||||||
3961 | } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { | ||||||||||
3962 | const SCEV *PtrOp = nullptr; | ||||||||||
3963 | for (const SCEV *NAryOp : NAry->operands()) { | ||||||||||
3964 | if (NAryOp->getType()->isPointerTy()) { | ||||||||||
3965 | // Cannot find the base of an expression with multiple pointer ops. | ||||||||||
3966 | if (PtrOp) | ||||||||||
3967 | return V; | ||||||||||
3968 | PtrOp = NAryOp; | ||||||||||
3969 | } | ||||||||||
3970 | } | ||||||||||
3971 | if (!PtrOp) // All operands were non-pointer. | ||||||||||
3972 | return V; | ||||||||||
3973 | V = PtrOp; | ||||||||||
3974 | } else // Not something we can look further into. | ||||||||||
3975 | return V; | ||||||||||
3976 | } | ||||||||||
3977 | } | ||||||||||
3978 | |||||||||||
3979 | /// Push users of the given Instruction onto the given Worklist. | ||||||||||
3980 | static void | ||||||||||
3981 | PushDefUseChildren(Instruction *I, | ||||||||||
3982 | SmallVectorImpl<Instruction *> &Worklist) { | ||||||||||
3983 | // Push the def-use children onto the Worklist stack. | ||||||||||
3984 | for (User *U : I->users()) | ||||||||||
3985 | Worklist.push_back(cast<Instruction>(U)); | ||||||||||
3986 | } | ||||||||||
3987 | |||||||||||
3988 | void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { | ||||||||||
3989 | SmallVector<Instruction *, 16> Worklist; | ||||||||||
3990 | PushDefUseChildren(PN, Worklist); | ||||||||||
3991 | |||||||||||
3992 | SmallPtrSet<Instruction *, 8> Visited; | ||||||||||
3993 | Visited.insert(PN); | ||||||||||
3994 | while (!Worklist.empty()) { | ||||||||||
3995 | Instruction *I = Worklist.pop_back_val(); | ||||||||||
3996 | if (!Visited.insert(I).second) | ||||||||||
3997 | continue; | ||||||||||
3998 | |||||||||||
3999 | auto It = ValueExprMap.find_as(static_cast<Value *>(I)); | ||||||||||
4000 | if (It != ValueExprMap.end()) { | ||||||||||
4001 | const SCEV *Old = It->second; | ||||||||||
4002 | |||||||||||
4003 | // Short-circuit the def-use traversal if the symbolic name | ||||||||||
4004 | // ceases to appear in expressions. | ||||||||||
4005 | if (Old != SymName && !hasOperand(Old, SymName)) | ||||||||||
4006 | continue; | ||||||||||
4007 | |||||||||||
4008 | // SCEVUnknown for a PHI either means that it has an unrecognized | ||||||||||
4009 | // structure, it's a PHI that's in the progress of being computed | ||||||||||
4010 | // by createNodeForPHI, or it's a single-value PHI. In the first case, | ||||||||||
4011 | // additional loop trip count information isn't going to change anything. | ||||||||||
4012 | // In the second case, createNodeForPHI will perform the necessary | ||||||||||
4013 | // updates on its own when it gets to that point. In the third, we do | ||||||||||
4014 | // want to forget the SCEVUnknown. | ||||||||||
4015 | if (!isa<PHINode>(I) || | ||||||||||
4016 | !isa<SCEVUnknown>(Old) || | ||||||||||
4017 | (I != PN && Old == SymName)) { | ||||||||||
4018 | eraseValueFromMap(It->first); | ||||||||||
4019 | forgetMemoizedResults(Old); | ||||||||||
4020 | } | ||||||||||
4021 | } | ||||||||||
4022 | |||||||||||
4023 | PushDefUseChildren(I, Worklist); | ||||||||||
4024 | } | ||||||||||
4025 | } | ||||||||||
4026 | |||||||||||
4027 | namespace { | ||||||||||
4028 | |||||||||||
4029 | /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start | ||||||||||
4030 | /// expression in case its Loop is L. If it is not L then | ||||||||||
4031 | /// if IgnoreOtherLoops is true then use AddRec itself | ||||||||||
4032 | /// otherwise rewrite cannot be done. | ||||||||||
4033 | /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. | ||||||||||
4034 | class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { | ||||||||||
4035 | public: | ||||||||||
4036 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, | ||||||||||
4037 | bool IgnoreOtherLoops = true) { | ||||||||||
4038 | SCEVInitRewriter Rewriter(L, SE); | ||||||||||
4039 | const SCEV *Result = Rewriter.visit(S); | ||||||||||
4040 | if (Rewriter.hasSeenLoopVariantSCEVUnknown()) | ||||||||||
4041 | return SE.getCouldNotCompute(); | ||||||||||
4042 | return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops | ||||||||||
4043 | ? SE.getCouldNotCompute() | ||||||||||
4044 | : Result; | ||||||||||
4045 | } | ||||||||||
4046 | |||||||||||
4047 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
4048 | if (!SE.isLoopInvariant(Expr, L)) | ||||||||||
4049 | SeenLoopVariantSCEVUnknown = true; | ||||||||||
4050 | return Expr; | ||||||||||
4051 | } | ||||||||||
4052 | |||||||||||
4053 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { | ||||||||||
4054 | // Only re-write AddRecExprs for this loop. | ||||||||||
4055 | if (Expr->getLoop() == L) | ||||||||||
4056 | return Expr->getStart(); | ||||||||||
4057 | SeenOtherLoops = true; | ||||||||||
4058 | return Expr; | ||||||||||
4059 | } | ||||||||||
4060 | |||||||||||
4061 | bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } | ||||||||||
4062 | |||||||||||
4063 | bool hasSeenOtherLoops() { return SeenOtherLoops; } | ||||||||||
4064 | |||||||||||
4065 | private: | ||||||||||
4066 | explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) | ||||||||||
4067 | : SCEVRewriteVisitor(SE), L(L) {} | ||||||||||
4068 | |||||||||||
4069 | const Loop *L; | ||||||||||
4070 | bool SeenLoopVariantSCEVUnknown = false; | ||||||||||
4071 | bool SeenOtherLoops = false; | ||||||||||
4072 | }; | ||||||||||
4073 | |||||||||||
4074 | /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post | ||||||||||
4075 | /// increment expression in case its Loop is L. If it is not L then | ||||||||||
4076 | /// use AddRec itself. | ||||||||||
4077 | /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. | ||||||||||
4078 | class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { | ||||||||||
4079 | public: | ||||||||||
4080 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { | ||||||||||
4081 | SCEVPostIncRewriter Rewriter(L, SE); | ||||||||||
4082 | const SCEV *Result = Rewriter.visit(S); | ||||||||||
4083 | return Rewriter.hasSeenLoopVariantSCEVUnknown() | ||||||||||
4084 | ? SE.getCouldNotCompute() | ||||||||||
4085 | : Result; | ||||||||||
4086 | } | ||||||||||
4087 | |||||||||||
4088 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
4089 | if (!SE.isLoopInvariant(Expr, L)) | ||||||||||
4090 | SeenLoopVariantSCEVUnknown = true; | ||||||||||
4091 | return Expr; | ||||||||||
4092 | } | ||||||||||
4093 | |||||||||||
4094 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { | ||||||||||
4095 | // Only re-write AddRecExprs for this loop. | ||||||||||
4096 | if (Expr->getLoop() == L) | ||||||||||
4097 | return Expr->getPostIncExpr(SE); | ||||||||||
4098 | SeenOtherLoops = true; | ||||||||||
4099 | return Expr; | ||||||||||
4100 | } | ||||||||||
4101 | |||||||||||
4102 | bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } | ||||||||||
4103 | |||||||||||
4104 | bool hasSeenOtherLoops() { return SeenOtherLoops; } | ||||||||||
4105 | |||||||||||
4106 | private: | ||||||||||
4107 | explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) | ||||||||||
4108 | : SCEVRewriteVisitor(SE), L(L) {} | ||||||||||
4109 | |||||||||||
4110 | const Loop *L; | ||||||||||
4111 | bool SeenLoopVariantSCEVUnknown = false; | ||||||||||
4112 | bool SeenOtherLoops = false; | ||||||||||
4113 | }; | ||||||||||
4114 | |||||||||||
4115 | /// This class evaluates the compare condition by matching it against the | ||||||||||
4116 | /// condition of loop latch. If there is a match we assume a true value | ||||||||||
4117 | /// for the condition while building SCEV nodes. | ||||||||||
4118 | class SCEVBackedgeConditionFolder | ||||||||||
4119 | : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { | ||||||||||
4120 | public: | ||||||||||
4121 | static const SCEV *rewrite(const SCEV *S, const Loop *L, | ||||||||||
4122 | ScalarEvolution &SE) { | ||||||||||
4123 | bool IsPosBECond = false; | ||||||||||
4124 | Value *BECond = nullptr; | ||||||||||
4125 | if (BasicBlock *Latch = L->getLoopLatch()) { | ||||||||||
4126 | BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); | ||||||||||
4127 | if (BI && BI->isConditional()) { | ||||||||||
4128 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4129, __PRETTY_FUNCTION__)) | ||||||||||
4129 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4129, __PRETTY_FUNCTION__)); | ||||||||||
4130 | BECond = BI->getCondition(); | ||||||||||
4131 | IsPosBECond = BI->getSuccessor(0) == L->getHeader(); | ||||||||||
4132 | } else { | ||||||||||
4133 | return S; | ||||||||||
4134 | } | ||||||||||
4135 | } | ||||||||||
4136 | SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); | ||||||||||
4137 | return Rewriter.visit(S); | ||||||||||
4138 | } | ||||||||||
4139 | |||||||||||
4140 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
4141 | const SCEV *Result = Expr; | ||||||||||
4142 | bool InvariantF = SE.isLoopInvariant(Expr, L); | ||||||||||
4143 | |||||||||||
4144 | if (!InvariantF) { | ||||||||||
4145 | Instruction *I = cast<Instruction>(Expr->getValue()); | ||||||||||
4146 | switch (I->getOpcode()) { | ||||||||||
4147 | case Instruction::Select: { | ||||||||||
4148 | SelectInst *SI = cast<SelectInst>(I); | ||||||||||
4149 | Optional<const SCEV *> Res = | ||||||||||
4150 | compareWithBackedgeCondition(SI->getCondition()); | ||||||||||
4151 | if (Res.hasValue()) { | ||||||||||
4152 | bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); | ||||||||||
4153 | Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); | ||||||||||
4154 | } | ||||||||||
4155 | break; | ||||||||||
4156 | } | ||||||||||
4157 | default: { | ||||||||||
4158 | Optional<const SCEV *> Res = compareWithBackedgeCondition(I); | ||||||||||
4159 | if (Res.hasValue()) | ||||||||||
4160 | Result = Res.getValue(); | ||||||||||
4161 | break; | ||||||||||
4162 | } | ||||||||||
4163 | } | ||||||||||
4164 | } | ||||||||||
4165 | return Result; | ||||||||||
4166 | } | ||||||||||
4167 | |||||||||||
4168 | private: | ||||||||||
4169 | explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, | ||||||||||
4170 | bool IsPosBECond, ScalarEvolution &SE) | ||||||||||
4171 | : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), | ||||||||||
4172 | IsPositiveBECond(IsPosBECond) {} | ||||||||||
4173 | |||||||||||
4174 | Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); | ||||||||||
4175 | |||||||||||
4176 | const Loop *L; | ||||||||||
4177 | /// Loop back condition. | ||||||||||
4178 | Value *BackedgeCond = nullptr; | ||||||||||
4179 | /// Set to true if loop back is on positive branch condition. | ||||||||||
4180 | bool IsPositiveBECond; | ||||||||||
4181 | }; | ||||||||||
4182 | |||||||||||
4183 | Optional<const SCEV *> | ||||||||||
4184 | SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { | ||||||||||
4185 | |||||||||||
4186 | // If value matches the backedge condition for loop latch, | ||||||||||
4187 | // then return a constant evolution node based on loopback | ||||||||||
4188 | // branch taken. | ||||||||||
4189 | if (BackedgeCond == IC) | ||||||||||
4190 | return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) | ||||||||||
4191 | : SE.getZero(Type::getInt1Ty(SE.getContext())); | ||||||||||
4192 | return None; | ||||||||||
4193 | } | ||||||||||
4194 | |||||||||||
4195 | class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { | ||||||||||
4196 | public: | ||||||||||
4197 | static const SCEV *rewrite(const SCEV *S, const Loop *L, | ||||||||||
4198 | ScalarEvolution &SE) { | ||||||||||
4199 | SCEVShiftRewriter Rewriter(L, SE); | ||||||||||
4200 | const SCEV *Result = Rewriter.visit(S); | ||||||||||
4201 | return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); | ||||||||||
4202 | } | ||||||||||
4203 | |||||||||||
4204 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
4205 | // Only allow AddRecExprs for this loop. | ||||||||||
4206 | if (!SE.isLoopInvariant(Expr, L)) | ||||||||||
4207 | Valid = false; | ||||||||||
4208 | return Expr; | ||||||||||
4209 | } | ||||||||||
4210 | |||||||||||
4211 | const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { | ||||||||||
4212 | if (Expr->getLoop() == L && Expr->isAffine()) | ||||||||||
4213 | return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); | ||||||||||
4214 | Valid = false; | ||||||||||
4215 | return Expr; | ||||||||||
4216 | } | ||||||||||
4217 | |||||||||||
4218 | bool isValid() { return Valid; } | ||||||||||
4219 | |||||||||||
4220 | private: | ||||||||||
4221 | explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) | ||||||||||
4222 | : SCEVRewriteVisitor(SE), L(L) {} | ||||||||||
4223 | |||||||||||
4224 | const Loop *L; | ||||||||||
4225 | bool Valid = true; | ||||||||||
4226 | }; | ||||||||||
4227 | |||||||||||
4228 | } // end anonymous namespace | ||||||||||
4229 | |||||||||||
4230 | SCEV::NoWrapFlags | ||||||||||
4231 | ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { | ||||||||||
4232 | if (!AR->isAffine()) | ||||||||||
4233 | return SCEV::FlagAnyWrap; | ||||||||||
4234 | |||||||||||
4235 | using OBO = OverflowingBinaryOperator; | ||||||||||
4236 | |||||||||||
4237 | SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; | ||||||||||
4238 | |||||||||||
4239 | if (!AR->hasNoSignedWrap()) { | ||||||||||
4240 | ConstantRange AddRecRange = getSignedRange(AR); | ||||||||||
4241 | ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); | ||||||||||
4242 | |||||||||||
4243 | auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( | ||||||||||
4244 | Instruction::Add, IncRange, OBO::NoSignedWrap); | ||||||||||
4245 | if (NSWRegion.contains(AddRecRange)) | ||||||||||
4246 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); | ||||||||||
4247 | } | ||||||||||
4248 | |||||||||||
4249 | if (!AR->hasNoUnsignedWrap()) { | ||||||||||
4250 | ConstantRange AddRecRange = getUnsignedRange(AR); | ||||||||||
4251 | ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); | ||||||||||
4252 | |||||||||||
4253 | auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( | ||||||||||
4254 | Instruction::Add, IncRange, OBO::NoUnsignedWrap); | ||||||||||
4255 | if (NUWRegion.contains(AddRecRange)) | ||||||||||
4256 | Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); | ||||||||||
4257 | } | ||||||||||
4258 | |||||||||||
4259 | return Result; | ||||||||||
4260 | } | ||||||||||
4261 | |||||||||||
4262 | namespace { | ||||||||||
4263 | |||||||||||
4264 | /// Represents an abstract binary operation. This may exist as a | ||||||||||
4265 | /// normal instruction or constant expression, or may have been | ||||||||||
4266 | /// derived from an expression tree. | ||||||||||
4267 | struct BinaryOp { | ||||||||||
4268 | unsigned Opcode; | ||||||||||
4269 | Value *LHS; | ||||||||||
4270 | Value *RHS; | ||||||||||
4271 | bool IsNSW = false; | ||||||||||
4272 | bool IsNUW = false; | ||||||||||
4273 | |||||||||||
4274 | /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or | ||||||||||
4275 | /// constant expression. | ||||||||||
4276 | Operator *Op = nullptr; | ||||||||||
4277 | |||||||||||
4278 | explicit BinaryOp(Operator *Op) | ||||||||||
4279 | : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), | ||||||||||
4280 | Op(Op) { | ||||||||||
4281 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { | ||||||||||
4282 | IsNSW = OBO->hasNoSignedWrap(); | ||||||||||
4283 | IsNUW = OBO->hasNoUnsignedWrap(); | ||||||||||
4284 | } | ||||||||||
4285 | } | ||||||||||
4286 | |||||||||||
4287 | explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, | ||||||||||
4288 | bool IsNUW = false) | ||||||||||
4289 | : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} | ||||||||||
4290 | }; | ||||||||||
4291 | |||||||||||
4292 | } // end anonymous namespace | ||||||||||
4293 | |||||||||||
4294 | /// Try to map \p V into a BinaryOp, and return \c None on failure. | ||||||||||
4295 | static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { | ||||||||||
4296 | auto *Op = dyn_cast<Operator>(V); | ||||||||||
4297 | if (!Op
| ||||||||||
4298 | return None; | ||||||||||
4299 | |||||||||||
4300 | // Implementation detail: all the cleverness here should happen without | ||||||||||
4301 | // creating new SCEV expressions -- our caller knowns tricks to avoid creating | ||||||||||
4302 | // SCEV expressions when possible, and we should not break that. | ||||||||||
4303 | |||||||||||
4304 | switch (Op->getOpcode()) { | ||||||||||
4305 | case Instruction::Add: | ||||||||||
4306 | case Instruction::Sub: | ||||||||||
4307 | case Instruction::Mul: | ||||||||||
4308 | case Instruction::UDiv: | ||||||||||
4309 | case Instruction::URem: | ||||||||||
4310 | case Instruction::And: | ||||||||||
4311 | case Instruction::Or: | ||||||||||
4312 | case Instruction::AShr: | ||||||||||
4313 | case Instruction::Shl: | ||||||||||
4314 | return BinaryOp(Op); | ||||||||||
4315 | |||||||||||
4316 | case Instruction::Xor: | ||||||||||
4317 | if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) | ||||||||||
4318 | // If the RHS of the xor is a signmask, then this is just an add. | ||||||||||
4319 | // Instcombine turns add of signmask into xor as a strength reduction step. | ||||||||||
4320 | if (RHSC->getValue().isSignMask()) | ||||||||||
4321 | return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); | ||||||||||
4322 | return BinaryOp(Op); | ||||||||||
4323 | |||||||||||
4324 | case Instruction::LShr: | ||||||||||
4325 | // Turn logical shift right of a constant into a unsigned divide. | ||||||||||
4326 | if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { | ||||||||||
4327 | uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); | ||||||||||
4328 | |||||||||||
4329 | // If the shift count is not less than the bitwidth, the result of | ||||||||||
4330 | // the shift is undefined. Don't try to analyze it, because the | ||||||||||
4331 | // resolution chosen here may differ from the resolution chosen in | ||||||||||
4332 | // other parts of the compiler. | ||||||||||
4333 | if (SA->getValue().ult(BitWidth)) { | ||||||||||
4334 | Constant *X = | ||||||||||
4335 | ConstantInt::get(SA->getContext(), | ||||||||||
4336 | APInt::getOneBitSet(BitWidth, SA->getZExtValue())); | ||||||||||
4337 | return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); | ||||||||||
4338 | } | ||||||||||
4339 | } | ||||||||||
4340 | return BinaryOp(Op); | ||||||||||
4341 | |||||||||||
4342 | case Instruction::ExtractValue: { | ||||||||||
4343 | auto *EVI = cast<ExtractValueInst>(Op); | ||||||||||
4344 | if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) | ||||||||||
4345 | break; | ||||||||||
4346 | |||||||||||
4347 | auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); | ||||||||||
4348 | if (!WO) | ||||||||||
4349 | break; | ||||||||||
4350 | |||||||||||
4351 | Instruction::BinaryOps BinOp = WO->getBinaryOp(); | ||||||||||
4352 | bool Signed = WO->isSigned(); | ||||||||||
4353 | // TODO: Should add nuw/nsw flags for mul as well. | ||||||||||
4354 | if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) | ||||||||||
4355 | return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); | ||||||||||
4356 | |||||||||||
4357 | // Now that we know that all uses of the arithmetic-result component of | ||||||||||
4358 | // CI are guarded by the overflow check, we can go ahead and pretend | ||||||||||
4359 | // that the arithmetic is non-overflowing. | ||||||||||
4360 | return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), | ||||||||||
4361 | /* IsNSW = */ Signed, /* IsNUW = */ !Signed); | ||||||||||
4362 | } | ||||||||||
4363 | |||||||||||
4364 | default: | ||||||||||
4365 | break; | ||||||||||
4366 | } | ||||||||||
4367 | |||||||||||
4368 | // Recognise intrinsic loop.decrement.reg, and as this has exactly the same | ||||||||||
4369 | // semantics as a Sub, return a binary sub expression. | ||||||||||
4370 | if (auto *II = dyn_cast<IntrinsicInst>(V)) | ||||||||||
4371 | if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) | ||||||||||
4372 | return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); | ||||||||||
4373 | |||||||||||
4374 | return None; | ||||||||||
4375 | } | ||||||||||
4376 | |||||||||||
4377 | /// Helper function to createAddRecFromPHIWithCasts. We have a phi | ||||||||||
4378 | /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via | ||||||||||
4379 | /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the | ||||||||||
4380 | /// way. This function checks if \p Op, an operand of this SCEVAddExpr, | ||||||||||
4381 | /// follows one of the following patterns: | ||||||||||
4382 | /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) | ||||||||||
4383 | /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) | ||||||||||
4384 | /// If the SCEV expression of \p Op conforms with one of the expected patterns | ||||||||||
4385 | /// we return the type of the truncation operation, and indicate whether the | ||||||||||
4386 | /// truncated type should be treated as signed/unsigned by setting | ||||||||||
4387 | /// \p Signed to true/false, respectively. | ||||||||||
4388 | static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, | ||||||||||
4389 | bool &Signed, ScalarEvolution &SE) { | ||||||||||
4390 | // The case where Op == SymbolicPHI (that is, with no type conversions on | ||||||||||
4391 | // the way) is handled by the regular add recurrence creating logic and | ||||||||||
4392 | // would have already been triggered in createAddRecForPHI. Reaching it here | ||||||||||
4393 | // means that createAddRecFromPHI had failed for this PHI before (e.g., | ||||||||||
4394 | // because one of the other operands of the SCEVAddExpr updating this PHI is | ||||||||||
4395 | // not invariant). | ||||||||||
4396 | // | ||||||||||
4397 | // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in | ||||||||||
4398 | // this case predicates that allow us to prove that Op == SymbolicPHI will | ||||||||||
4399 | // be added. | ||||||||||
4400 | if (Op == SymbolicPHI) | ||||||||||
4401 | return nullptr; | ||||||||||
4402 | |||||||||||
4403 | unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); | ||||||||||
4404 | unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); | ||||||||||
4405 | if (SourceBits != NewBits) | ||||||||||
4406 | return nullptr; | ||||||||||
4407 | |||||||||||
4408 | const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); | ||||||||||
4409 | const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); | ||||||||||
4410 | if (!SExt && !ZExt) | ||||||||||
4411 | return nullptr; | ||||||||||
4412 | const SCEVTruncateExpr *Trunc = | ||||||||||
4413 | SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) | ||||||||||
4414 | : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); | ||||||||||
4415 | if (!Trunc) | ||||||||||
4416 | return nullptr; | ||||||||||
4417 | const SCEV *X = Trunc->getOperand(); | ||||||||||
4418 | if (X != SymbolicPHI) | ||||||||||
4419 | return nullptr; | ||||||||||
4420 | Signed = SExt != nullptr; | ||||||||||
4421 | return Trunc->getType(); | ||||||||||
4422 | } | ||||||||||
4423 | |||||||||||
4424 | static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { | ||||||||||
4425 | if (!PN->getType()->isIntegerTy()) | ||||||||||
4426 | return nullptr; | ||||||||||
4427 | const Loop *L = LI.getLoopFor(PN->getParent()); | ||||||||||
4428 | if (!L || L->getHeader() != PN->getParent()) | ||||||||||
4429 | return nullptr; | ||||||||||
4430 | return L; | ||||||||||
4431 | } | ||||||||||
4432 | |||||||||||
4433 | // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the | ||||||||||
4434 | // computation that updates the phi follows the following pattern: | ||||||||||
4435 | // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum | ||||||||||
4436 | // which correspond to a phi->trunc->sext/zext->add->phi update chain. | ||||||||||
4437 | // If so, try to see if it can be rewritten as an AddRecExpr under some | ||||||||||
4438 | // Predicates. If successful, return them as a pair. Also cache the results | ||||||||||
4439 | // of the analysis. | ||||||||||
4440 | // | ||||||||||
4441 | // Example usage scenario: | ||||||||||
4442 | // Say the Rewriter is called for the following SCEV: | ||||||||||
4443 | // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) | ||||||||||
4444 | // where: | ||||||||||
4445 | // %X = phi i64 (%Start, %BEValue) | ||||||||||
4446 | // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), | ||||||||||
4447 | // and call this function with %SymbolicPHI = %X. | ||||||||||
4448 | // | ||||||||||
4449 | // The analysis will find that the value coming around the backedge has | ||||||||||
4450 | // the following SCEV: | ||||||||||
4451 | // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) | ||||||||||
4452 | // Upon concluding that this matches the desired pattern, the function | ||||||||||
4453 | // will return the pair {NewAddRec, SmallPredsVec} where: | ||||||||||
4454 | // NewAddRec = {%Start,+,%Step} | ||||||||||
4455 | // SmallPredsVec = {P1, P2, P3} as follows: | ||||||||||
4456 | // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> | ||||||||||
4457 | // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) | ||||||||||
4458 | // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) | ||||||||||
4459 | // The returned pair means that SymbolicPHI can be rewritten into NewAddRec | ||||||||||
4460 | // under the predicates {P1,P2,P3}. | ||||||||||
4461 | // This predicated rewrite will be cached in PredicatedSCEVRewrites: | ||||||||||
4462 | // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} | ||||||||||
4463 | // | ||||||||||
4464 | // TODO's: | ||||||||||
4465 | // | ||||||||||
4466 | // 1) Extend the Induction descriptor to also support inductions that involve | ||||||||||
4467 | // casts: When needed (namely, when we are called in the context of the | ||||||||||
4468 | // vectorizer induction analysis), a Set of cast instructions will be | ||||||||||
4469 | // populated by this method, and provided back to isInductionPHI. This is | ||||||||||
4470 | // needed to allow the vectorizer to properly record them to be ignored by | ||||||||||
4471 | // the cost model and to avoid vectorizing them (otherwise these casts, | ||||||||||
4472 | // which are redundant under the runtime overflow checks, will be | ||||||||||
4473 | // vectorized, which can be costly). | ||||||||||
4474 | // | ||||||||||
4475 | // 2) Support additional induction/PHISCEV patterns: We also want to support | ||||||||||
4476 | // inductions where the sext-trunc / zext-trunc operations (partly) occur | ||||||||||
4477 | // after the induction update operation (the induction increment): | ||||||||||
4478 | // | ||||||||||
4479 | // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) | ||||||||||
4480 | // which correspond to a phi->add->trunc->sext/zext->phi update chain. | ||||||||||
4481 | // | ||||||||||
4482 | // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) | ||||||||||
4483 | // which correspond to a phi->trunc->add->sext/zext->phi update chain. | ||||||||||
4484 | // | ||||||||||
4485 | // 3) Outline common code with createAddRecFromPHI to avoid duplication. | ||||||||||
4486 | Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> | ||||||||||
4487 | ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { | ||||||||||
4488 | SmallVector<const SCEVPredicate *, 3> Predicates; | ||||||||||
4489 | |||||||||||
4490 | // *** Part1: Analyze if we have a phi-with-cast pattern for which we can | ||||||||||
4491 | // return an AddRec expression under some predicate. | ||||||||||
4492 | |||||||||||
4493 | auto *PN = cast<PHINode>(SymbolicPHI->getValue()); | ||||||||||
4494 | const Loop *L = isIntegerLoopHeaderPHI(PN, LI); | ||||||||||
4495 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4495, __PRETTY_FUNCTION__)); | ||||||||||
4496 | |||||||||||
4497 | // The loop may have multiple entrances or multiple exits; we can analyze | ||||||||||
4498 | // this phi as an addrec if it has a unique entry value and a unique | ||||||||||
4499 | // backedge value. | ||||||||||
4500 | Value *BEValueV = nullptr, *StartValueV = nullptr; | ||||||||||
4501 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { | ||||||||||
4502 | Value *V = PN->getIncomingValue(i); | ||||||||||
4503 | if (L->contains(PN->getIncomingBlock(i))) { | ||||||||||
4504 | if (!BEValueV) { | ||||||||||
4505 | BEValueV = V; | ||||||||||
4506 | } else if (BEValueV != V) { | ||||||||||
4507 | BEValueV = nullptr; | ||||||||||
4508 | break; | ||||||||||
4509 | } | ||||||||||
4510 | } else if (!StartValueV) { | ||||||||||
4511 | StartValueV = V; | ||||||||||
4512 | } else if (StartValueV != V) { | ||||||||||
4513 | StartValueV = nullptr; | ||||||||||
4514 | break; | ||||||||||
4515 | } | ||||||||||
4516 | } | ||||||||||
4517 | if (!BEValueV || !StartValueV) | ||||||||||
4518 | return None; | ||||||||||
4519 | |||||||||||
4520 | const SCEV *BEValue = getSCEV(BEValueV); | ||||||||||
4521 | |||||||||||
4522 | // If the value coming around the backedge is an add with the symbolic | ||||||||||
4523 | // value we just inserted, possibly with casts that we can ignore under | ||||||||||
4524 | // an appropriate runtime guard, then we found a simple induction variable! | ||||||||||
4525 | const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); | ||||||||||
4526 | if (!Add) | ||||||||||
4527 | return None; | ||||||||||
4528 | |||||||||||
4529 | // If there is a single occurrence of the symbolic value, possibly | ||||||||||
4530 | // casted, replace it with a recurrence. | ||||||||||
4531 | unsigned FoundIndex = Add->getNumOperands(); | ||||||||||
4532 | Type *TruncTy = nullptr; | ||||||||||
4533 | bool Signed; | ||||||||||
4534 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) | ||||||||||
4535 | if ((TruncTy = | ||||||||||
4536 | isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) | ||||||||||
4537 | if (FoundIndex == e) { | ||||||||||
4538 | FoundIndex = i; | ||||||||||
4539 | break; | ||||||||||
4540 | } | ||||||||||
4541 | |||||||||||
4542 | if (FoundIndex == Add->getNumOperands()) | ||||||||||
4543 | return None; | ||||||||||
4544 | |||||||||||
4545 | // Create an add with everything but the specified operand. | ||||||||||
4546 | SmallVector<const SCEV *, 8> Ops; | ||||||||||
4547 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) | ||||||||||
4548 | if (i != FoundIndex) | ||||||||||
4549 | Ops.push_back(Add->getOperand(i)); | ||||||||||
4550 | const SCEV *Accum = getAddExpr(Ops); | ||||||||||
4551 | |||||||||||
4552 | // The runtime checks will not be valid if the step amount is | ||||||||||
4553 | // varying inside the loop. | ||||||||||
4554 | if (!isLoopInvariant(Accum, L)) | ||||||||||
4555 | return None; | ||||||||||
4556 | |||||||||||
4557 | // *** Part2: Create the predicates | ||||||||||
4558 | |||||||||||
4559 | // Analysis was successful: we have a phi-with-cast pattern for which we | ||||||||||
4560 | // can return an AddRec expression under the following predicates: | ||||||||||
4561 | // | ||||||||||
4562 | // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) | ||||||||||
4563 | // fits within the truncated type (does not overflow) for i = 0 to n-1. | ||||||||||
4564 | // P2: An Equal predicate that guarantees that | ||||||||||
4565 | // Start = (Ext ix (Trunc iy (Start) to ix) to iy) | ||||||||||
4566 | // P3: An Equal predicate that guarantees that | ||||||||||
4567 | // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) | ||||||||||
4568 | // | ||||||||||
4569 | // As we next prove, the above predicates guarantee that: | ||||||||||
4570 | // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) | ||||||||||
4571 | // | ||||||||||
4572 | // | ||||||||||
4573 | // More formally, we want to prove that: | ||||||||||
4574 | // Expr(i+1) = Start + (i+1) * Accum | ||||||||||
4575 | // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum | ||||||||||
4576 | // | ||||||||||
4577 | // Given that: | ||||||||||
4578 | // 1) Expr(0) = Start | ||||||||||
4579 | // 2) Expr(1) = Start + Accum | ||||||||||
4580 | // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 | ||||||||||
4581 | // 3) Induction hypothesis (step i): | ||||||||||
4582 | // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum | ||||||||||
4583 | // | ||||||||||
4584 | // Proof: | ||||||||||
4585 | // Expr(i+1) = | ||||||||||
4586 | // = Start + (i+1)*Accum | ||||||||||
4587 | // = (Start + i*Accum) + Accum | ||||||||||
4588 | // = Expr(i) + Accum | ||||||||||
4589 | // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum | ||||||||||
4590 | // :: from step i | ||||||||||
4591 | // | ||||||||||
4592 | // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum | ||||||||||
4593 | // | ||||||||||
4594 | // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) | ||||||||||
4595 | // + (Ext ix (Trunc iy (Accum) to ix) to iy) | ||||||||||
4596 | // + Accum :: from P3 | ||||||||||
4597 | // | ||||||||||
4598 | // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) | ||||||||||
4599 | // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) | ||||||||||
4600 | // | ||||||||||
4601 | // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum | ||||||||||
4602 | // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum | ||||||||||
4603 | // | ||||||||||
4604 | // By induction, the same applies to all iterations 1<=i<n: | ||||||||||
4605 | // | ||||||||||
4606 | |||||||||||
4607 | // Create a truncated addrec for which we will add a no overflow check (P1). | ||||||||||
4608 | const SCEV *StartVal = getSCEV(StartValueV); | ||||||||||
4609 | const SCEV *PHISCEV = | ||||||||||
4610 | getAddRecExpr(getTruncateExpr(StartVal, TruncTy), | ||||||||||
4611 | getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); | ||||||||||
4612 | |||||||||||
4613 | // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. | ||||||||||
4614 | // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV | ||||||||||
4615 | // will be constant. | ||||||||||
4616 | // | ||||||||||
4617 | // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't | ||||||||||
4618 | // add P1. | ||||||||||
4619 | if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { | ||||||||||
4620 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags = | ||||||||||
4621 | Signed ? SCEVWrapPredicate::IncrementNSSW | ||||||||||
4622 | : SCEVWrapPredicate::IncrementNUSW; | ||||||||||
4623 | const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); | ||||||||||
4624 | Predicates.push_back(AddRecPred); | ||||||||||
4625 | } | ||||||||||
4626 | |||||||||||
4627 | // Create the Equal Predicates P2,P3: | ||||||||||
4628 | |||||||||||
4629 | // It is possible that the predicates P2 and/or P3 are computable at | ||||||||||
4630 | // compile time due to StartVal and/or Accum being constants. | ||||||||||
4631 | // If either one is, then we can check that now and escape if either P2 | ||||||||||
4632 | // or P3 is false. | ||||||||||
4633 | |||||||||||
4634 | // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) | ||||||||||
4635 | // for each of StartVal and Accum | ||||||||||
4636 | auto getExtendedExpr = [&](const SCEV *Expr, | ||||||||||
4637 | bool CreateSignExtend) -> const SCEV * { | ||||||||||
4638 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4638, __PRETTY_FUNCTION__)); | ||||||||||
4639 | const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); | ||||||||||
4640 | const SCEV *ExtendedExpr = | ||||||||||
4641 | CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) | ||||||||||
4642 | : getZeroExtendExpr(TruncatedExpr, Expr->getType()); | ||||||||||
4643 | return ExtendedExpr; | ||||||||||
4644 | }; | ||||||||||
4645 | |||||||||||
4646 | // Given: | ||||||||||
4647 | // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy | ||||||||||
4648 | // = getExtendedExpr(Expr) | ||||||||||
4649 | // Determine whether the predicate P: Expr == ExtendedExpr | ||||||||||
4650 | // is known to be false at compile time | ||||||||||
4651 | auto PredIsKnownFalse = [&](const SCEV *Expr, | ||||||||||
4652 | const SCEV *ExtendedExpr) -> bool { | ||||||||||
4653 | return Expr != ExtendedExpr && | ||||||||||
4654 | isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); | ||||||||||
4655 | }; | ||||||||||
4656 | |||||||||||
4657 | const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); | ||||||||||
4658 | if (PredIsKnownFalse(StartVal, StartExtended)) { | ||||||||||
4659 | 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); | ||||||||||
4660 | return None; | ||||||||||
4661 | } | ||||||||||
4662 | |||||||||||
4663 | // The Step is always Signed (because the overflow checks are either | ||||||||||
4664 | // NSSW or NUSW) | ||||||||||
4665 | const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); | ||||||||||
4666 | if (PredIsKnownFalse(Accum, AccumExtended)) { | ||||||||||
4667 | 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); | ||||||||||
4668 | return None; | ||||||||||
4669 | } | ||||||||||
4670 | |||||||||||
4671 | auto AppendPredicate = [&](const SCEV *Expr, | ||||||||||
4672 | const SCEV *ExtendedExpr) -> void { | ||||||||||
4673 | if (Expr != ExtendedExpr && | ||||||||||
4674 | !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { | ||||||||||
4675 | const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); | ||||||||||
4676 | LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "Added Predicate: " << *Pred; } } while (false); | ||||||||||
4677 | Predicates.push_back(Pred); | ||||||||||
4678 | } | ||||||||||
4679 | }; | ||||||||||
4680 | |||||||||||
4681 | AppendPredicate(StartVal, StartExtended); | ||||||||||
4682 | AppendPredicate(Accum, AccumExtended); | ||||||||||
4683 | |||||||||||
4684 | // *** Part3: Predicates are ready. Now go ahead and create the new addrec in | ||||||||||
4685 | // which the casts had been folded away. The caller can rewrite SymbolicPHI | ||||||||||
4686 | // into NewAR if it will also add the runtime overflow checks specified in | ||||||||||
4687 | // Predicates. | ||||||||||
4688 | auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); | ||||||||||
4689 | |||||||||||
4690 | std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = | ||||||||||
4691 | std::make_pair(NewAR, Predicates); | ||||||||||
4692 | // Remember the result of the analysis for this SCEV at this locayyytion. | ||||||||||
4693 | PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; | ||||||||||
4694 | return PredRewrite; | ||||||||||
4695 | } | ||||||||||
4696 | |||||||||||
4697 | Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> | ||||||||||
4698 | ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { | ||||||||||
4699 | auto *PN = cast<PHINode>(SymbolicPHI->getValue()); | ||||||||||
4700 | const Loop *L = isIntegerLoopHeaderPHI(PN, LI); | ||||||||||
4701 | if (!L) | ||||||||||
4702 | return None; | ||||||||||
4703 | |||||||||||
4704 | // Check to see if we already analyzed this PHI. | ||||||||||
4705 | auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); | ||||||||||
4706 | if (I != PredicatedSCEVRewrites.end()) { | ||||||||||
4707 | std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = | ||||||||||
4708 | I->second; | ||||||||||
4709 | // Analysis was done before and failed to create an AddRec: | ||||||||||
4710 | if (Rewrite.first == SymbolicPHI) | ||||||||||
4711 | return None; | ||||||||||
4712 | // Analysis was done before and succeeded to create an AddRec under | ||||||||||
4713 | // a predicate: | ||||||||||
4714 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4714, __PRETTY_FUNCTION__)); | ||||||||||
4715 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4715, __PRETTY_FUNCTION__)); | ||||||||||
4716 | return Rewrite; | ||||||||||
4717 | } | ||||||||||
4718 | |||||||||||
4719 | Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> | ||||||||||
4720 | Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); | ||||||||||
4721 | |||||||||||
4722 | // Record in the cache that the analysis failed | ||||||||||
4723 | if (!Rewrite) { | ||||||||||
4724 | SmallVector<const SCEVPredicate *, 3> Predicates; | ||||||||||
4725 | PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; | ||||||||||
4726 | return None; | ||||||||||
4727 | } | ||||||||||
4728 | |||||||||||
4729 | return Rewrite; | ||||||||||
4730 | } | ||||||||||
4731 | |||||||||||
4732 | // FIXME: This utility is currently required because the Rewriter currently | ||||||||||
4733 | // does not rewrite this expression: | ||||||||||
4734 | // {0, +, (sext ix (trunc iy to ix) to iy)} | ||||||||||
4735 | // into {0, +, %step}, | ||||||||||
4736 | // even when the following Equal predicate exists: | ||||||||||
4737 | // "%step == (sext ix (trunc iy to ix) to iy)". | ||||||||||
4738 | bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( | ||||||||||
4739 | const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { | ||||||||||
4740 | if (AR1 == AR2) | ||||||||||
4741 | return true; | ||||||||||
4742 | |||||||||||
4743 | auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { | ||||||||||
4744 | if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && | ||||||||||
4745 | !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) | ||||||||||
4746 | return false; | ||||||||||
4747 | return true; | ||||||||||
4748 | }; | ||||||||||
4749 | |||||||||||
4750 | if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || | ||||||||||
4751 | !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) | ||||||||||
4752 | return false; | ||||||||||
4753 | return true; | ||||||||||
4754 | } | ||||||||||
4755 | |||||||||||
4756 | /// A helper function for createAddRecFromPHI to handle simple cases. | ||||||||||
4757 | /// | ||||||||||
4758 | /// This function tries to find an AddRec expression for the simplest (yet most | ||||||||||
4759 | /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). | ||||||||||
4760 | /// If it fails, createAddRecFromPHI will use a more general, but slow, | ||||||||||
4761 | /// technique for finding the AddRec expression. | ||||||||||
4762 | const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, | ||||||||||
4763 | Value *BEValueV, | ||||||||||
4764 | Value *StartValueV) { | ||||||||||
4765 | const Loop *L = LI.getLoopFor(PN->getParent()); | ||||||||||
4766 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4766, __PRETTY_FUNCTION__)); | ||||||||||
4767 | assert(BEValueV && StartValueV)((BEValueV && StartValueV) ? static_cast<void> ( 0) : __assert_fail ("BEValueV && StartValueV", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4767, __PRETTY_FUNCTION__)); | ||||||||||
4768 | |||||||||||
4769 | auto BO = MatchBinaryOp(BEValueV, DT); | ||||||||||
4770 | if (!BO) | ||||||||||
4771 | return nullptr; | ||||||||||
4772 | |||||||||||
4773 | if (BO->Opcode != Instruction::Add) | ||||||||||
4774 | return nullptr; | ||||||||||
4775 | |||||||||||
4776 | const SCEV *Accum = nullptr; | ||||||||||
4777 | if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) | ||||||||||
4778 | Accum = getSCEV(BO->RHS); | ||||||||||
4779 | else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) | ||||||||||
4780 | Accum = getSCEV(BO->LHS); | ||||||||||
4781 | |||||||||||
4782 | if (!Accum) | ||||||||||
4783 | return nullptr; | ||||||||||
4784 | |||||||||||
4785 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; | ||||||||||
4786 | if (BO->IsNUW) | ||||||||||
4787 | Flags = setFlags(Flags, SCEV::FlagNUW); | ||||||||||
4788 | if (BO->IsNSW) | ||||||||||
4789 | Flags = setFlags(Flags, SCEV::FlagNSW); | ||||||||||
4790 | |||||||||||
4791 | const SCEV *StartVal = getSCEV(StartValueV); | ||||||||||
4792 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); | ||||||||||
4793 | |||||||||||
4794 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; | ||||||||||
4795 | |||||||||||
4796 | // We can add Flags to the post-inc expression only if we | ||||||||||
4797 | // know that it is *undefined behavior* for BEValueV to | ||||||||||
4798 | // overflow. | ||||||||||
4799 | if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) | ||||||||||
4800 | if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) | ||||||||||
4801 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); | ||||||||||
4802 | |||||||||||
4803 | return PHISCEV; | ||||||||||
4804 | } | ||||||||||
4805 | |||||||||||
4806 | const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { | ||||||||||
4807 | const Loop *L = LI.getLoopFor(PN->getParent()); | ||||||||||
4808 | if (!L || L->getHeader() != PN->getParent()) | ||||||||||
4809 | return nullptr; | ||||||||||
4810 | |||||||||||
4811 | // The loop may have multiple entrances or multiple exits; we can analyze | ||||||||||
4812 | // this phi as an addrec if it has a unique entry value and a unique | ||||||||||
4813 | // backedge value. | ||||||||||
4814 | Value *BEValueV = nullptr, *StartValueV = nullptr; | ||||||||||
4815 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { | ||||||||||
4816 | Value *V = PN->getIncomingValue(i); | ||||||||||
4817 | if (L->contains(PN->getIncomingBlock(i))) { | ||||||||||
4818 | if (!BEValueV) { | ||||||||||
4819 | BEValueV = V; | ||||||||||
4820 | } else if (BEValueV != V) { | ||||||||||
4821 | BEValueV = nullptr; | ||||||||||
4822 | break; | ||||||||||
4823 | } | ||||||||||
4824 | } else if (!StartValueV) { | ||||||||||
4825 | StartValueV = V; | ||||||||||
4826 | } else if (StartValueV != V) { | ||||||||||
4827 | StartValueV = nullptr; | ||||||||||
4828 | break; | ||||||||||
4829 | } | ||||||||||
4830 | } | ||||||||||
4831 | if (!BEValueV || !StartValueV) | ||||||||||
4832 | return nullptr; | ||||||||||
4833 | |||||||||||
4834 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4835, __PRETTY_FUNCTION__)) | ||||||||||
4835 | "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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 4835, __PRETTY_FUNCTION__)); | ||||||||||
4836 | |||||||||||
4837 | // First, try to find AddRec expression without creating a fictituos symbolic | ||||||||||
4838 | // value for PN. | ||||||||||
4839 | if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) | ||||||||||
4840 | return S; | ||||||||||
4841 | |||||||||||
4842 | // Handle PHI node value symbolically. | ||||||||||
4843 | const SCEV *SymbolicName = getUnknown(PN); | ||||||||||
4844 | ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); | ||||||||||
4845 | |||||||||||
4846 | // Using this symbolic name for the PHI, analyze the value coming around | ||||||||||
4847 | // the back-edge. | ||||||||||
4848 | const SCEV *BEValue = getSCEV(BEValueV); | ||||||||||
4849 | |||||||||||
4850 | // NOTE: If BEValue is loop invariant, we know that the PHI node just | ||||||||||
4851 | // has a special value for the first iteration of the loop. | ||||||||||
4852 | |||||||||||
4853 | // If the value coming around the backedge is an add with the symbolic | ||||||||||
4854 | // value we just inserted, then we found a simple induction variable! | ||||||||||
4855 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { | ||||||||||
4856 | // If there is a single occurrence of the symbolic value, replace it | ||||||||||
4857 | // with a recurrence. | ||||||||||
4858 | unsigned FoundIndex = Add->getNumOperands(); | ||||||||||
4859 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) | ||||||||||
4860 | if (Add->getOperand(i) == SymbolicName) | ||||||||||
4861 | if (FoundIndex == e) { | ||||||||||
4862 | FoundIndex = i; | ||||||||||
4863 | break; | ||||||||||
4864 | } | ||||||||||
4865 | |||||||||||
4866 | if (FoundIndex != Add->getNumOperands()) { | ||||||||||
4867 | // Create an add with everything but the specified operand. | ||||||||||
4868 | SmallVector<const SCEV *, 8> Ops; | ||||||||||
4869 | for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) | ||||||||||
4870 | if (i != FoundIndex) | ||||||||||
4871 | Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), | ||||||||||
4872 | L, *this)); | ||||||||||
4873 | const SCEV *Accum = getAddExpr(Ops); | ||||||||||
4874 | |||||||||||
4875 | // This is not a valid addrec if the step amount is varying each | ||||||||||
4876 | // loop iteration, but is not itself an addrec in this loop. | ||||||||||
4877 | if (isLoopInvariant(Accum, L) || | ||||||||||
4878 | (isa<SCEVAddRecExpr>(Accum) && | ||||||||||
4879 | cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { | ||||||||||
4880 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; | ||||||||||
4881 | |||||||||||
4882 | if (auto BO = MatchBinaryOp(BEValueV, DT)) { | ||||||||||
4883 | if (BO->Opcode == Instruction::Add && BO->LHS == PN) { | ||||||||||
4884 | if (BO->IsNUW) | ||||||||||
4885 | Flags = setFlags(Flags, SCEV::FlagNUW); | ||||||||||
4886 | if (BO->IsNSW) | ||||||||||
4887 | Flags = setFlags(Flags, SCEV::FlagNSW); | ||||||||||
4888 | } | ||||||||||
4889 | } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { | ||||||||||
4890 | // If the increment is an inbounds GEP, then we know the address | ||||||||||
4891 | // space cannot be wrapped around. We cannot make any guarantee | ||||||||||
4892 | // about signed or unsigned overflow because pointers are | ||||||||||
4893 | // unsigned but we may have a negative index from the base | ||||||||||
4894 | // pointer. We can guarantee that no unsigned wrap occurs if the | ||||||||||
4895 | // indices form a positive value. | ||||||||||
4896 | if (GEP->isInBounds() && GEP->getOperand(0) == PN) { | ||||||||||
4897 | Flags = setFlags(Flags, SCEV::FlagNW); | ||||||||||
4898 | |||||||||||
4899 | const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); | ||||||||||
4900 | if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) | ||||||||||
4901 | Flags = setFlags(Flags, SCEV::FlagNUW); | ||||||||||
4902 | } | ||||||||||
4903 | |||||||||||
4904 | // We cannot transfer nuw and nsw flags from subtraction | ||||||||||
4905 | // operations -- sub nuw X, Y is not the same as add nuw X, -Y | ||||||||||
4906 | // for instance. | ||||||||||
4907 | } | ||||||||||
4908 | |||||||||||
4909 | const SCEV *StartVal = getSCEV(StartValueV); | ||||||||||
4910 | const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); | ||||||||||
4911 | |||||||||||
4912 | // Okay, for the entire analysis of this edge we assumed the PHI | ||||||||||
4913 | // to be symbolic. We now need to go back and purge all of the | ||||||||||
4914 | // entries for the scalars that use the symbolic expression. | ||||||||||
4915 | forgetSymbolicName(PN, SymbolicName); | ||||||||||
4916 | ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; | ||||||||||
4917 | |||||||||||
4918 | // We can add Flags to the post-inc expression only if we | ||||||||||
4919 | // know that it is *undefined behavior* for BEValueV to | ||||||||||
4920 | // overflow. | ||||||||||
4921 | if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) | ||||||||||
4922 | if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) | ||||||||||
4923 | (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); | ||||||||||
4924 | |||||||||||
4925 | return PHISCEV; | ||||||||||
4926 | } | ||||||||||
4927 | } | ||||||||||
4928 | } else { | ||||||||||
4929 | // Otherwise, this could be a loop like this: | ||||||||||
4930 | // i = 0; for (j = 1; ..; ++j) { .... i = j; } | ||||||||||
4931 | // In this case, j = {1,+,1} and BEValue is j. | ||||||||||
4932 | // Because the other in-value of i (0) fits the evolution of BEValue | ||||||||||
4933 | // i really is an addrec evolution. | ||||||||||
4934 | // | ||||||||||
4935 | // We can generalize this saying that i is the shifted value of BEValue | ||||||||||
4936 | // by one iteration: | ||||||||||
4937 | // PHI(f(0), f({1,+,1})) --> f({0,+,1}) | ||||||||||
4938 | const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); | ||||||||||
4939 | const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); | ||||||||||
4940 | if (Shifted != getCouldNotCompute() && | ||||||||||
4941 | Start != getCouldNotCompute()) { | ||||||||||
4942 | const SCEV *StartVal = getSCEV(StartValueV); | ||||||||||
4943 | if (Start == StartVal) { | ||||||||||
4944 | // Okay, for the entire analysis of this edge we assumed the PHI | ||||||||||
4945 | // to be symbolic. We now need to go back and purge all of the | ||||||||||
4946 | // entries for the scalars that use the symbolic expression. | ||||||||||
4947 | forgetSymbolicName(PN, SymbolicName); | ||||||||||
4948 | ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; | ||||||||||
4949 | return Shifted; | ||||||||||
4950 | } | ||||||||||
4951 | } | ||||||||||
4952 | } | ||||||||||
4953 | |||||||||||
4954 | // Remove the temporary PHI node SCEV that has been inserted while intending | ||||||||||
4955 | // to create an AddRecExpr for this PHI node. We can not keep this temporary | ||||||||||
4956 | // as it will prevent later (possibly simpler) SCEV expressions to be added | ||||||||||
4957 | // to the ValueExprMap. | ||||||||||
4958 | eraseValueFromMap(PN); | ||||||||||
4959 | |||||||||||
4960 | return nullptr; | ||||||||||
4961 | } | ||||||||||
4962 | |||||||||||
4963 | // Checks if the SCEV S is available at BB. S is considered available at BB | ||||||||||
4964 | // if S can be materialized at BB without introducing a fault. | ||||||||||
4965 | static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, | ||||||||||
4966 | BasicBlock *BB) { | ||||||||||
4967 | struct CheckAvailable { | ||||||||||
4968 | bool TraversalDone = false; | ||||||||||
4969 | bool Available = true; | ||||||||||
4970 | |||||||||||
4971 | const Loop *L = nullptr; // The loop BB is in (can be nullptr) | ||||||||||
4972 | BasicBlock *BB = nullptr; | ||||||||||
4973 | DominatorTree &DT; | ||||||||||
4974 | |||||||||||
4975 | CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) | ||||||||||
4976 | : L(L), BB(BB), DT(DT) {} | ||||||||||
4977 | |||||||||||
4978 | bool setUnavailable() { | ||||||||||
4979 | TraversalDone = true; | ||||||||||
4980 | Available = false; | ||||||||||
4981 | return false; | ||||||||||
4982 | } | ||||||||||
4983 | |||||||||||
4984 | bool follow(const SCEV *S) { | ||||||||||
4985 | switch (S->getSCEVType()) { | ||||||||||
4986 | case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: | ||||||||||
4987 | case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: | ||||||||||
4988 | case scUMinExpr: | ||||||||||
4989 | case scSMinExpr: | ||||||||||
4990 | // These expressions are available if their operand(s) is/are. | ||||||||||
4991 | return true; | ||||||||||
4992 | |||||||||||
4993 | case scAddRecExpr: { | ||||||||||
4994 | // We allow add recurrences that are on the loop BB is in, or some | ||||||||||
4995 | // outer loop. This guarantees availability because the value of the | ||||||||||
4996 | // add recurrence at BB is simply the "current" value of the induction | ||||||||||
4997 | // variable. We can relax this in the future; for instance an add | ||||||||||
4998 | // recurrence on a sibling dominating loop is also available at BB. | ||||||||||
4999 | const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); | ||||||||||
5000 | if (L && (ARLoop == L || ARLoop->contains(L))) | ||||||||||
5001 | return true; | ||||||||||
5002 | |||||||||||
5003 | return setUnavailable(); | ||||||||||
5004 | } | ||||||||||
5005 | |||||||||||
5006 | case scUnknown: { | ||||||||||
5007 | // For SCEVUnknown, we check for simple dominance. | ||||||||||
5008 | const auto *SU = cast<SCEVUnknown>(S); | ||||||||||
5009 | Value *V = SU->getValue(); | ||||||||||
5010 | |||||||||||
5011 | if (isa<Argument>(V)) | ||||||||||
5012 | return false; | ||||||||||
5013 | |||||||||||
5014 | if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) | ||||||||||
5015 | return false; | ||||||||||
5016 | |||||||||||
5017 | return setUnavailable(); | ||||||||||
5018 | } | ||||||||||
5019 | |||||||||||
5020 | case scUDivExpr: | ||||||||||
5021 | case scCouldNotCompute: | ||||||||||
5022 | // We do not try to smart about these at all. | ||||||||||
5023 | return setUnavailable(); | ||||||||||
5024 | } | ||||||||||
5025 | llvm_unreachable("switch should be fully covered!")::llvm::llvm_unreachable_internal("switch should be fully covered!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5025); | ||||||||||
5026 | } | ||||||||||
5027 | |||||||||||
5028 | bool isDone() { return TraversalDone; } | ||||||||||
5029 | }; | ||||||||||
5030 | |||||||||||
5031 | CheckAvailable CA(L, BB, DT); | ||||||||||
5032 | SCEVTraversal<CheckAvailable> ST(CA); | ||||||||||
5033 | |||||||||||
5034 | ST.visitAll(S); | ||||||||||
5035 | return CA.Available; | ||||||||||
5036 | } | ||||||||||
5037 | |||||||||||
5038 | // Try to match a control flow sequence that branches out at BI and merges back | ||||||||||
5039 | // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful | ||||||||||
5040 | // match. | ||||||||||
5041 | static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, | ||||||||||
5042 | Value *&C, Value *&LHS, Value *&RHS) { | ||||||||||
5043 | C = BI->getCondition(); | ||||||||||
5044 | |||||||||||
5045 | BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); | ||||||||||
5046 | BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); | ||||||||||
5047 | |||||||||||
5048 | if (!LeftEdge.isSingleEdge()) | ||||||||||
5049 | return false; | ||||||||||
5050 | |||||||||||
5051 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5051, __PRETTY_FUNCTION__)); | ||||||||||
5052 | |||||||||||
5053 | Use &LeftUse = Merge->getOperandUse(0); | ||||||||||
5054 | Use &RightUse = Merge->getOperandUse(1); | ||||||||||
5055 | |||||||||||
5056 | if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { | ||||||||||
5057 | LHS = LeftUse; | ||||||||||
5058 | RHS = RightUse; | ||||||||||
5059 | return true; | ||||||||||
5060 | } | ||||||||||
5061 | |||||||||||
5062 | if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { | ||||||||||
5063 | LHS = RightUse; | ||||||||||
5064 | RHS = LeftUse; | ||||||||||
5065 | return true; | ||||||||||
5066 | } | ||||||||||
5067 | |||||||||||
5068 | return false; | ||||||||||
5069 | } | ||||||||||
5070 | |||||||||||
5071 | const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { | ||||||||||
5072 | auto IsReachable = | ||||||||||
5073 | [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; | ||||||||||
5074 | if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { | ||||||||||
5075 | const Loop *L = LI.getLoopFor(PN->getParent()); | ||||||||||
5076 | |||||||||||
5077 | // We don't want to break LCSSA, even in a SCEV expression tree. | ||||||||||
5078 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) | ||||||||||
5079 | if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) | ||||||||||
5080 | return nullptr; | ||||||||||
5081 | |||||||||||
5082 | // Try to match | ||||||||||
5083 | // | ||||||||||
5084 | // br %cond, label %left, label %right | ||||||||||
5085 | // left: | ||||||||||
5086 | // br label %merge | ||||||||||
5087 | // right: | ||||||||||
5088 | // br label %merge | ||||||||||
5089 | // merge: | ||||||||||
5090 | // V = phi [ %x, %left ], [ %y, %right ] | ||||||||||
5091 | // | ||||||||||
5092 | // as "select %cond, %x, %y" | ||||||||||
5093 | |||||||||||
5094 | BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); | ||||||||||
5095 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5095, __PRETTY_FUNCTION__)); | ||||||||||
5096 | |||||||||||
5097 | auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); | ||||||||||
5098 | Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; | ||||||||||
5099 | |||||||||||
5100 | if (BI && BI->isConditional() && | ||||||||||
5101 | BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && | ||||||||||
5102 | IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && | ||||||||||
5103 | IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) | ||||||||||
5104 | return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); | ||||||||||
5105 | } | ||||||||||
5106 | |||||||||||
5107 | return nullptr; | ||||||||||
5108 | } | ||||||||||
5109 | |||||||||||
5110 | const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { | ||||||||||
5111 | if (const SCEV *S = createAddRecFromPHI(PN)) | ||||||||||
5112 | return S; | ||||||||||
5113 | |||||||||||
5114 | if (const SCEV *S = createNodeFromSelectLikePHI(PN)) | ||||||||||
5115 | return S; | ||||||||||
5116 | |||||||||||
5117 | // If the PHI has a single incoming value, follow that value, unless the | ||||||||||
5118 | // PHI's incoming blocks are in a different loop, in which case doing so | ||||||||||
5119 | // risks breaking LCSSA form. Instcombine would normally zap these, but | ||||||||||
5120 | // it doesn't have DominatorTree information, so it may miss cases. | ||||||||||
5121 | if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) | ||||||||||
5122 | if (LI.replacementPreservesLCSSAForm(PN, V)) | ||||||||||
5123 | return getSCEV(V); | ||||||||||
5124 | |||||||||||
5125 | // If it's not a loop phi, we can't handle it yet. | ||||||||||
5126 | return getUnknown(PN); | ||||||||||
5127 | } | ||||||||||
5128 | |||||||||||
5129 | const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, | ||||||||||
5130 | Value *Cond, | ||||||||||
5131 | Value *TrueVal, | ||||||||||
5132 | Value *FalseVal) { | ||||||||||
5133 | // Handle "constant" branch or select. This can occur for instance when a | ||||||||||
5134 | // loop pass transforms an inner loop and moves on to process the outer loop. | ||||||||||
5135 | if (auto *CI = dyn_cast<ConstantInt>(Cond)) | ||||||||||
5136 | return getSCEV(CI->isOne() ? TrueVal : FalseVal); | ||||||||||
5137 | |||||||||||
5138 | // Try to match some simple smax or umax patterns. | ||||||||||
5139 | auto *ICI = dyn_cast<ICmpInst>(Cond); | ||||||||||
5140 | if (!ICI) | ||||||||||
5141 | return getUnknown(I); | ||||||||||
5142 | |||||||||||
5143 | Value *LHS = ICI->getOperand(0); | ||||||||||
5144 | Value *RHS = ICI->getOperand(1); | ||||||||||
5145 | |||||||||||
5146 | switch (ICI->getPredicate()) { | ||||||||||
5147 | case ICmpInst::ICMP_SLT: | ||||||||||
5148 | case ICmpInst::ICMP_SLE: | ||||||||||
5149 | std::swap(LHS, RHS); | ||||||||||
5150 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
5151 | case ICmpInst::ICMP_SGT: | ||||||||||
5152 | case ICmpInst::ICMP_SGE: | ||||||||||
5153 | // a >s b ? a+x : b+x -> smax(a, b)+x | ||||||||||
5154 | // a >s b ? b+x : a+x -> smin(a, b)+x | ||||||||||
5155 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { | ||||||||||
5156 | const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); | ||||||||||
5157 | const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); | ||||||||||
5158 | const SCEV *LA = getSCEV(TrueVal); | ||||||||||
5159 | const SCEV *RA = getSCEV(FalseVal); | ||||||||||
5160 | const SCEV *LDiff = getMinusSCEV(LA, LS); | ||||||||||
5161 | const SCEV *RDiff = getMinusSCEV(RA, RS); | ||||||||||
5162 | if (LDiff == RDiff) | ||||||||||
5163 | return getAddExpr(getSMaxExpr(LS, RS), LDiff); | ||||||||||
5164 | LDiff = getMinusSCEV(LA, RS); | ||||||||||
5165 | RDiff = getMinusSCEV(RA, LS); | ||||||||||
5166 | if (LDiff == RDiff) | ||||||||||
5167 | return getAddExpr(getSMinExpr(LS, RS), LDiff); | ||||||||||
5168 | } | ||||||||||
5169 | break; | ||||||||||
5170 | case ICmpInst::ICMP_ULT: | ||||||||||
5171 | case ICmpInst::ICMP_ULE: | ||||||||||
5172 | std::swap(LHS, RHS); | ||||||||||
5173 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
5174 | case ICmpInst::ICMP_UGT: | ||||||||||
5175 | case ICmpInst::ICMP_UGE: | ||||||||||
5176 | // a >u b ? a+x : b+x -> umax(a, b)+x | ||||||||||
5177 | // a >u b ? b+x : a+x -> umin(a, b)+x | ||||||||||
5178 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { | ||||||||||
5179 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); | ||||||||||
5180 | const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); | ||||||||||
5181 | const SCEV *LA = getSCEV(TrueVal); | ||||||||||
5182 | const SCEV *RA = getSCEV(FalseVal); | ||||||||||
5183 | const SCEV *LDiff = getMinusSCEV(LA, LS); | ||||||||||
5184 | const SCEV *RDiff = getMinusSCEV(RA, RS); | ||||||||||
5185 | if (LDiff == RDiff) | ||||||||||
5186 | return getAddExpr(getUMaxExpr(LS, RS), LDiff); | ||||||||||
5187 | LDiff = getMinusSCEV(LA, RS); | ||||||||||
5188 | RDiff = getMinusSCEV(RA, LS); | ||||||||||
5189 | if (LDiff == RDiff) | ||||||||||
5190 | return getAddExpr(getUMinExpr(LS, RS), LDiff); | ||||||||||
5191 | } | ||||||||||
5192 | break; | ||||||||||
5193 | case ICmpInst::ICMP_NE: | ||||||||||
5194 | // n != 0 ? n+x : 1+x -> umax(n, 1)+x | ||||||||||
5195 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && | ||||||||||
5196 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { | ||||||||||
5197 | const SCEV *One = getOne(I->getType()); | ||||||||||
5198 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); | ||||||||||
5199 | const SCEV *LA = getSCEV(TrueVal); | ||||||||||
5200 | const SCEV *RA = getSCEV(FalseVal); | ||||||||||
5201 | const SCEV *LDiff = getMinusSCEV(LA, LS); | ||||||||||
5202 | const SCEV *RDiff = getMinusSCEV(RA, One); | ||||||||||
5203 | if (LDiff == RDiff) | ||||||||||
5204 | return getAddExpr(getUMaxExpr(One, LS), LDiff); | ||||||||||
5205 | } | ||||||||||
5206 | break; | ||||||||||
5207 | case ICmpInst::ICMP_EQ: | ||||||||||
5208 | // n == 0 ? 1+x : n+x -> umax(n, 1)+x | ||||||||||
5209 | if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && | ||||||||||
5210 | isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { | ||||||||||
5211 | const SCEV *One = getOne(I->getType()); | ||||||||||
5212 | const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); | ||||||||||
5213 | const SCEV *LA = getSCEV(TrueVal); | ||||||||||
5214 | const SCEV *RA = getSCEV(FalseVal); | ||||||||||
5215 | const SCEV *LDiff = getMinusSCEV(LA, One); | ||||||||||
5216 | const SCEV *RDiff = getMinusSCEV(RA, LS); | ||||||||||
5217 | if (LDiff == RDiff) | ||||||||||
5218 | return getAddExpr(getUMaxExpr(One, LS), LDiff); | ||||||||||
5219 | } | ||||||||||
5220 | break; | ||||||||||
5221 | default: | ||||||||||
5222 | break; | ||||||||||
5223 | } | ||||||||||
5224 | |||||||||||
5225 | return getUnknown(I); | ||||||||||
5226 | } | ||||||||||
5227 | |||||||||||
5228 | /// Expand GEP instructions into add and multiply operations. This allows them | ||||||||||
5229 | /// to be analyzed by regular SCEV code. | ||||||||||
5230 | const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { | ||||||||||
5231 | // Don't attempt to analyze GEPs over unsized objects. | ||||||||||
5232 | if (!GEP->getSourceElementType()->isSized()) | ||||||||||
5233 | return getUnknown(GEP); | ||||||||||
5234 | |||||||||||
5235 | SmallVector<const SCEV *, 4> IndexExprs; | ||||||||||
5236 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) | ||||||||||
5237 | IndexExprs.push_back(getSCEV(*Index)); | ||||||||||
5238 | return getGEPExpr(GEP, IndexExprs); | ||||||||||
5239 | } | ||||||||||
5240 | |||||||||||
5241 | uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { | ||||||||||
5242 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) | ||||||||||
5243 | return C->getAPInt().countTrailingZeros(); | ||||||||||
5244 | |||||||||||
5245 | if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) | ||||||||||
5246 | return std::min(GetMinTrailingZeros(T->getOperand()), | ||||||||||
5247 | (uint32_t)getTypeSizeInBits(T->getType())); | ||||||||||
5248 | |||||||||||
5249 | if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { | ||||||||||
5250 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); | ||||||||||
5251 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) | ||||||||||
5252 | ? getTypeSizeInBits(E->getType()) | ||||||||||
5253 | : OpRes; | ||||||||||
5254 | } | ||||||||||
5255 | |||||||||||
5256 | if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { | ||||||||||
5257 | uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); | ||||||||||
5258 | return OpRes == getTypeSizeInBits(E->getOperand()->getType()) | ||||||||||
5259 | ? getTypeSizeInBits(E->getType()) | ||||||||||
5260 | : OpRes; | ||||||||||
5261 | } | ||||||||||
5262 | |||||||||||
5263 | if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { | ||||||||||
5264 | // The result is the min of all operands results. | ||||||||||
5265 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); | ||||||||||
5266 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) | ||||||||||
5267 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); | ||||||||||
5268 | return MinOpRes; | ||||||||||
5269 | } | ||||||||||
5270 | |||||||||||
5271 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { | ||||||||||
5272 | // The result is the sum of all operands results. | ||||||||||
5273 | uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); | ||||||||||
5274 | uint32_t BitWidth = getTypeSizeInBits(M->getType()); | ||||||||||
5275 | for (unsigned i = 1, e = M->getNumOperands(); | ||||||||||
5276 | SumOpRes != BitWidth && i != e; ++i) | ||||||||||
5277 | SumOpRes = | ||||||||||
5278 | std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); | ||||||||||
5279 | return SumOpRes; | ||||||||||
5280 | } | ||||||||||
5281 | |||||||||||
5282 | if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { | ||||||||||
5283 | // The result is the min of all operands results. | ||||||||||
5284 | uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); | ||||||||||
5285 | for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) | ||||||||||
5286 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); | ||||||||||
5287 | return MinOpRes; | ||||||||||
5288 | } | ||||||||||
5289 | |||||||||||
5290 | if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { | ||||||||||
5291 | // The result is the min of all operands results. | ||||||||||
5292 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); | ||||||||||
5293 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) | ||||||||||
5294 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); | ||||||||||
5295 | return MinOpRes; | ||||||||||
5296 | } | ||||||||||
5297 | |||||||||||
5298 | if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { | ||||||||||
5299 | // The result is the min of all operands results. | ||||||||||
5300 | uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); | ||||||||||
5301 | for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) | ||||||||||
5302 | MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); | ||||||||||
5303 | return MinOpRes; | ||||||||||
5304 | } | ||||||||||
5305 | |||||||||||
5306 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { | ||||||||||
5307 | // For a SCEVUnknown, ask ValueTracking. | ||||||||||
5308 | KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); | ||||||||||
5309 | return Known.countMinTrailingZeros(); | ||||||||||
5310 | } | ||||||||||
5311 | |||||||||||
5312 | // SCEVUDivExpr | ||||||||||
5313 | return 0; | ||||||||||
5314 | } | ||||||||||
5315 | |||||||||||
5316 | uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { | ||||||||||
5317 | auto I = MinTrailingZerosCache.find(S); | ||||||||||
5318 | if (I != MinTrailingZerosCache.end()) | ||||||||||
5319 | return I->second; | ||||||||||
5320 | |||||||||||
5321 | uint32_t Result = GetMinTrailingZerosImpl(S); | ||||||||||
5322 | auto InsertPair = MinTrailingZerosCache.insert({S, Result}); | ||||||||||
5323 | 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~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5323, __PRETTY_FUNCTION__)); | ||||||||||
5324 | return InsertPair.first->second; | ||||||||||
5325 | } | ||||||||||
5326 | |||||||||||
5327 | /// Helper method to assign a range to V from metadata present in the IR. | ||||||||||
5328 | static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { | ||||||||||
5329 | if (Instruction *I = dyn_cast<Instruction>(V)) | ||||||||||
5330 | if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) | ||||||||||
5331 | return getConstantRangeFromMetadata(*MD); | ||||||||||
5332 | |||||||||||
5333 | return None; | ||||||||||
5334 | } | ||||||||||
5335 | |||||||||||
5336 | /// Determine the range for a particular SCEV. If SignHint is | ||||||||||
5337 | /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges | ||||||||||
5338 | /// with a "cleaner" unsigned (resp. signed) representation. | ||||||||||
5339 | const ConstantRange & | ||||||||||
5340 | ScalarEvolution::getRangeRef(const SCEV *S, | ||||||||||
5341 | ScalarEvolution::RangeSignHint SignHint) { | ||||||||||
5342 | DenseMap<const SCEV *, ConstantRange> &Cache = | ||||||||||
5343 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges | ||||||||||
5344 | : SignedRanges; | ||||||||||
5345 | ConstantRange::PreferredRangeType RangeType = | ||||||||||
5346 | SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED | ||||||||||
5347 | ? ConstantRange::Unsigned : ConstantRange::Signed; | ||||||||||
5348 | |||||||||||
5349 | // See if we've computed this range already. | ||||||||||
5350 | DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); | ||||||||||
5351 | if (I != Cache.end()) | ||||||||||
5352 | return I->second; | ||||||||||
5353 | |||||||||||
5354 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) | ||||||||||
5355 | return setRange(C, SignHint, ConstantRange(C->getAPInt())); | ||||||||||
5356 | |||||||||||
5357 | unsigned BitWidth = getTypeSizeInBits(S->getType()); | ||||||||||
5358 | ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); | ||||||||||
5359 | using OBO = OverflowingBinaryOperator; | ||||||||||
5360 | |||||||||||
5361 | // If the value has known zeros, the maximum value will have those known zeros | ||||||||||
5362 | // as well. | ||||||||||
5363 | uint32_t TZ = GetMinTrailingZeros(S); | ||||||||||
5364 | if (TZ != 0) { | ||||||||||
5365 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) | ||||||||||
5366 | ConservativeResult = | ||||||||||
5367 | ConstantRange(APInt::getMinValue(BitWidth), | ||||||||||
5368 | APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); | ||||||||||
5369 | else | ||||||||||
5370 | ConservativeResult = ConstantRange( | ||||||||||
5371 | APInt::getSignedMinValue(BitWidth), | ||||||||||
5372 | APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); | ||||||||||
5373 | } | ||||||||||
5374 | |||||||||||
5375 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | ||||||||||
5376 | ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); | ||||||||||
5377 | unsigned WrapType = OBO::AnyWrap; | ||||||||||
5378 | if (Add->hasNoSignedWrap()) | ||||||||||
5379 | WrapType |= OBO::NoSignedWrap; | ||||||||||
5380 | if (Add->hasNoUnsignedWrap()) | ||||||||||
5381 | WrapType |= OBO::NoUnsignedWrap; | ||||||||||
5382 | for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) | ||||||||||
5383 | X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), | ||||||||||
5384 | WrapType, RangeType); | ||||||||||
5385 | return setRange(Add, SignHint, | ||||||||||
5386 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5387 | } | ||||||||||
5388 | |||||||||||
5389 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { | ||||||||||
5390 | ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); | ||||||||||
5391 | for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) | ||||||||||
5392 | X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); | ||||||||||
5393 | return setRange(Mul, SignHint, | ||||||||||
5394 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5395 | } | ||||||||||
5396 | |||||||||||
5397 | if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { | ||||||||||
5398 | ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); | ||||||||||
5399 | for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) | ||||||||||
5400 | X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); | ||||||||||
5401 | return setRange(SMax, SignHint, | ||||||||||
5402 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5403 | } | ||||||||||
5404 | |||||||||||
5405 | if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { | ||||||||||
5406 | ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); | ||||||||||
5407 | for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) | ||||||||||
5408 | X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); | ||||||||||
5409 | return setRange(UMax, SignHint, | ||||||||||
5410 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5411 | } | ||||||||||
5412 | |||||||||||
5413 | if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { | ||||||||||
5414 | ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); | ||||||||||
5415 | for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) | ||||||||||
5416 | X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); | ||||||||||
5417 | return setRange(SMin, SignHint, | ||||||||||
5418 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5419 | } | ||||||||||
5420 | |||||||||||
5421 | if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { | ||||||||||
5422 | ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); | ||||||||||
5423 | for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) | ||||||||||
5424 | X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); | ||||||||||
5425 | return setRange(UMin, SignHint, | ||||||||||
5426 | ConservativeResult.intersectWith(X, RangeType)); | ||||||||||
5427 | } | ||||||||||
5428 | |||||||||||
5429 | if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { | ||||||||||
5430 | ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); | ||||||||||
5431 | ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); | ||||||||||
5432 | return setRange(UDiv, SignHint, | ||||||||||
5433 | ConservativeResult.intersectWith(X.udiv(Y), RangeType)); | ||||||||||
5434 | } | ||||||||||
5435 | |||||||||||
5436 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { | ||||||||||
5437 | ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); | ||||||||||
5438 | return setRange(ZExt, SignHint, | ||||||||||
5439 | ConservativeResult.intersectWith(X.zeroExtend(BitWidth), | ||||||||||
5440 | RangeType)); | ||||||||||
5441 | } | ||||||||||
5442 | |||||||||||
5443 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { | ||||||||||
5444 | ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); | ||||||||||
5445 | return setRange(SExt, SignHint, | ||||||||||
5446 | ConservativeResult.intersectWith(X.signExtend(BitWidth), | ||||||||||
5447 | RangeType)); | ||||||||||
5448 | } | ||||||||||
5449 | |||||||||||
5450 | if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { | ||||||||||
5451 | ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); | ||||||||||
5452 | return setRange(Trunc, SignHint, | ||||||||||
5453 | ConservativeResult.intersectWith(X.truncate(BitWidth), | ||||||||||
5454 | RangeType)); | ||||||||||
5455 | } | ||||||||||
5456 | |||||||||||
5457 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { | ||||||||||
5458 | // If there's no unsigned wrap, the value will never be less than its | ||||||||||
5459 | // initial value. | ||||||||||
5460 | if (AddRec->hasNoUnsignedWrap()) { | ||||||||||
5461 | APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); | ||||||||||
5462 | if (!UnsignedMinValue.isNullValue()) | ||||||||||
5463 | ConservativeResult = ConservativeResult.intersectWith( | ||||||||||
5464 | ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); | ||||||||||
5465 | } | ||||||||||
5466 | |||||||||||
5467 | // If there's no signed wrap, and all the operands except initial value have | ||||||||||
5468 | // the same sign or zero, the value won't ever be: | ||||||||||
5469 | // 1: smaller than initial value if operands are non negative, | ||||||||||
5470 | // 2: bigger than initial value if operands are non positive. | ||||||||||
5471 | // For both cases, value can not cross signed min/max boundary. | ||||||||||
5472 | if (AddRec->hasNoSignedWrap()) { | ||||||||||
5473 | bool AllNonNeg = true; | ||||||||||
5474 | bool AllNonPos = true; | ||||||||||
5475 | for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { | ||||||||||
5476 | if (!isKnownNonNegative(AddRec->getOperand(i))) | ||||||||||
5477 | AllNonNeg = false; | ||||||||||
5478 | if (!isKnownNonPositive(AddRec->getOperand(i))) | ||||||||||
5479 | AllNonPos = false; | ||||||||||
5480 | } | ||||||||||
5481 | if (AllNonNeg) | ||||||||||
5482 | ConservativeResult = ConservativeResult.intersectWith( | ||||||||||
5483 | ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), | ||||||||||
5484 | APInt::getSignedMinValue(BitWidth)), | ||||||||||
5485 | RangeType); | ||||||||||
5486 | else if (AllNonPos) | ||||||||||
5487 | ConservativeResult = ConservativeResult.intersectWith( | ||||||||||
5488 | ConstantRange::getNonEmpty( | ||||||||||
5489 | APInt::getSignedMinValue(BitWidth), | ||||||||||
5490 | getSignedRangeMax(AddRec->getStart()) + 1), | ||||||||||
5491 | RangeType); | ||||||||||
5492 | } | ||||||||||
5493 | |||||||||||
5494 | // TODO: non-affine addrec | ||||||||||
5495 | if (AddRec->isAffine()) { | ||||||||||
5496 | const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); | ||||||||||
5497 | if (!isa<SCEVCouldNotCompute>(MaxBECount) && | ||||||||||
5498 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { | ||||||||||
5499 | auto RangeFromAffine = getRangeForAffineAR( | ||||||||||
5500 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, | ||||||||||
5501 | BitWidth); | ||||||||||
5502 | if (!RangeFromAffine.isFullSet()) | ||||||||||
5503 | ConservativeResult = | ||||||||||
5504 | ConservativeResult.intersectWith(RangeFromAffine, RangeType); | ||||||||||
5505 | |||||||||||
5506 | auto RangeFromFactoring = getRangeViaFactoring( | ||||||||||
5507 | AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, | ||||||||||
5508 | BitWidth); | ||||||||||
5509 | if (!RangeFromFactoring.isFullSet()) | ||||||||||
5510 | ConservativeResult = | ||||||||||
5511 | ConservativeResult.intersectWith(RangeFromFactoring, RangeType); | ||||||||||
5512 | } | ||||||||||
5513 | } | ||||||||||
5514 | |||||||||||
5515 | return setRange(AddRec, SignHint, std::move(ConservativeResult)); | ||||||||||
5516 | } | ||||||||||
5517 | |||||||||||
5518 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { | ||||||||||
5519 | // Check if the IR explicitly contains !range metadata. | ||||||||||
5520 | Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); | ||||||||||
5521 | if (MDRange.hasValue()) | ||||||||||
5522 | ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), | ||||||||||
5523 | RangeType); | ||||||||||
5524 | |||||||||||
5525 | // Split here to avoid paying the compile-time cost of calling both | ||||||||||
5526 | // computeKnownBits and ComputeNumSignBits. This restriction can be lifted | ||||||||||
5527 | // if needed. | ||||||||||
5528 | const DataLayout &DL = getDataLayout(); | ||||||||||
5529 | if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { | ||||||||||
5530 | // For a SCEVUnknown, ask ValueTracking. | ||||||||||
5531 | KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); | ||||||||||
5532 | if (Known.getBitWidth() != BitWidth) | ||||||||||
5533 | Known = Known.zextOrTrunc(BitWidth); | ||||||||||
5534 | // If Known does not result in full-set, intersect with it. | ||||||||||
5535 | if (Known.getMinValue() != Known.getMaxValue() + 1) | ||||||||||
5536 | ConservativeResult = ConservativeResult.intersectWith( | ||||||||||
5537 | ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), | ||||||||||
5538 | RangeType); | ||||||||||
5539 | } else { | ||||||||||
5540 | assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!" ) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5541, __PRETTY_FUNCTION__)) | ||||||||||
5541 | "generalize as needed!")((SignHint == ScalarEvolution::HINT_RANGE_SIGNED && "generalize as needed!" ) ? static_cast<void> (0) : __assert_fail ("SignHint == ScalarEvolution::HINT_RANGE_SIGNED && \"generalize as needed!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5541, __PRETTY_FUNCTION__)); | ||||||||||
5542 | unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); | ||||||||||
5543 | // If the pointer size is larger than the index size type, this can cause | ||||||||||
5544 | // NS to be larger than BitWidth. So compensate for this. | ||||||||||
5545 | if (U->getType()->isPointerTy()) { | ||||||||||
5546 | unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); | ||||||||||
5547 | int ptrIdxDiff = ptrSize - BitWidth; | ||||||||||
5548 | if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) | ||||||||||
5549 | NS -= ptrIdxDiff; | ||||||||||
5550 | } | ||||||||||
5551 | |||||||||||
5552 | if (NS > 1) | ||||||||||
5553 | ConservativeResult = ConservativeResult.intersectWith( | ||||||||||
5554 | ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), | ||||||||||
5555 | APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), | ||||||||||
5556 | RangeType); | ||||||||||
5557 | } | ||||||||||
5558 | |||||||||||
5559 | // A range of Phi is a subset of union of all ranges of its input. | ||||||||||
5560 | if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { | ||||||||||
5561 | // Make sure that we do not run over cycled Phis. | ||||||||||
5562 | if (PendingPhiRanges.insert(Phi).second) { | ||||||||||
5563 | ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); | ||||||||||
5564 | for (auto &Op : Phi->operands()) { | ||||||||||
5565 | auto OpRange = getRangeRef(getSCEV(Op), SignHint); | ||||||||||
5566 | RangeFromOps = RangeFromOps.unionWith(OpRange); | ||||||||||
5567 | // No point to continue if we already have a full set. | ||||||||||
5568 | if (RangeFromOps.isFullSet()) | ||||||||||
5569 | break; | ||||||||||
5570 | } | ||||||||||
5571 | ConservativeResult = | ||||||||||
5572 | ConservativeResult.intersectWith(RangeFromOps, RangeType); | ||||||||||
5573 | bool Erased = PendingPhiRanges.erase(Phi); | ||||||||||
5574 | assert(Erased && "Failed to erase Phi properly?")((Erased && "Failed to erase Phi properly?") ? static_cast <void> (0) : __assert_fail ("Erased && \"Failed to erase Phi properly?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5574, __PRETTY_FUNCTION__)); | ||||||||||
5575 | (void) Erased; | ||||||||||
5576 | } | ||||||||||
5577 | } | ||||||||||
5578 | |||||||||||
5579 | return setRange(U, SignHint, std::move(ConservativeResult)); | ||||||||||
5580 | } | ||||||||||
5581 | |||||||||||
5582 | return setRange(S, SignHint, std::move(ConservativeResult)); | ||||||||||
5583 | } | ||||||||||
5584 | |||||||||||
5585 | // Given a StartRange, Step and MaxBECount for an expression compute a range of | ||||||||||
5586 | // values that the expression can take. Initially, the expression has a value | ||||||||||
5587 | // from StartRange and then is changed by Step up to MaxBECount times. Signed | ||||||||||
5588 | // argument defines if we treat Step as signed or unsigned. | ||||||||||
5589 | static ConstantRange getRangeForAffineARHelper(APInt Step, | ||||||||||
5590 | const ConstantRange &StartRange, | ||||||||||
5591 | const APInt &MaxBECount, | ||||||||||
5592 | unsigned BitWidth, bool Signed) { | ||||||||||
5593 | // If either Step or MaxBECount is 0, then the expression won't change, and we | ||||||||||
5594 | // just need to return the initial range. | ||||||||||
5595 | if (Step == 0 || MaxBECount == 0) | ||||||||||
5596 | return StartRange; | ||||||||||
5597 | |||||||||||
5598 | // If we don't know anything about the initial value (i.e. StartRange is | ||||||||||
5599 | // FullRange), then we don't know anything about the final range either. | ||||||||||
5600 | // Return FullRange. | ||||||||||
5601 | if (StartRange.isFullSet()) | ||||||||||
5602 | return ConstantRange::getFull(BitWidth); | ||||||||||
5603 | |||||||||||
5604 | // If Step is signed and negative, then we use its absolute value, but we also | ||||||||||
5605 | // note that we're moving in the opposite direction. | ||||||||||
5606 | bool Descending = Signed && Step.isNegative(); | ||||||||||
5607 | |||||||||||
5608 | if (Signed) | ||||||||||
5609 | // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: | ||||||||||
5610 | // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. | ||||||||||
5611 | // This equations hold true due to the well-defined wrap-around behavior of | ||||||||||
5612 | // APInt. | ||||||||||
5613 | Step = Step.abs(); | ||||||||||
5614 | |||||||||||
5615 | // Check if Offset is more than full span of BitWidth. If it is, the | ||||||||||
5616 | // expression is guaranteed to overflow. | ||||||||||
5617 | if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) | ||||||||||
5618 | return ConstantRange::getFull(BitWidth); | ||||||||||
5619 | |||||||||||
5620 | // Offset is by how much the expression can change. Checks above guarantee no | ||||||||||
5621 | // overflow here. | ||||||||||
5622 | APInt Offset = Step * MaxBECount; | ||||||||||
5623 | |||||||||||
5624 | // Minimum value of the final range will match the minimal value of StartRange | ||||||||||
5625 | // if the expression is increasing and will be decreased by Offset otherwise. | ||||||||||
5626 | // Maximum value of the final range will match the maximal value of StartRange | ||||||||||
5627 | // if the expression is decreasing and will be increased by Offset otherwise. | ||||||||||
5628 | APInt StartLower = StartRange.getLower(); | ||||||||||
5629 | APInt StartUpper = StartRange.getUpper() - 1; | ||||||||||
5630 | APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) | ||||||||||
5631 | : (StartUpper + std::move(Offset)); | ||||||||||
5632 | |||||||||||
5633 | // It's possible that the new minimum/maximum value will fall into the initial | ||||||||||
5634 | // range (due to wrap around). This means that the expression can take any | ||||||||||
5635 | // value in this bitwidth, and we have to return full range. | ||||||||||
5636 | if (StartRange.contains(MovedBoundary)) | ||||||||||
5637 | return ConstantRange::getFull(BitWidth); | ||||||||||
5638 | |||||||||||
5639 | APInt NewLower = | ||||||||||
5640 | Descending ? std::move(MovedBoundary) : std::move(StartLower); | ||||||||||
5641 | APInt NewUpper = | ||||||||||
5642 | Descending ? std::move(StartUpper) : std::move(MovedBoundary); | ||||||||||
5643 | NewUpper += 1; | ||||||||||
5644 | |||||||||||
5645 | // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. | ||||||||||
5646 | return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); | ||||||||||
5647 | } | ||||||||||
5648 | |||||||||||
5649 | ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, | ||||||||||
5650 | const SCEV *Step, | ||||||||||
5651 | const SCEV *MaxBECount, | ||||||||||
5652 | unsigned BitWidth) { | ||||||||||
5653 | assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits (MaxBECount->getType()) <= BitWidth && "Precondition!" ) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5655, __PRETTY_FUNCTION__)) | ||||||||||
5654 | getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits (MaxBECount->getType()) <= BitWidth && "Precondition!" ) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5655, __PRETTY_FUNCTION__)) | ||||||||||
5655 | "Precondition!")((!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits (MaxBECount->getType()) <= BitWidth && "Precondition!" ) ? static_cast<void> (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(MaxBECount) && getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && \"Precondition!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5655, __PRETTY_FUNCTION__)); | ||||||||||
5656 | |||||||||||
5657 | MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); | ||||||||||
5658 | APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); | ||||||||||
5659 | |||||||||||
5660 | // First, consider step signed. | ||||||||||
5661 | ConstantRange StartSRange = getSignedRange(Start); | ||||||||||
5662 | ConstantRange StepSRange = getSignedRange(Step); | ||||||||||
5663 | |||||||||||
5664 | // If Step can be both positive and negative, we need to find ranges for the | ||||||||||
5665 | // maximum absolute step values in both directions and union them. | ||||||||||
5666 | ConstantRange SR = | ||||||||||
5667 | getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, | ||||||||||
5668 | MaxBECountValue, BitWidth, /* Signed = */ true); | ||||||||||
5669 | SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), | ||||||||||
5670 | StartSRange, MaxBECountValue, | ||||||||||
5671 | BitWidth, /* Signed = */ true)); | ||||||||||
5672 | |||||||||||
5673 | // Next, consider step unsigned. | ||||||||||
5674 | ConstantRange UR = getRangeForAffineARHelper( | ||||||||||
5675 | getUnsignedRangeMax(Step), getUnsignedRange(Start), | ||||||||||
5676 | MaxBECountValue, BitWidth, /* Signed = */ false); | ||||||||||
5677 | |||||||||||
5678 | // Finally, intersect signed and unsigned ranges. | ||||||||||
5679 | return SR.intersectWith(UR, ConstantRange::Smallest); | ||||||||||
5680 | } | ||||||||||
5681 | |||||||||||
5682 | ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, | ||||||||||
5683 | const SCEV *Step, | ||||||||||
5684 | const SCEV *MaxBECount, | ||||||||||
5685 | unsigned BitWidth) { | ||||||||||
5686 | // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) | ||||||||||
5687 | // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) | ||||||||||
5688 | |||||||||||
5689 | struct SelectPattern { | ||||||||||
5690 | Value *Condition = nullptr; | ||||||||||
5691 | APInt TrueValue; | ||||||||||
5692 | APInt FalseValue; | ||||||||||
5693 | |||||||||||
5694 | explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, | ||||||||||
5695 | const SCEV *S) { | ||||||||||
5696 | Optional<unsigned> CastOp; | ||||||||||
5697 | APInt Offset(BitWidth, 0); | ||||||||||
5698 | |||||||||||
5699 | assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&((SE.getTypeSizeInBits(S->getType()) == BitWidth && "Should be!") ? static_cast<void> (0) : __assert_fail ( "SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5700, __PRETTY_FUNCTION__)) | ||||||||||
5700 | "Should be!")((SE.getTypeSizeInBits(S->getType()) == BitWidth && "Should be!") ? static_cast<void> (0) : __assert_fail ( "SE.getTypeSizeInBits(S->getType()) == BitWidth && \"Should be!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5700, __PRETTY_FUNCTION__)); | ||||||||||
5701 | |||||||||||
5702 | // Peel off a constant offset: | ||||||||||
5703 | if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { | ||||||||||
5704 | // In the future we could consider being smarter here and handle | ||||||||||
5705 | // {Start+Step,+,Step} too. | ||||||||||
5706 | if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) | ||||||||||
5707 | return; | ||||||||||
5708 | |||||||||||
5709 | Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); | ||||||||||
5710 | S = SA->getOperand(1); | ||||||||||
5711 | } | ||||||||||
5712 | |||||||||||
5713 | // Peel off a cast operation | ||||||||||
5714 | if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { | ||||||||||
5715 | CastOp = SCast->getSCEVType(); | ||||||||||
5716 | S = SCast->getOperand(); | ||||||||||
5717 | } | ||||||||||
5718 | |||||||||||
5719 | using namespace llvm::PatternMatch; | ||||||||||
5720 | |||||||||||
5721 | auto *SU = dyn_cast<SCEVUnknown>(S); | ||||||||||
5722 | const APInt *TrueVal, *FalseVal; | ||||||||||
5723 | if (!SU || | ||||||||||
5724 | !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), | ||||||||||
5725 | m_APInt(FalseVal)))) { | ||||||||||
5726 | Condition = nullptr; | ||||||||||
5727 | return; | ||||||||||
5728 | } | ||||||||||
5729 | |||||||||||
5730 | TrueValue = *TrueVal; | ||||||||||
5731 | FalseValue = *FalseVal; | ||||||||||
5732 | |||||||||||
5733 | // Re-apply the cast we peeled off earlier | ||||||||||
5734 | if (CastOp.hasValue()) | ||||||||||
5735 | switch (*CastOp) { | ||||||||||
5736 | default: | ||||||||||
5737 | llvm_unreachable("Unknown SCEV cast type!")::llvm::llvm_unreachable_internal("Unknown SCEV cast type!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5737); | ||||||||||
5738 | |||||||||||
5739 | case scTruncate: | ||||||||||
5740 | TrueValue = TrueValue.trunc(BitWidth); | ||||||||||
5741 | FalseValue = FalseValue.trunc(BitWidth); | ||||||||||
5742 | break; | ||||||||||
5743 | case scZeroExtend: | ||||||||||
5744 | TrueValue = TrueValue.zext(BitWidth); | ||||||||||
5745 | FalseValue = FalseValue.zext(BitWidth); | ||||||||||
5746 | break; | ||||||||||
5747 | case scSignExtend: | ||||||||||
5748 | TrueValue = TrueValue.sext(BitWidth); | ||||||||||
5749 | FalseValue = FalseValue.sext(BitWidth); | ||||||||||
5750 | break; | ||||||||||
5751 | } | ||||||||||
5752 | |||||||||||
5753 | // Re-apply the constant offset we peeled off earlier | ||||||||||
5754 | TrueValue += Offset; | ||||||||||
5755 | FalseValue += Offset; | ||||||||||
5756 | } | ||||||||||
5757 | |||||||||||
5758 | bool isRecognized() { return Condition != nullptr; } | ||||||||||
5759 | }; | ||||||||||
5760 | |||||||||||
5761 | SelectPattern StartPattern(*this, BitWidth, Start); | ||||||||||
5762 | if (!StartPattern.isRecognized()) | ||||||||||
5763 | return ConstantRange::getFull(BitWidth); | ||||||||||
5764 | |||||||||||
5765 | SelectPattern StepPattern(*this, BitWidth, Step); | ||||||||||
5766 | if (!StepPattern.isRecognized()) | ||||||||||
5767 | return ConstantRange::getFull(BitWidth); | ||||||||||
5768 | |||||||||||
5769 | if (StartPattern.Condition != StepPattern.Condition) { | ||||||||||
5770 | // We don't handle this case today; but we could, by considering four | ||||||||||
5771 | // possibilities below instead of two. I'm not sure if there are cases where | ||||||||||
5772 | // that will help over what getRange already does, though. | ||||||||||
5773 | return ConstantRange::getFull(BitWidth); | ||||||||||
5774 | } | ||||||||||
5775 | |||||||||||
5776 | // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to | ||||||||||
5777 | // construct arbitrary general SCEV expressions here. This function is called | ||||||||||
5778 | // from deep in the call stack, and calling getSCEV (on a sext instruction, | ||||||||||
5779 | // say) can end up caching a suboptimal value. | ||||||||||
5780 | |||||||||||
5781 | // FIXME: without the explicit `this` receiver below, MSVC errors out with | ||||||||||
5782 | // C2352 and C2512 (otherwise it isn't needed). | ||||||||||
5783 | |||||||||||
5784 | const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); | ||||||||||
5785 | const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); | ||||||||||
5786 | const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); | ||||||||||
5787 | const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); | ||||||||||
5788 | |||||||||||
5789 | ConstantRange TrueRange = | ||||||||||
5790 | this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); | ||||||||||
5791 | ConstantRange FalseRange = | ||||||||||
5792 | this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); | ||||||||||
5793 | |||||||||||
5794 | return TrueRange.unionWith(FalseRange); | ||||||||||
5795 | } | ||||||||||
5796 | |||||||||||
5797 | SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { | ||||||||||
5798 | if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; | ||||||||||
5799 | const BinaryOperator *BinOp = cast<BinaryOperator>(V); | ||||||||||
5800 | |||||||||||
5801 | // Return early if there are no flags to propagate to the SCEV. | ||||||||||
5802 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; | ||||||||||
5803 | if (BinOp->hasNoUnsignedWrap()) | ||||||||||
5804 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); | ||||||||||
5805 | if (BinOp->hasNoSignedWrap()) | ||||||||||
5806 | Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); | ||||||||||
5807 | if (Flags == SCEV::FlagAnyWrap) | ||||||||||
5808 | return SCEV::FlagAnyWrap; | ||||||||||
5809 | |||||||||||
5810 | return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; | ||||||||||
5811 | } | ||||||||||
5812 | |||||||||||
5813 | bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { | ||||||||||
5814 | // Here we check that I is in the header of the innermost loop containing I, | ||||||||||
5815 | // since we only deal with instructions in the loop header. The actual loop we | ||||||||||
5816 | // need to check later will come from an add recurrence, but getting that | ||||||||||
5817 | // requires computing the SCEV of the operands, which can be expensive. This | ||||||||||
5818 | // check we can do cheaply to rule out some cases early. | ||||||||||
5819 | Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); | ||||||||||
5820 | if (InnermostContainingLoop == nullptr || | ||||||||||
5821 | InnermostContainingLoop->getHeader() != I->getParent()) | ||||||||||
5822 | return false; | ||||||||||
5823 | |||||||||||
5824 | // Only proceed if we can prove that I does not yield poison. | ||||||||||
5825 | if (!programUndefinedIfPoison(I)) | ||||||||||
5826 | return false; | ||||||||||
5827 | |||||||||||
5828 | // At this point we know that if I is executed, then it does not wrap | ||||||||||
5829 | // according to at least one of NSW or NUW. If I is not executed, then we do | ||||||||||
5830 | // not know if the calculation that I represents would wrap. Multiple | ||||||||||
5831 | // instructions can map to the same SCEV. If we apply NSW or NUW from I to | ||||||||||
5832 | // the SCEV, we must guarantee no wrapping for that SCEV also when it is | ||||||||||
5833 | // derived from other instructions that map to the same SCEV. We cannot make | ||||||||||
5834 | // that guarantee for cases where I is not executed. So we need to find the | ||||||||||
5835 | // loop that I is considered in relation to and prove that I is executed for | ||||||||||
5836 | // every iteration of that loop. That implies that the value that I | ||||||||||
5837 | // calculates does not wrap anywhere in the loop, so then we can apply the | ||||||||||
5838 | // flags to the SCEV. | ||||||||||
5839 | // | ||||||||||
5840 | // We check isLoopInvariant to disambiguate in case we are adding recurrences | ||||||||||
5841 | // from different loops, so that we know which loop to prove that I is | ||||||||||
5842 | // executed in. | ||||||||||
5843 | for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { | ||||||||||
5844 | // I could be an extractvalue from a call to an overflow intrinsic. | ||||||||||
5845 | // TODO: We can do better here in some cases. | ||||||||||
5846 | if (!isSCEVable(I->getOperand(OpIndex)->getType())) | ||||||||||
5847 | return false; | ||||||||||
5848 | const SCEV *Op = getSCEV(I->getOperand(OpIndex)); | ||||||||||
5849 | if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { | ||||||||||
5850 | bool AllOtherOpsLoopInvariant = true; | ||||||||||
5851 | for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); | ||||||||||
5852 | ++OtherOpIndex) { | ||||||||||
5853 | if (OtherOpIndex != OpIndex) { | ||||||||||
5854 | const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); | ||||||||||
5855 | if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { | ||||||||||
5856 | AllOtherOpsLoopInvariant = false; | ||||||||||
5857 | break; | ||||||||||
5858 | } | ||||||||||
5859 | } | ||||||||||
5860 | } | ||||||||||
5861 | if (AllOtherOpsLoopInvariant && | ||||||||||
5862 | isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) | ||||||||||
5863 | return true; | ||||||||||
5864 | } | ||||||||||
5865 | } | ||||||||||
5866 | return false; | ||||||||||
5867 | } | ||||||||||
5868 | |||||||||||
5869 | bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { | ||||||||||
5870 | // If we know that \c I can never be poison period, then that's enough. | ||||||||||
5871 | if (isSCEVExprNeverPoison(I)) | ||||||||||
5872 | return true; | ||||||||||
5873 | |||||||||||
5874 | // For an add recurrence specifically, we assume that infinite loops without | ||||||||||
5875 | // side effects are undefined behavior, and then reason as follows: | ||||||||||
5876 | // | ||||||||||
5877 | // If the add recurrence is poison in any iteration, it is poison on all | ||||||||||
5878 | // future iterations (since incrementing poison yields poison). If the result | ||||||||||
5879 | // of the add recurrence is fed into the loop latch condition and the loop | ||||||||||
5880 | // does not contain any throws or exiting blocks other than the latch, we now | ||||||||||
5881 | // have the ability to "choose" whether the backedge is taken or not (by | ||||||||||
5882 | // choosing a sufficiently evil value for the poison feeding into the branch) | ||||||||||
5883 | // for every iteration including and after the one in which \p I first became | ||||||||||
5884 | // poison. There are two possibilities (let's call the iteration in which \p | ||||||||||
5885 | // I first became poison as K): | ||||||||||
5886 | // | ||||||||||
5887 | // 1. In the set of iterations including and after K, the loop body executes | ||||||||||
5888 | // no side effects. In this case executing the backege an infinte number | ||||||||||
5889 | // of times will yield undefined behavior. | ||||||||||
5890 | // | ||||||||||
5891 | // 2. In the set of iterations including and after K, the loop body executes | ||||||||||
5892 | // at least one side effect. In this case, that specific instance of side | ||||||||||
5893 | // effect is control dependent on poison, which also yields undefined | ||||||||||
5894 | // behavior. | ||||||||||
5895 | |||||||||||
5896 | auto *ExitingBB = L->getExitingBlock(); | ||||||||||
5897 | auto *LatchBB = L->getLoopLatch(); | ||||||||||
5898 | if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) | ||||||||||
5899 | return false; | ||||||||||
5900 | |||||||||||
5901 | SmallPtrSet<const Instruction *, 16> Pushed; | ||||||||||
5902 | SmallVector<const Instruction *, 8> PoisonStack; | ||||||||||
5903 | |||||||||||
5904 | // We start by assuming \c I, the post-inc add recurrence, is poison. Only | ||||||||||
5905 | // things that are known to be poison under that assumption go on the | ||||||||||
5906 | // PoisonStack. | ||||||||||
5907 | Pushed.insert(I); | ||||||||||
5908 | PoisonStack.push_back(I); | ||||||||||
5909 | |||||||||||
5910 | bool LatchControlDependentOnPoison = false; | ||||||||||
5911 | while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { | ||||||||||
5912 | const Instruction *Poison = PoisonStack.pop_back_val(); | ||||||||||
5913 | |||||||||||
5914 | for (auto *PoisonUser : Poison->users()) { | ||||||||||
5915 | if (propagatesPoison(cast<Operator>(PoisonUser))) { | ||||||||||
5916 | if (Pushed.insert(cast<Instruction>(PoisonUser)).second) | ||||||||||
5917 | PoisonStack.push_back(cast<Instruction>(PoisonUser)); | ||||||||||
5918 | } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { | ||||||||||
5919 | assert(BI->isConditional() && "Only possibility!")((BI->isConditional() && "Only possibility!") ? static_cast <void> (0) : __assert_fail ("BI->isConditional() && \"Only possibility!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5919, __PRETTY_FUNCTION__)); | ||||||||||
5920 | if (BI->getParent() == LatchBB) { | ||||||||||
5921 | LatchControlDependentOnPoison = true; | ||||||||||
5922 | break; | ||||||||||
5923 | } | ||||||||||
5924 | } | ||||||||||
5925 | } | ||||||||||
5926 | } | ||||||||||
5927 | |||||||||||
5928 | return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); | ||||||||||
5929 | } | ||||||||||
5930 | |||||||||||
5931 | ScalarEvolution::LoopProperties | ||||||||||
5932 | ScalarEvolution::getLoopProperties(const Loop *L) { | ||||||||||
5933 | using LoopProperties = ScalarEvolution::LoopProperties; | ||||||||||
5934 | |||||||||||
5935 | auto Itr = LoopPropertiesCache.find(L); | ||||||||||
5936 | if (Itr == LoopPropertiesCache.end()) { | ||||||||||
5937 | auto HasSideEffects = [](Instruction *I) { | ||||||||||
5938 | if (auto *SI = dyn_cast<StoreInst>(I)) | ||||||||||
5939 | return !SI->isSimple(); | ||||||||||
5940 | |||||||||||
5941 | return I->mayHaveSideEffects(); | ||||||||||
5942 | }; | ||||||||||
5943 | |||||||||||
5944 | LoopProperties LP = {/* HasNoAbnormalExits */ true, | ||||||||||
5945 | /*HasNoSideEffects*/ true}; | ||||||||||
5946 | |||||||||||
5947 | for (auto *BB : L->getBlocks()) | ||||||||||
5948 | for (auto &I : *BB) { | ||||||||||
5949 | if (!isGuaranteedToTransferExecutionToSuccessor(&I)) | ||||||||||
5950 | LP.HasNoAbnormalExits = false; | ||||||||||
5951 | if (HasSideEffects(&I)) | ||||||||||
5952 | LP.HasNoSideEffects = false; | ||||||||||
5953 | if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) | ||||||||||
5954 | break; // We're already as pessimistic as we can get. | ||||||||||
5955 | } | ||||||||||
5956 | |||||||||||
5957 | auto InsertPair = LoopPropertiesCache.insert({L, LP}); | ||||||||||
5958 | assert(InsertPair.second && "We just checked!")((InsertPair.second && "We just checked!") ? static_cast <void> (0) : __assert_fail ("InsertPair.second && \"We just checked!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 5958, __PRETTY_FUNCTION__)); | ||||||||||
5959 | Itr = InsertPair.first; | ||||||||||
5960 | } | ||||||||||
5961 | |||||||||||
5962 | return Itr->second; | ||||||||||
5963 | } | ||||||||||
5964 | |||||||||||
5965 | const SCEV *ScalarEvolution::createSCEV(Value *V) { | ||||||||||
5966 | if (!isSCEVable(V->getType())) | ||||||||||
| |||||||||||
5967 | return getUnknown(V); | ||||||||||
5968 | |||||||||||
5969 | if (Instruction *I
| ||||||||||
5970 | // Don't attempt to analyze instructions in blocks that aren't | ||||||||||
5971 | // reachable. Such instructions don't matter, and they aren't required | ||||||||||
5972 | // to obey basic rules for definitions dominating uses which this | ||||||||||
5973 | // analysis depends on. | ||||||||||
5974 | if (!DT.isReachableFromEntry(I->getParent())) | ||||||||||
5975 | return getUnknown(UndefValue::get(V->getType())); | ||||||||||
5976 | } else if (ConstantInt *CI
| ||||||||||
5977 | return getConstant(CI); | ||||||||||
5978 | else if (isa<ConstantPointerNull>(V)) | ||||||||||
5979 | return getZero(V->getType()); | ||||||||||
5980 | else if (GlobalAlias *GA
| ||||||||||
5981 | return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); | ||||||||||
5982 | else if (!isa<ConstantExpr>(V)) | ||||||||||
5983 | return getUnknown(V); | ||||||||||
5984 | |||||||||||
5985 | Operator *U = cast<Operator>(V); | ||||||||||
5986 | if (auto BO = MatchBinaryOp(U, DT)) { | ||||||||||
5987 | switch (BO->Opcode) { | ||||||||||
5988 | case Instruction::Add: { | ||||||||||
5989 | // The simple thing to do would be to just call getSCEV on both operands | ||||||||||
5990 | // and call getAddExpr with the result. However if we're looking at a | ||||||||||
5991 | // bunch of things all added together, this can be quite inefficient, | ||||||||||
5992 | // because it leads to N-1 getAddExpr calls for N ultimate operands. | ||||||||||
5993 | // Instead, gather up all the operands and make a single getAddExpr call. | ||||||||||
5994 | // LLVM IR canonical form means we need only traverse the left operands. | ||||||||||
5995 | SmallVector<const SCEV *, 4> AddOps; | ||||||||||
5996 | do { | ||||||||||
5997 | if (BO->Op) { | ||||||||||
5998 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { | ||||||||||
5999 | AddOps.push_back(OpSCEV); | ||||||||||
6000 | break; | ||||||||||
6001 | } | ||||||||||
6002 | |||||||||||
6003 | // If a NUW or NSW flag can be applied to the SCEV for this | ||||||||||
6004 | // addition, then compute the SCEV for this addition by itself | ||||||||||
6005 | // with a separate call to getAddExpr. We need to do that | ||||||||||
6006 | // instead of pushing the operands of the addition onto AddOps, | ||||||||||
6007 | // since the flags are only known to apply to this particular | ||||||||||
6008 | // addition - they may not apply to other additions that can be | ||||||||||
6009 | // formed with operands from AddOps. | ||||||||||
6010 | const SCEV *RHS = getSCEV(BO->RHS); | ||||||||||
6011 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); | ||||||||||
6012 | if (Flags != SCEV::FlagAnyWrap) { | ||||||||||
6013 | const SCEV *LHS = getSCEV(BO->LHS); | ||||||||||
6014 | if (BO->Opcode == Instruction::Sub) | ||||||||||
6015 | AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); | ||||||||||
6016 | else | ||||||||||
6017 | AddOps.push_back(getAddExpr(LHS, RHS, Flags)); | ||||||||||
6018 | break; | ||||||||||
6019 | } | ||||||||||
6020 | } | ||||||||||
6021 | |||||||||||
6022 | if (BO->Opcode == Instruction::Sub) | ||||||||||
6023 | AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); | ||||||||||
6024 | else | ||||||||||
6025 | AddOps.push_back(getSCEV(BO->RHS)); | ||||||||||
6026 | |||||||||||
6027 | auto NewBO = MatchBinaryOp(BO->LHS, DT); | ||||||||||
6028 | if (!NewBO || (NewBO->Opcode != Instruction::Add && | ||||||||||
6029 | NewBO->Opcode != Instruction::Sub)) { | ||||||||||
6030 | AddOps.push_back(getSCEV(BO->LHS)); | ||||||||||
6031 | break; | ||||||||||
6032 | } | ||||||||||
6033 | BO = NewBO; | ||||||||||
6034 | } while (true); | ||||||||||
6035 | |||||||||||
6036 | return getAddExpr(AddOps); | ||||||||||
6037 | } | ||||||||||
6038 | |||||||||||
6039 | case Instruction::Mul: { | ||||||||||
6040 | SmallVector<const SCEV *, 4> MulOps; | ||||||||||
6041 | do { | ||||||||||
6042 | if (BO->Op) { | ||||||||||
6043 | if (auto *OpSCEV = getExistingSCEV(BO->Op)) { | ||||||||||
6044 | MulOps.push_back(OpSCEV); | ||||||||||
6045 | break; | ||||||||||
6046 | } | ||||||||||
6047 | |||||||||||
6048 | SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); | ||||||||||
6049 | if (Flags != SCEV::FlagAnyWrap) { | ||||||||||
6050 | MulOps.push_back( | ||||||||||
6051 | getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); | ||||||||||
6052 | break; | ||||||||||
6053 | } | ||||||||||
6054 | } | ||||||||||
6055 | |||||||||||
6056 | MulOps.push_back(getSCEV(BO->RHS)); | ||||||||||
6057 | auto NewBO = MatchBinaryOp(BO->LHS, DT); | ||||||||||
6058 | if (!NewBO || NewBO->Opcode != Instruction::Mul) { | ||||||||||
6059 | MulOps.push_back(getSCEV(BO->LHS)); | ||||||||||
6060 | break; | ||||||||||
6061 | } | ||||||||||
6062 | BO = NewBO; | ||||||||||
6063 | } while (true); | ||||||||||
6064 | |||||||||||
6065 | return getMulExpr(MulOps); | ||||||||||
6066 | } | ||||||||||
6067 | case Instruction::UDiv: | ||||||||||
6068 | return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); | ||||||||||
6069 | case Instruction::URem: | ||||||||||
6070 | return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); | ||||||||||
6071 | case Instruction::Sub: { | ||||||||||
6072 | SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; | ||||||||||
6073 | if (BO->Op) | ||||||||||
6074 | Flags = getNoWrapFlagsFromUB(BO->Op); | ||||||||||
6075 | return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); | ||||||||||
6076 | } | ||||||||||
6077 | case Instruction::And: | ||||||||||
6078 | // For an expression like x&255 that merely masks off the high bits, | ||||||||||
6079 | // use zext(trunc(x)) as the SCEV expression. | ||||||||||
6080 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { | ||||||||||
6081 | if (CI->isZero()) | ||||||||||
6082 | return getSCEV(BO->RHS); | ||||||||||
6083 | if (CI->isMinusOne()) | ||||||||||
6084 | return getSCEV(BO->LHS); | ||||||||||
6085 | const APInt &A = CI->getValue(); | ||||||||||
6086 | |||||||||||
6087 | // Instcombine's ShrinkDemandedConstant may strip bits out of | ||||||||||
6088 | // constants, obscuring what would otherwise be a low-bits mask. | ||||||||||
6089 | // Use computeKnownBits to compute what ShrinkDemandedConstant | ||||||||||
6090 | // knew about to reconstruct a low-bits mask value. | ||||||||||
6091 | unsigned LZ = A.countLeadingZeros(); | ||||||||||
6092 | unsigned TZ = A.countTrailingZeros(); | ||||||||||
6093 | unsigned BitWidth = A.getBitWidth(); | ||||||||||
6094 | KnownBits Known(BitWidth); | ||||||||||
6095 | computeKnownBits(BO->LHS, Known, getDataLayout(), | ||||||||||
6096 | 0, &AC, nullptr, &DT); | ||||||||||
6097 | |||||||||||
6098 | APInt EffectiveMask = | ||||||||||
6099 | APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); | ||||||||||
6100 | if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { | ||||||||||
6101 | const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); | ||||||||||
6102 | const SCEV *LHS = getSCEV(BO->LHS); | ||||||||||
6103 | const SCEV *ShiftedLHS = nullptr; | ||||||||||
6104 | if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { | ||||||||||
6105 | if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { | ||||||||||
6106 | // For an expression like (x * 8) & 8, simplify the multiply. | ||||||||||
6107 | unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); | ||||||||||
6108 | unsigned GCD = std::min(MulZeros, TZ); | ||||||||||
6109 | APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); | ||||||||||
6110 | SmallVector<const SCEV*, 4> MulOps; | ||||||||||
6111 | MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); | ||||||||||
6112 | MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); | ||||||||||
6113 | auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); | ||||||||||
6114 | ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); | ||||||||||
6115 | } | ||||||||||
6116 | } | ||||||||||
6117 | if (!ShiftedLHS) | ||||||||||
6118 | ShiftedLHS = getUDivExpr(LHS, MulCount); | ||||||||||
6119 | return getMulExpr( | ||||||||||
6120 | getZeroExtendExpr( | ||||||||||
6121 | getTruncateExpr(ShiftedLHS, | ||||||||||
6122 | IntegerType::get(getContext(), BitWidth - LZ - TZ)), | ||||||||||
6123 | BO->LHS->getType()), | ||||||||||
6124 | MulCount); | ||||||||||
6125 | } | ||||||||||
6126 | } | ||||||||||
6127 | break; | ||||||||||
6128 | |||||||||||
6129 | case Instruction::Or: | ||||||||||
6130 | // If the RHS of the Or is a constant, we may have something like: | ||||||||||
6131 | // X*4+1 which got turned into X*4|1. Handle this as an Add so loop | ||||||||||
6132 | // optimizations will transparently handle this case. | ||||||||||
6133 | // | ||||||||||
6134 | // In order for this transformation to be safe, the LHS must be of the | ||||||||||
6135 | // form X*(2^n) and the Or constant must be less than 2^n. | ||||||||||
6136 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { | ||||||||||
6137 | const SCEV *LHS = getSCEV(BO->LHS); | ||||||||||
6138 | const APInt &CIVal = CI->getValue(); | ||||||||||
6139 | if (GetMinTrailingZeros(LHS) >= | ||||||||||
6140 | (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { | ||||||||||
6141 | // Build a plain add SCEV. | ||||||||||
6142 | return getAddExpr(LHS, getSCEV(CI), | ||||||||||
6143 | (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); | ||||||||||
6144 | } | ||||||||||
6145 | } | ||||||||||
6146 | break; | ||||||||||
6147 | |||||||||||
6148 | case Instruction::Xor: | ||||||||||
6149 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { | ||||||||||
6150 | // If the RHS of xor is -1, then this is a not operation. | ||||||||||
6151 | if (CI->isMinusOne()) | ||||||||||
6152 | return getNotSCEV(getSCEV(BO->LHS)); | ||||||||||
6153 | |||||||||||
6154 | // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. | ||||||||||
6155 | // This is a variant of the check for xor with -1, and it handles | ||||||||||
6156 | // the case where instcombine has trimmed non-demanded bits out | ||||||||||
6157 | // of an xor with -1. | ||||||||||
6158 | if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) | ||||||||||
6159 | if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) | ||||||||||
6160 | if (LBO->getOpcode() == Instruction::And && | ||||||||||
6161 | LCI->getValue() == CI->getValue()) | ||||||||||
6162 | if (const SCEVZeroExtendExpr *Z
| ||||||||||
6163 | dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { | ||||||||||
6164 | Type *UTy = BO->LHS->getType(); | ||||||||||
| |||||||||||
6165 | const SCEV *Z0 = Z->getOperand(); | ||||||||||
6166 | Type *Z0Ty = Z0->getType(); | ||||||||||
6167 | unsigned Z0TySize = getTypeSizeInBits(Z0Ty); | ||||||||||
6168 | |||||||||||
6169 | // If C is a low-bits mask, the zero extend is serving to | ||||||||||
6170 | // mask off the high bits. Complement the operand and | ||||||||||
6171 | // re-apply the zext. | ||||||||||
6172 | if (CI->getValue().isMask(Z0TySize)) | ||||||||||
6173 | return getZeroExtendExpr(getNotSCEV(Z0), UTy); | ||||||||||
6174 | |||||||||||
6175 | // If C is a single bit, it may be in the sign-bit position | ||||||||||
6176 | // before the zero-extend. In this case, represent the xor | ||||||||||
6177 | // using an add, which is equivalent, and re-apply the zext. | ||||||||||
6178 | APInt Trunc = CI->getValue().trunc(Z0TySize); | ||||||||||
6179 | if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && | ||||||||||
6180 | Trunc.isSignMask()) | ||||||||||
6181 | return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), | ||||||||||
6182 | UTy); | ||||||||||
6183 | } | ||||||||||
6184 | } | ||||||||||
6185 | break; | ||||||||||
6186 | |||||||||||
6187 | case Instruction::Shl: | ||||||||||
6188 | // Turn shift left of a constant amount into a multiply. | ||||||||||
6189 | if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { | ||||||||||
6190 | uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); | ||||||||||
6191 | |||||||||||
6192 | // If the shift count is not less than the bitwidth, the result of | ||||||||||
6193 | // the shift is undefined. Don't try to analyze it, because the | ||||||||||
6194 | // resolution chosen here may differ from the resolution chosen in | ||||||||||
6195 | // other parts of the compiler. | ||||||||||
6196 | if (SA->getValue().uge(BitWidth)) | ||||||||||
6197 | break; | ||||||||||
6198 | |||||||||||
6199 | // We can safely preserve the nuw flag in all cases. It's also safe to | ||||||||||
6200 | // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation | ||||||||||
6201 | // requires special handling. It can be preserved as long as we're not | ||||||||||
6202 | // left shifting by bitwidth - 1. | ||||||||||
6203 | auto Flags = SCEV::FlagAnyWrap; | ||||||||||
6204 | if (BO->Op) { | ||||||||||
6205 | auto MulFlags = getNoWrapFlagsFromUB(BO->Op); | ||||||||||
6206 | if ((MulFlags & SCEV::FlagNSW) && | ||||||||||
6207 | ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) | ||||||||||
6208 | Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); | ||||||||||
6209 | if (MulFlags & SCEV::FlagNUW) | ||||||||||
6210 | Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); | ||||||||||
6211 | } | ||||||||||
6212 | |||||||||||
6213 | Constant *X = ConstantInt::get( | ||||||||||
6214 | getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); | ||||||||||
6215 | return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); | ||||||||||
6216 | } | ||||||||||
6217 | break; | ||||||||||
6218 | |||||||||||
6219 | case Instruction::AShr: { | ||||||||||
6220 | // AShr X, C, where C is a constant. | ||||||||||
6221 | ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); | ||||||||||
6222 | if (!CI) | ||||||||||
6223 | break; | ||||||||||
6224 | |||||||||||
6225 | Type *OuterTy = BO->LHS->getType(); | ||||||||||
6226 | uint64_t BitWidth = getTypeSizeInBits(OuterTy); | ||||||||||
6227 | // If the shift count is not less than the bitwidth, the result of | ||||||||||
6228 | // the shift is undefined. Don't try to analyze it, because the | ||||||||||
6229 | // resolution chosen here may differ from the resolution chosen in | ||||||||||
6230 | // other parts of the compiler. | ||||||||||
6231 | if (CI->getValue().uge(BitWidth)) | ||||||||||
6232 | break; | ||||||||||
6233 | |||||||||||
6234 | if (CI->isZero()) | ||||||||||
6235 | return getSCEV(BO->LHS); // shift by zero --> noop | ||||||||||
6236 | |||||||||||
6237 | uint64_t AShrAmt = CI->getZExtValue(); | ||||||||||
6238 | Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); | ||||||||||
6239 | |||||||||||
6240 | Operator *L = dyn_cast<Operator>(BO->LHS); | ||||||||||
6241 | if (L && L->getOpcode() == Instruction::Shl) { | ||||||||||
6242 | // X = Shl A, n | ||||||||||
6243 | // Y = AShr X, m | ||||||||||
6244 | // Both n and m are constant. | ||||||||||
6245 | |||||||||||
6246 | const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); | ||||||||||
6247 | if (L->getOperand(1) == BO->RHS) | ||||||||||
6248 | // For a two-shift sext-inreg, i.e. n = m, | ||||||||||
6249 | // use sext(trunc(x)) as the SCEV expression. | ||||||||||
6250 | return getSignExtendExpr( | ||||||||||
6251 | getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); | ||||||||||
6252 | |||||||||||
6253 | ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); | ||||||||||
6254 | if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { | ||||||||||
6255 | uint64_t ShlAmt = ShlAmtCI->getZExtValue(); | ||||||||||
6256 | if (ShlAmt > AShrAmt) { | ||||||||||
6257 | // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV | ||||||||||
6258 | // expression. We already checked that ShlAmt < BitWidth, so | ||||||||||
6259 | // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as | ||||||||||
6260 | // ShlAmt - AShrAmt < Amt. | ||||||||||
6261 | APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, | ||||||||||
6262 | ShlAmt - AShrAmt); | ||||||||||
6263 | return getSignExtendExpr( | ||||||||||
6264 | getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), | ||||||||||
6265 | getConstant(Mul)), OuterTy); | ||||||||||
6266 | } | ||||||||||
6267 | } | ||||||||||
6268 | } | ||||||||||
6269 | break; | ||||||||||
6270 | } | ||||||||||
6271 | } | ||||||||||
6272 | } | ||||||||||
6273 | |||||||||||
6274 | switch (U->getOpcode()) { | ||||||||||
6275 | case Instruction::Trunc: | ||||||||||
6276 | return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); | ||||||||||
6277 | |||||||||||
6278 | case Instruction::ZExt: | ||||||||||
6279 | return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); | ||||||||||
6280 | |||||||||||
6281 | case Instruction::SExt: | ||||||||||
6282 | if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { | ||||||||||
6283 | // The NSW flag of a subtract does not always survive the conversion to | ||||||||||
6284 | // A + (-1)*B. By pushing sign extension onto its operands we are much | ||||||||||
6285 | // more likely to preserve NSW and allow later AddRec optimisations. | ||||||||||
6286 | // | ||||||||||
6287 | // NOTE: This is effectively duplicating this logic from getSignExtend: | ||||||||||
6288 | // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> | ||||||||||
6289 | // but by that point the NSW information has potentially been lost. | ||||||||||
6290 | if (BO->Opcode == Instruction::Sub && BO->IsNSW) { | ||||||||||
6291 | Type *Ty = U->getType(); | ||||||||||
6292 | auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); | ||||||||||
6293 | auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); | ||||||||||
6294 | return getMinusSCEV(V1, V2, SCEV::FlagNSW); | ||||||||||
6295 | } | ||||||||||
6296 | } | ||||||||||
6297 | return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); | ||||||||||
6298 | |||||||||||
6299 | case Instruction::BitCast: | ||||||||||
6300 | // BitCasts are no-op casts so we just eliminate the cast. | ||||||||||
6301 | if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) | ||||||||||
6302 | return getSCEV(U->getOperand(0)); | ||||||||||
6303 | break; | ||||||||||
6304 | |||||||||||
6305 | case Instruction::SDiv: | ||||||||||
6306 | // If both operands are non-negative, this is just an udiv. | ||||||||||
6307 | if (isKnownNonNegative(getSCEV(U->getOperand(0))) && | ||||||||||
6308 | isKnownNonNegative(getSCEV(U->getOperand(1)))) | ||||||||||
6309 | return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); | ||||||||||
6310 | break; | ||||||||||
6311 | |||||||||||
6312 | case Instruction::SRem: | ||||||||||
6313 | // If both operands are non-negative, this is just an urem. | ||||||||||
6314 | if (isKnownNonNegative(getSCEV(U->getOperand(0))) && | ||||||||||
6315 | isKnownNonNegative(getSCEV(U->getOperand(1)))) | ||||||||||
6316 | return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); | ||||||||||
6317 | break; | ||||||||||
6318 | |||||||||||
6319 | // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can | ||||||||||
6320 | // lead to pointer expressions which cannot safely be expanded to GEPs, | ||||||||||
6321 | // because ScalarEvolution doesn't respect the GEP aliasing rules when | ||||||||||
6322 | // simplifying integer expressions. | ||||||||||
6323 | |||||||||||
6324 | case Instruction::GetElementPtr: | ||||||||||
6325 | return createNodeForGEP(cast<GEPOperator>(U)); | ||||||||||
6326 | |||||||||||
6327 | case Instruction::PHI: | ||||||||||
6328 | return createNodeForPHI(cast<PHINode>(U)); | ||||||||||
6329 | |||||||||||
6330 | case Instruction::Select: | ||||||||||
6331 | // U can also be a select constant expr, which let fall through. Since | ||||||||||
6332 | // createNodeForSelect only works for a condition that is an `ICmpInst`, and | ||||||||||
6333 | // constant expressions cannot have instructions as operands, we'd have | ||||||||||
6334 | // returned getUnknown for a select constant expressions anyway. | ||||||||||
6335 | if (isa<Instruction>(U)) | ||||||||||
6336 | return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), | ||||||||||
6337 | U->getOperand(1), U->getOperand(2)); | ||||||||||
6338 | break; | ||||||||||
6339 | |||||||||||
6340 | case Instruction::Call: | ||||||||||
6341 | case Instruction::Invoke: | ||||||||||
6342 | if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) | ||||||||||
6343 | return getSCEV(RV); | ||||||||||
6344 | |||||||||||
6345 | if (auto *II = dyn_cast<IntrinsicInst>(U)) { | ||||||||||
6346 | switch (II->getIntrinsicID()) { | ||||||||||
6347 | case Intrinsic::umax: | ||||||||||
6348 | return getUMaxExpr(getSCEV(II->getArgOperand(0)), | ||||||||||
6349 | getSCEV(II->getArgOperand(1))); | ||||||||||
6350 | case Intrinsic::umin: | ||||||||||
6351 | return getUMinExpr(getSCEV(II->getArgOperand(0)), | ||||||||||
6352 | getSCEV(II->getArgOperand(1))); | ||||||||||
6353 | case Intrinsic::smax: | ||||||||||
6354 | return getSMaxExpr(getSCEV(II->getArgOperand(0)), | ||||||||||
6355 | getSCEV(II->getArgOperand(1))); | ||||||||||
6356 | case Intrinsic::smin: | ||||||||||
6357 | return getSMinExpr(getSCEV(II->getArgOperand(0)), | ||||||||||
6358 | getSCEV(II->getArgOperand(1))); | ||||||||||
6359 | default: | ||||||||||
6360 | break; | ||||||||||
6361 | } | ||||||||||
6362 | } | ||||||||||
6363 | break; | ||||||||||
6364 | } | ||||||||||
6365 | |||||||||||
6366 | return getUnknown(V); | ||||||||||
6367 | } | ||||||||||
6368 | |||||||||||
6369 | //===----------------------------------------------------------------------===// | ||||||||||
6370 | // Iteration Count Computation Code | ||||||||||
6371 | // | ||||||||||
6372 | |||||||||||
6373 | static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { | ||||||||||
6374 | if (!ExitCount) | ||||||||||
6375 | return 0; | ||||||||||
6376 | |||||||||||
6377 | ConstantInt *ExitConst = ExitCount->getValue(); | ||||||||||
6378 | |||||||||||
6379 | // Guard against huge trip counts. | ||||||||||
6380 | if (ExitConst->getValue().getActiveBits() > 32) | ||||||||||
6381 | return 0; | ||||||||||
6382 | |||||||||||
6383 | // In case of integer overflow, this returns 0, which is correct. | ||||||||||
6384 | return ((unsigned)ExitConst->getZExtValue()) + 1; | ||||||||||
6385 | } | ||||||||||
6386 | |||||||||||
6387 | unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { | ||||||||||
6388 | if (BasicBlock *ExitingBB = L->getExitingBlock()) | ||||||||||
6389 | return getSmallConstantTripCount(L, ExitingBB); | ||||||||||
6390 | |||||||||||
6391 | // No trip count information for multiple exits. | ||||||||||
6392 | return 0; | ||||||||||
6393 | } | ||||||||||
6394 | |||||||||||
6395 | unsigned | ||||||||||
6396 | ScalarEvolution::getSmallConstantTripCount(const Loop *L, | ||||||||||
6397 | const BasicBlock *ExitingBlock) { | ||||||||||
6398 | assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!" ) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6398, __PRETTY_FUNCTION__)); | ||||||||||
6399 | assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6400, __PRETTY_FUNCTION__)) | ||||||||||
6400 | "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6400, __PRETTY_FUNCTION__)); | ||||||||||
6401 | const SCEVConstant *ExitCount = | ||||||||||
6402 | dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); | ||||||||||
6403 | return getConstantTripCount(ExitCount); | ||||||||||
6404 | } | ||||||||||
6405 | |||||||||||
6406 | unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { | ||||||||||
6407 | const auto *MaxExitCount = | ||||||||||
6408 | dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); | ||||||||||
6409 | return getConstantTripCount(MaxExitCount); | ||||||||||
6410 | } | ||||||||||
6411 | |||||||||||
6412 | unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { | ||||||||||
6413 | if (BasicBlock *ExitingBB = L->getExitingBlock()) | ||||||||||
6414 | return getSmallConstantTripMultiple(L, ExitingBB); | ||||||||||
6415 | |||||||||||
6416 | // No trip multiple information for multiple exits. | ||||||||||
6417 | return 0; | ||||||||||
6418 | } | ||||||||||
6419 | |||||||||||
6420 | /// Returns the largest constant divisor of the trip count of this loop as a | ||||||||||
6421 | /// normal unsigned value, if possible. This means that the actual trip count is | ||||||||||
6422 | /// always a multiple of the returned value (don't forget the trip count could | ||||||||||
6423 | /// very well be zero as well!). | ||||||||||
6424 | /// | ||||||||||
6425 | /// Returns 1 if the trip count is unknown or not guaranteed to be the | ||||||||||
6426 | /// multiple of a constant (which is also the case if the trip count is simply | ||||||||||
6427 | /// constant, use getSmallConstantTripCount for that case), Will also return 1 | ||||||||||
6428 | /// if the trip count is very large (>= 2^32). | ||||||||||
6429 | /// | ||||||||||
6430 | /// As explained in the comments for getSmallConstantTripCount, this assumes | ||||||||||
6431 | /// that control exits the loop via ExitingBlock. | ||||||||||
6432 | unsigned | ||||||||||
6433 | ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, | ||||||||||
6434 | const BasicBlock *ExitingBlock) { | ||||||||||
6435 | assert(ExitingBlock && "Must pass a non-null exiting block!")((ExitingBlock && "Must pass a non-null exiting block!" ) ? static_cast<void> (0) : __assert_fail ("ExitingBlock && \"Must pass a non-null exiting block!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6435, __PRETTY_FUNCTION__)); | ||||||||||
6436 | assert(L->isLoopExiting(ExitingBlock) &&((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6437, __PRETTY_FUNCTION__)) | ||||||||||
6437 | "Exiting block must actually branch out of the loop!")((L->isLoopExiting(ExitingBlock) && "Exiting block must actually branch out of the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Exiting block must actually branch out of the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6437, __PRETTY_FUNCTION__)); | ||||||||||
6438 | const SCEV *ExitCount = getExitCount(L, ExitingBlock); | ||||||||||
6439 | if (ExitCount == getCouldNotCompute()) | ||||||||||
6440 | return 1; | ||||||||||
6441 | |||||||||||
6442 | // Get the trip count from the BE count by adding 1. | ||||||||||
6443 | const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); | ||||||||||
6444 | |||||||||||
6445 | const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); | ||||||||||
6446 | if (!TC) | ||||||||||
6447 | // Attempt to factor more general cases. Returns the greatest power of | ||||||||||
6448 | // two divisor. If overflow happens, the trip count expression is still | ||||||||||
6449 | // divisible by the greatest power of 2 divisor returned. | ||||||||||
6450 | return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); | ||||||||||
6451 | |||||||||||
6452 | ConstantInt *Result = TC->getValue(); | ||||||||||
6453 | |||||||||||
6454 | // Guard against huge trip counts (this requires checking | ||||||||||
6455 | // for zero to handle the case where the trip count == -1 and the | ||||||||||
6456 | // addition wraps). | ||||||||||
6457 | if (!Result || Result->getValue().getActiveBits() > 32 || | ||||||||||
6458 | Result->getValue().getActiveBits() == 0) | ||||||||||
6459 | return 1; | ||||||||||
6460 | |||||||||||
6461 | return (unsigned)Result->getZExtValue(); | ||||||||||
6462 | } | ||||||||||
6463 | |||||||||||
6464 | const SCEV *ScalarEvolution::getExitCount(const Loop *L, | ||||||||||
6465 | const BasicBlock *ExitingBlock, | ||||||||||
6466 | ExitCountKind Kind) { | ||||||||||
6467 | switch (Kind) { | ||||||||||
6468 | case Exact: | ||||||||||
6469 | return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); | ||||||||||
6470 | case ConstantMaximum: | ||||||||||
6471 | return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); | ||||||||||
6472 | }; | ||||||||||
6473 | llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6473); | ||||||||||
6474 | } | ||||||||||
6475 | |||||||||||
6476 | const SCEV * | ||||||||||
6477 | ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, | ||||||||||
6478 | SCEVUnionPredicate &Preds) { | ||||||||||
6479 | return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); | ||||||||||
6480 | } | ||||||||||
6481 | |||||||||||
6482 | const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, | ||||||||||
6483 | ExitCountKind Kind) { | ||||||||||
6484 | switch (Kind) { | ||||||||||
6485 | case Exact: | ||||||||||
6486 | return getBackedgeTakenInfo(L).getExact(L, this); | ||||||||||
6487 | case ConstantMaximum: | ||||||||||
6488 | return getBackedgeTakenInfo(L).getMax(this); | ||||||||||
6489 | }; | ||||||||||
6490 | llvm_unreachable("Invalid ExitCountKind!")::llvm::llvm_unreachable_internal("Invalid ExitCountKind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6490); | ||||||||||
6491 | } | ||||||||||
6492 | |||||||||||
6493 | bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { | ||||||||||
6494 | return getBackedgeTakenInfo(L).isMaxOrZero(this); | ||||||||||
6495 | } | ||||||||||
6496 | |||||||||||
6497 | /// Push PHI nodes in the header of the given loop onto the given Worklist. | ||||||||||
6498 | static void | ||||||||||
6499 | PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { | ||||||||||
6500 | BasicBlock *Header = L->getHeader(); | ||||||||||
6501 | |||||||||||
6502 | // Push all Loop-header PHIs onto the Worklist stack. | ||||||||||
6503 | for (PHINode &PN : Header->phis()) | ||||||||||
6504 | Worklist.push_back(&PN); | ||||||||||
6505 | } | ||||||||||
6506 | |||||||||||
6507 | const ScalarEvolution::BackedgeTakenInfo & | ||||||||||
6508 | ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { | ||||||||||
6509 | auto &BTI = getBackedgeTakenInfo(L); | ||||||||||
6510 | if (BTI.hasFullInfo()) | ||||||||||
6511 | return BTI; | ||||||||||
6512 | |||||||||||
6513 | auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); | ||||||||||
6514 | |||||||||||
6515 | if (!Pair.second) | ||||||||||
6516 | return Pair.first->second; | ||||||||||
6517 | |||||||||||
6518 | BackedgeTakenInfo Result = | ||||||||||
6519 | computeBackedgeTakenCount(L, /*AllowPredicates=*/true); | ||||||||||
6520 | |||||||||||
6521 | return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); | ||||||||||
6522 | } | ||||||||||
6523 | |||||||||||
6524 | const ScalarEvolution::BackedgeTakenInfo & | ||||||||||
6525 | ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { | ||||||||||
6526 | // Initially insert an invalid entry for this loop. If the insertion | ||||||||||
6527 | // succeeds, proceed to actually compute a backedge-taken count and | ||||||||||
6528 | // update the value. The temporary CouldNotCompute value tells SCEV | ||||||||||
6529 | // code elsewhere that it shouldn't attempt to request a new | ||||||||||
6530 | // backedge-taken count, which could result in infinite recursion. | ||||||||||
6531 | std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = | ||||||||||
6532 | BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); | ||||||||||
6533 | if (!Pair.second) | ||||||||||
6534 | return Pair.first->second; | ||||||||||
6535 | |||||||||||
6536 | // computeBackedgeTakenCount may allocate memory for its result. Inserting it | ||||||||||
6537 | // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result | ||||||||||
6538 | // must be cleared in this scope. | ||||||||||
6539 | BackedgeTakenInfo Result = computeBackedgeTakenCount(L); | ||||||||||
6540 | |||||||||||
6541 | // In product build, there are no usage of statistic. | ||||||||||
6542 | (void)NumTripCountsComputed; | ||||||||||
6543 | (void)NumTripCountsNotComputed; | ||||||||||
6544 | #if LLVM_ENABLE_STATS1 || !defined(NDEBUG) | ||||||||||
6545 | const SCEV *BEExact = Result.getExact(L, this); | ||||||||||
6546 | if (BEExact != getCouldNotCompute()) { | ||||||||||
6547 | assert(isLoopInvariant(BEExact, L) &&((isLoopInvariant(BEExact, L) && isLoopInvariant(Result .getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!" ) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6549, __PRETTY_FUNCTION__)) | ||||||||||
6548 | isLoopInvariant(Result.getMax(this), L) &&((isLoopInvariant(BEExact, L) && isLoopInvariant(Result .getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!" ) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6549, __PRETTY_FUNCTION__)) | ||||||||||
6549 | "Computed backedge-taken count isn't loop invariant for loop!")((isLoopInvariant(BEExact, L) && isLoopInvariant(Result .getMax(this), L) && "Computed backedge-taken count isn't loop invariant for loop!" ) ? static_cast<void> (0) : __assert_fail ("isLoopInvariant(BEExact, L) && isLoopInvariant(Result.getMax(this), L) && \"Computed backedge-taken count isn't loop invariant for loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6549, __PRETTY_FUNCTION__)); | ||||||||||
6550 | ++NumTripCountsComputed; | ||||||||||
6551 | } | ||||||||||
6552 | else if (Result.getMax(this) == getCouldNotCompute() && | ||||||||||
6553 | isa<PHINode>(L->getHeader()->begin())) { | ||||||||||
6554 | // Only count loops that have phi nodes as not being computable. | ||||||||||
6555 | ++NumTripCountsNotComputed; | ||||||||||
6556 | } | ||||||||||
6557 | #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) | ||||||||||
6558 | |||||||||||
6559 | // Now that we know more about the trip count for this loop, forget any | ||||||||||
6560 | // existing SCEV values for PHI nodes in this loop since they are only | ||||||||||
6561 | // conservative estimates made without the benefit of trip count | ||||||||||
6562 | // information. This is similar to the code in forgetLoop, except that | ||||||||||
6563 | // it handles SCEVUnknown PHI nodes specially. | ||||||||||
6564 | if (Result.hasAnyInfo()) { | ||||||||||
6565 | SmallVector<Instruction *, 16> Worklist; | ||||||||||
6566 | PushLoopPHIs(L, Worklist); | ||||||||||
6567 | |||||||||||
6568 | SmallPtrSet<Instruction *, 8> Discovered; | ||||||||||
6569 | while (!Worklist.empty()) { | ||||||||||
6570 | Instruction *I = Worklist.pop_back_val(); | ||||||||||
6571 | |||||||||||
6572 | ValueExprMapType::iterator It = | ||||||||||
6573 | ValueExprMap.find_as(static_cast<Value *>(I)); | ||||||||||
6574 | if (It != ValueExprMap.end()) { | ||||||||||
6575 | const SCEV *Old = It->second; | ||||||||||
6576 | |||||||||||
6577 | // SCEVUnknown for a PHI either means that it has an unrecognized | ||||||||||
6578 | // structure, or it's a PHI that's in the progress of being computed | ||||||||||
6579 | // by createNodeForPHI. In the former case, additional loop trip | ||||||||||
6580 | // count information isn't going to change anything. In the later | ||||||||||
6581 | // case, createNodeForPHI will perform the necessary updates on its | ||||||||||
6582 | // own when it gets to that point. | ||||||||||
6583 | if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { | ||||||||||
6584 | eraseValueFromMap(It->first); | ||||||||||
6585 | forgetMemoizedResults(Old); | ||||||||||
6586 | } | ||||||||||
6587 | if (PHINode *PN = dyn_cast<PHINode>(I)) | ||||||||||
6588 | ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
6589 | } | ||||||||||
6590 | |||||||||||
6591 | // Since we don't need to invalidate anything for correctness and we're | ||||||||||
6592 | // only invalidating to make SCEV's results more precise, we get to stop | ||||||||||
6593 | // early to avoid invalidating too much. This is especially important in | ||||||||||
6594 | // cases like: | ||||||||||
6595 | // | ||||||||||
6596 | // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node | ||||||||||
6597 | // loop0: | ||||||||||
6598 | // %pn0 = phi | ||||||||||
6599 | // ... | ||||||||||
6600 | // loop1: | ||||||||||
6601 | // %pn1 = phi | ||||||||||
6602 | // ... | ||||||||||
6603 | // | ||||||||||
6604 | // where both loop0 and loop1's backedge taken count uses the SCEV | ||||||||||
6605 | // expression for %v. If we don't have the early stop below then in cases | ||||||||||
6606 | // like the above, getBackedgeTakenInfo(loop1) will clear out the trip | ||||||||||
6607 | // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip | ||||||||||
6608 | // count for loop1, effectively nullifying SCEV's trip count cache. | ||||||||||
6609 | for (auto *U : I->users()) | ||||||||||
6610 | if (auto *I = dyn_cast<Instruction>(U)) { | ||||||||||
6611 | auto *LoopForUser = LI.getLoopFor(I->getParent()); | ||||||||||
6612 | if (LoopForUser && L->contains(LoopForUser) && | ||||||||||
6613 | Discovered.insert(I).second) | ||||||||||
6614 | Worklist.push_back(I); | ||||||||||
6615 | } | ||||||||||
6616 | } | ||||||||||
6617 | } | ||||||||||
6618 | |||||||||||
6619 | // Re-lookup the insert position, since the call to | ||||||||||
6620 | // computeBackedgeTakenCount above could result in a | ||||||||||
6621 | // recusive call to getBackedgeTakenInfo (on a different | ||||||||||
6622 | // loop), which would invalidate the iterator computed | ||||||||||
6623 | // earlier. | ||||||||||
6624 | return BackedgeTakenCounts.find(L)->second = std::move(Result); | ||||||||||
6625 | } | ||||||||||
6626 | |||||||||||
6627 | void ScalarEvolution::forgetAllLoops() { | ||||||||||
6628 | // This method is intended to forget all info about loops. It should | ||||||||||
6629 | // invalidate caches as if the following happened: | ||||||||||
6630 | // - The trip counts of all loops have changed arbitrarily | ||||||||||
6631 | // - Every llvm::Value has been updated in place to produce a different | ||||||||||
6632 | // result. | ||||||||||
6633 | BackedgeTakenCounts.clear(); | ||||||||||
6634 | PredicatedBackedgeTakenCounts.clear(); | ||||||||||
6635 | LoopPropertiesCache.clear(); | ||||||||||
6636 | ConstantEvolutionLoopExitValue.clear(); | ||||||||||
6637 | ValueExprMap.clear(); | ||||||||||
6638 | ValuesAtScopes.clear(); | ||||||||||
6639 | LoopDispositions.clear(); | ||||||||||
6640 | BlockDispositions.clear(); | ||||||||||
6641 | UnsignedRanges.clear(); | ||||||||||
6642 | SignedRanges.clear(); | ||||||||||
6643 | ExprValueMap.clear(); | ||||||||||
6644 | HasRecMap.clear(); | ||||||||||
6645 | MinTrailingZerosCache.clear(); | ||||||||||
6646 | PredicatedSCEVRewrites.clear(); | ||||||||||
6647 | } | ||||||||||
6648 | |||||||||||
6649 | void ScalarEvolution::forgetLoop(const Loop *L) { | ||||||||||
6650 | // Drop any stored trip count value. | ||||||||||
6651 | auto RemoveLoopFromBackedgeMap = | ||||||||||
6652 | [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { | ||||||||||
6653 | auto BTCPos = Map.find(L); | ||||||||||
6654 | if (BTCPos != Map.end()) { | ||||||||||
6655 | BTCPos->second.clear(); | ||||||||||
6656 | Map.erase(BTCPos); | ||||||||||
6657 | } | ||||||||||
6658 | }; | ||||||||||
6659 | |||||||||||
6660 | SmallVector<const Loop *, 16> LoopWorklist(1, L); | ||||||||||
6661 | SmallVector<Instruction *, 32> Worklist; | ||||||||||
6662 | SmallPtrSet<Instruction *, 16> Visited; | ||||||||||
6663 | |||||||||||
6664 | // Iterate over all the loops and sub-loops to drop SCEV information. | ||||||||||
6665 | while (!LoopWorklist.empty()) { | ||||||||||
6666 | auto *CurrL = LoopWorklist.pop_back_val(); | ||||||||||
6667 | |||||||||||
6668 | RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); | ||||||||||
6669 | RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); | ||||||||||
6670 | |||||||||||
6671 | // Drop information about predicated SCEV rewrites for this loop. | ||||||||||
6672 | for (auto I = PredicatedSCEVRewrites.begin(); | ||||||||||
6673 | I != PredicatedSCEVRewrites.end();) { | ||||||||||
6674 | std::pair<const SCEV *, const Loop *> Entry = I->first; | ||||||||||
6675 | if (Entry.second == CurrL) | ||||||||||
6676 | PredicatedSCEVRewrites.erase(I++); | ||||||||||
6677 | else | ||||||||||
6678 | ++I; | ||||||||||
6679 | } | ||||||||||
6680 | |||||||||||
6681 | auto LoopUsersItr = LoopUsers.find(CurrL); | ||||||||||
6682 | if (LoopUsersItr != LoopUsers.end()) { | ||||||||||
6683 | for (auto *S : LoopUsersItr->second) | ||||||||||
6684 | forgetMemoizedResults(S); | ||||||||||
6685 | LoopUsers.erase(LoopUsersItr); | ||||||||||
6686 | } | ||||||||||
6687 | |||||||||||
6688 | // Drop information about expressions based on loop-header PHIs. | ||||||||||
6689 | PushLoopPHIs(CurrL, Worklist); | ||||||||||
6690 | |||||||||||
6691 | while (!Worklist.empty()) { | ||||||||||
6692 | Instruction *I = Worklist.pop_back_val(); | ||||||||||
6693 | if (!Visited.insert(I).second) | ||||||||||
6694 | continue; | ||||||||||
6695 | |||||||||||
6696 | ValueExprMapType::iterator It = | ||||||||||
6697 | ValueExprMap.find_as(static_cast<Value *>(I)); | ||||||||||
6698 | if (It != ValueExprMap.end()) { | ||||||||||
6699 | eraseValueFromMap(It->first); | ||||||||||
6700 | forgetMemoizedResults(It->second); | ||||||||||
6701 | if (PHINode *PN = dyn_cast<PHINode>(I)) | ||||||||||
6702 | ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
6703 | } | ||||||||||
6704 | |||||||||||
6705 | PushDefUseChildren(I, Worklist); | ||||||||||
6706 | } | ||||||||||
6707 | |||||||||||
6708 | LoopPropertiesCache.erase(CurrL); | ||||||||||
6709 | // Forget all contained loops too, to avoid dangling entries in the | ||||||||||
6710 | // ValuesAtScopes map. | ||||||||||
6711 | LoopWorklist.append(CurrL->begin(), CurrL->end()); | ||||||||||
6712 | } | ||||||||||
6713 | } | ||||||||||
6714 | |||||||||||
6715 | void ScalarEvolution::forgetTopmostLoop(const Loop *L) { | ||||||||||
6716 | while (Loop *Parent = L->getParentLoop()) | ||||||||||
6717 | L = Parent; | ||||||||||
6718 | forgetLoop(L); | ||||||||||
6719 | } | ||||||||||
6720 | |||||||||||
6721 | void ScalarEvolution::forgetValue(Value *V) { | ||||||||||
6722 | Instruction *I = dyn_cast<Instruction>(V); | ||||||||||
6723 | if (!I) return; | ||||||||||
6724 | |||||||||||
6725 | // Drop information about expressions based on loop-header PHIs. | ||||||||||
6726 | SmallVector<Instruction *, 16> Worklist; | ||||||||||
6727 | Worklist.push_back(I); | ||||||||||
6728 | |||||||||||
6729 | SmallPtrSet<Instruction *, 8> Visited; | ||||||||||
6730 | while (!Worklist.empty()) { | ||||||||||
6731 | I = Worklist.pop_back_val(); | ||||||||||
6732 | if (!Visited.insert(I).second) | ||||||||||
6733 | continue; | ||||||||||
6734 | |||||||||||
6735 | ValueExprMapType::iterator It = | ||||||||||
6736 | ValueExprMap.find_as(static_cast<Value *>(I)); | ||||||||||
6737 | if (It != ValueExprMap.end()) { | ||||||||||
6738 | eraseValueFromMap(It->first); | ||||||||||
6739 | forgetMemoizedResults(It->second); | ||||||||||
6740 | if (PHINode *PN = dyn_cast<PHINode>(I)) | ||||||||||
6741 | ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
6742 | } | ||||||||||
6743 | |||||||||||
6744 | PushDefUseChildren(I, Worklist); | ||||||||||
6745 | } | ||||||||||
6746 | } | ||||||||||
6747 | |||||||||||
6748 | void ScalarEvolution::forgetLoopDispositions(const Loop *L) { | ||||||||||
6749 | LoopDispositions.clear(); | ||||||||||
6750 | } | ||||||||||
6751 | |||||||||||
6752 | /// Get the exact loop backedge taken count considering all loop exits. A | ||||||||||
6753 | /// computable result can only be returned for loops with all exiting blocks | ||||||||||
6754 | /// dominating the latch. howFarToZero assumes that the limit of each loop test | ||||||||||
6755 | /// is never skipped. This is a valid assumption as long as the loop exits via | ||||||||||
6756 | /// that test. For precise results, it is the caller's responsibility to specify | ||||||||||
6757 | /// the relevant loop exiting block using getExact(ExitingBlock, SE). | ||||||||||
6758 | const SCEV * | ||||||||||
6759 | ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, | ||||||||||
6760 | SCEVUnionPredicate *Preds) const { | ||||||||||
6761 | // If any exits were not computable, the loop is not computable. | ||||||||||
6762 | if (!isComplete() || ExitNotTaken.empty()) | ||||||||||
6763 | return SE->getCouldNotCompute(); | ||||||||||
6764 | |||||||||||
6765 | const BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
6766 | // All exiting blocks we have collected must dominate the only backedge. | ||||||||||
6767 | if (!Latch) | ||||||||||
6768 | return SE->getCouldNotCompute(); | ||||||||||
6769 | |||||||||||
6770 | // All exiting blocks we have gathered dominate loop's latch, so exact trip | ||||||||||
6771 | // count is simply a minimum out of all these calculated exit counts. | ||||||||||
6772 | SmallVector<const SCEV *, 2> Ops; | ||||||||||
6773 | for (auto &ENT : ExitNotTaken) { | ||||||||||
6774 | const SCEV *BECount = ENT.ExactNotTaken; | ||||||||||
6775 | assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!")((BECount != SE->getCouldNotCompute() && "Bad exit SCEV!" ) ? static_cast<void> (0) : __assert_fail ("BECount != SE->getCouldNotCompute() && \"Bad exit SCEV!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6775, __PRETTY_FUNCTION__)); | ||||||||||
6776 | assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate " "latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6778, __PRETTY_FUNCTION__)) | ||||||||||
6777 | "We should only have known counts for exiting blocks that dominate "((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate " "latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6778, __PRETTY_FUNCTION__)) | ||||||||||
6778 | "latch!")((SE->DT.dominates(ENT.ExitingBlock, Latch) && "We should only have known counts for exiting blocks that dominate " "latch!") ? static_cast<void> (0) : __assert_fail ("SE->DT.dominates(ENT.ExitingBlock, Latch) && \"We should only have known counts for exiting blocks that dominate \" \"latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6778, __PRETTY_FUNCTION__)); | ||||||||||
6779 | |||||||||||
6780 | Ops.push_back(BECount); | ||||||||||
6781 | |||||||||||
6782 | if (Preds && !ENT.hasAlwaysTruePredicate()) | ||||||||||
6783 | Preds->add(ENT.Predicate.get()); | ||||||||||
6784 | |||||||||||
6785 | assert((Preds || ENT.hasAlwaysTruePredicate()) &&(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!" ) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6786, __PRETTY_FUNCTION__)) | ||||||||||
6786 | "Predicate should be always true!")(((Preds || ENT.hasAlwaysTruePredicate()) && "Predicate should be always true!" ) ? static_cast<void> (0) : __assert_fail ("(Preds || ENT.hasAlwaysTruePredicate()) && \"Predicate should be always true!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6786, __PRETTY_FUNCTION__)); | ||||||||||
6787 | } | ||||||||||
6788 | |||||||||||
6789 | return SE->getUMinFromMismatchedTypes(Ops); | ||||||||||
6790 | } | ||||||||||
6791 | |||||||||||
6792 | /// Get the exact not taken count for this loop exit. | ||||||||||
6793 | const SCEV * | ||||||||||
6794 | ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, | ||||||||||
6795 | ScalarEvolution *SE) const { | ||||||||||
6796 | for (auto &ENT : ExitNotTaken) | ||||||||||
6797 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) | ||||||||||
6798 | return ENT.ExactNotTaken; | ||||||||||
6799 | |||||||||||
6800 | return SE->getCouldNotCompute(); | ||||||||||
6801 | } | ||||||||||
6802 | |||||||||||
6803 | const SCEV * | ||||||||||
6804 | ScalarEvolution::BackedgeTakenInfo::getMax(const BasicBlock *ExitingBlock, | ||||||||||
6805 | ScalarEvolution *SE) const { | ||||||||||
6806 | for (auto &ENT : ExitNotTaken) | ||||||||||
6807 | if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) | ||||||||||
6808 | return ENT.MaxNotTaken; | ||||||||||
6809 | |||||||||||
6810 | return SE->getCouldNotCompute(); | ||||||||||
6811 | } | ||||||||||
6812 | |||||||||||
6813 | /// getMax - Get the max backedge taken count for the loop. | ||||||||||
6814 | const SCEV * | ||||||||||
6815 | ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { | ||||||||||
6816 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { | ||||||||||
6817 | return !ENT.hasAlwaysTruePredicate(); | ||||||||||
6818 | }; | ||||||||||
6819 | |||||||||||
6820 | if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) | ||||||||||
6821 | return SE->getCouldNotCompute(); | ||||||||||
6822 | |||||||||||
6823 | assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&(((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant >(getMax())) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6824, __PRETTY_FUNCTION__)) | ||||||||||
6824 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant >(getMax())) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6824, __PRETTY_FUNCTION__)); | ||||||||||
6825 | return getMax(); | ||||||||||
6826 | } | ||||||||||
6827 | |||||||||||
6828 | bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { | ||||||||||
6829 | auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { | ||||||||||
6830 | return !ENT.hasAlwaysTruePredicate(); | ||||||||||
6831 | }; | ||||||||||
6832 | return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); | ||||||||||
6833 | } | ||||||||||
6834 | |||||||||||
6835 | bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, | ||||||||||
6836 | ScalarEvolution *SE) const { | ||||||||||
6837 | if (getMax() && getMax() != SE->getCouldNotCompute() && | ||||||||||
6838 | SE->hasOperand(getMax(), S)) | ||||||||||
6839 | return true; | ||||||||||
6840 | |||||||||||
6841 | for (auto &ENT : ExitNotTaken) | ||||||||||
6842 | if (ENT.ExactNotTaken != SE->getCouldNotCompute() && | ||||||||||
6843 | SE->hasOperand(ENT.ExactNotTaken, S)) | ||||||||||
6844 | return true; | ||||||||||
6845 | |||||||||||
6846 | return false; | ||||||||||
6847 | } | ||||||||||
6848 | |||||||||||
6849 | ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) | ||||||||||
6850 | : ExactNotTaken(E), MaxNotTaken(E) { | ||||||||||
6851 | assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6853, __PRETTY_FUNCTION__)) | ||||||||||
6852 | isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6853, __PRETTY_FUNCTION__)) | ||||||||||
6853 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6853, __PRETTY_FUNCTION__)); | ||||||||||
6854 | } | ||||||||||
6855 | |||||||||||
6856 | ScalarEvolution::ExitLimit::ExitLimit( | ||||||||||
6857 | const SCEV *E, const SCEV *M, bool MaxOrZero, | ||||||||||
6858 | ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) | ||||||||||
6859 | : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { | ||||||||||
6860 | assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute >(MaxNotTaken)) && "Exact is not allowed to be less precise than Max" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6862, __PRETTY_FUNCTION__)) | ||||||||||
6861 | !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute >(MaxNotTaken)) && "Exact is not allowed to be less precise than Max" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6862, __PRETTY_FUNCTION__)) | ||||||||||
6862 | "Exact is not allowed to be less precise than Max")(((isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute >(MaxNotTaken)) && "Exact is not allowed to be less precise than Max" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(ExactNotTaken) || !isa<SCEVCouldNotCompute>(MaxNotTaken)) && \"Exact is not allowed to be less precise than Max\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6862, __PRETTY_FUNCTION__)); | ||||||||||
6863 | assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6865, __PRETTY_FUNCTION__)) | ||||||||||
6864 | isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6865, __PRETTY_FUNCTION__)) | ||||||||||
6865 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6865, __PRETTY_FUNCTION__)); | ||||||||||
6866 | for (auto *PredSet : PredSetList) | ||||||||||
6867 | for (auto *P : *PredSet) | ||||||||||
6868 | addPredicate(P); | ||||||||||
6869 | } | ||||||||||
6870 | |||||||||||
6871 | ScalarEvolution::ExitLimit::ExitLimit( | ||||||||||
6872 | const SCEV *E, const SCEV *M, bool MaxOrZero, | ||||||||||
6873 | const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) | ||||||||||
6874 | : ExitLimit(E, M, MaxOrZero, {&PredSet}) { | ||||||||||
6875 | assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6877, __PRETTY_FUNCTION__)) | ||||||||||
6876 | isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6877, __PRETTY_FUNCTION__)) | ||||||||||
6877 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6877, __PRETTY_FUNCTION__)); | ||||||||||
6878 | } | ||||||||||
6879 | |||||||||||
6880 | ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, | ||||||||||
6881 | bool MaxOrZero) | ||||||||||
6882 | : ExitLimit(E, M, MaxOrZero, None) { | ||||||||||
6883 | assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6885, __PRETTY_FUNCTION__)) | ||||||||||
6884 | isa<SCEVConstant>(MaxNotTaken)) &&(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6885, __PRETTY_FUNCTION__)) | ||||||||||
6885 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant >(MaxNotTaken)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxNotTaken) || isa<SCEVConstant>(MaxNotTaken)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6885, __PRETTY_FUNCTION__)); | ||||||||||
6886 | } | ||||||||||
6887 | |||||||||||
6888 | /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each | ||||||||||
6889 | /// computable exit into a persistent ExitNotTakenInfo array. | ||||||||||
6890 | ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( | ||||||||||
6891 | ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> | ||||||||||
6892 | ExitCounts, | ||||||||||
6893 | bool Complete, const SCEV *MaxCount, bool MaxOrZero) | ||||||||||
6894 | : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { | ||||||||||
6895 | using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; | ||||||||||
6896 | |||||||||||
6897 | ExitNotTaken.reserve(ExitCounts.size()); | ||||||||||
6898 | std::transform( | ||||||||||
6899 | ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), | ||||||||||
6900 | [&](const EdgeExitInfo &EEI) { | ||||||||||
6901 | BasicBlock *ExitBB = EEI.first; | ||||||||||
6902 | const ExitLimit &EL = EEI.second; | ||||||||||
6903 | if (EL.Predicates.empty()) | ||||||||||
6904 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, | ||||||||||
6905 | nullptr); | ||||||||||
6906 | |||||||||||
6907 | std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); | ||||||||||
6908 | for (auto *Pred : EL.Predicates) | ||||||||||
6909 | Predicate->add(Pred); | ||||||||||
6910 | |||||||||||
6911 | return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, | ||||||||||
6912 | std::move(Predicate)); | ||||||||||
6913 | }); | ||||||||||
6914 | assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&(((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant >(MaxCount)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6915, __PRETTY_FUNCTION__)) | ||||||||||
6915 | "No point in having a non-constant max backedge taken count!")(((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant >(MaxCount)) && "No point in having a non-constant max backedge taken count!" ) ? static_cast<void> (0) : __assert_fail ("(isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && \"No point in having a non-constant max backedge taken count!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6915, __PRETTY_FUNCTION__)); | ||||||||||
6916 | } | ||||||||||
6917 | |||||||||||
6918 | /// Invalidate this result and free the ExitNotTakenInfo array. | ||||||||||
6919 | void ScalarEvolution::BackedgeTakenInfo::clear() { | ||||||||||
6920 | ExitNotTaken.clear(); | ||||||||||
6921 | } | ||||||||||
6922 | |||||||||||
6923 | /// Compute the number of times the backedge of the specified loop will execute. | ||||||||||
6924 | ScalarEvolution::BackedgeTakenInfo | ||||||||||
6925 | ScalarEvolution::computeBackedgeTakenCount(const Loop *L, | ||||||||||
6926 | bool AllowPredicates) { | ||||||||||
6927 | SmallVector<BasicBlock *, 8> ExitingBlocks; | ||||||||||
6928 | L->getExitingBlocks(ExitingBlocks); | ||||||||||
6929 | |||||||||||
6930 | using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; | ||||||||||
6931 | |||||||||||
6932 | SmallVector<EdgeExitInfo, 4> ExitCounts; | ||||||||||
6933 | bool CouldComputeBECount = true; | ||||||||||
6934 | BasicBlock *Latch = L->getLoopLatch(); // may be NULL. | ||||||||||
6935 | const SCEV *MustExitMaxBECount = nullptr; | ||||||||||
6936 | const SCEV *MayExitMaxBECount = nullptr; | ||||||||||
6937 | bool MustExitMaxOrZero = false; | ||||||||||
6938 | |||||||||||
6939 | // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts | ||||||||||
6940 | // and compute maxBECount. | ||||||||||
6941 | // Do a union of all the predicates here. | ||||||||||
6942 | for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { | ||||||||||
6943 | BasicBlock *ExitBB = ExitingBlocks[i]; | ||||||||||
6944 | |||||||||||
6945 | // We canonicalize untaken exits to br (constant), ignore them so that | ||||||||||
6946 | // proving an exit untaken doesn't negatively impact our ability to reason | ||||||||||
6947 | // about the loop as whole. | ||||||||||
6948 | if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) | ||||||||||
6949 | if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { | ||||||||||
6950 | bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); | ||||||||||
6951 | if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) | ||||||||||
6952 | continue; | ||||||||||
6953 | } | ||||||||||
6954 | |||||||||||
6955 | ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); | ||||||||||
6956 | |||||||||||
6957 | assert((AllowPredicates || EL.Predicates.empty()) &&(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!" ) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6958, __PRETTY_FUNCTION__)) | ||||||||||
6958 | "Predicated exit limit when predicates are not allowed!")(((AllowPredicates || EL.Predicates.empty()) && "Predicated exit limit when predicates are not allowed!" ) ? static_cast<void> (0) : __assert_fail ("(AllowPredicates || EL.Predicates.empty()) && \"Predicated exit limit when predicates are not allowed!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 6958, __PRETTY_FUNCTION__)); | ||||||||||
6959 | |||||||||||
6960 | // 1. For each exit that can be computed, add an entry to ExitCounts. | ||||||||||
6961 | // CouldComputeBECount is true only if all exits can be computed. | ||||||||||
6962 | if (EL.ExactNotTaken == getCouldNotCompute()) | ||||||||||
6963 | // We couldn't compute an exact value for this exit, so | ||||||||||
6964 | // we won't be able to compute an exact value for the loop. | ||||||||||
6965 | CouldComputeBECount = false; | ||||||||||
6966 | else | ||||||||||
6967 | ExitCounts.emplace_back(ExitBB, EL); | ||||||||||
6968 | |||||||||||
6969 | // 2. Derive the loop's MaxBECount from each exit's max number of | ||||||||||
6970 | // non-exiting iterations. Partition the loop exits into two kinds: | ||||||||||
6971 | // LoopMustExits and LoopMayExits. | ||||||||||
6972 | // | ||||||||||
6973 | // If the exit dominates the loop latch, it is a LoopMustExit otherwise it | ||||||||||
6974 | // is a LoopMayExit. If any computable LoopMustExit is found, then | ||||||||||
6975 | // MaxBECount is the minimum EL.MaxNotTaken of computable | ||||||||||
6976 | // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum | ||||||||||
6977 | // EL.MaxNotTaken, where CouldNotCompute is considered greater than any | ||||||||||
6978 | // computable EL.MaxNotTaken. | ||||||||||
6979 | if (EL.MaxNotTaken != getCouldNotCompute() && Latch && | ||||||||||
6980 | DT.dominates(ExitBB, Latch)) { | ||||||||||
6981 | if (!MustExitMaxBECount) { | ||||||||||
6982 | MustExitMaxBECount = EL.MaxNotTaken; | ||||||||||
6983 | MustExitMaxOrZero = EL.MaxOrZero; | ||||||||||
6984 | } else { | ||||||||||
6985 | MustExitMaxBECount = | ||||||||||
6986 | getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); | ||||||||||
6987 | } | ||||||||||
6988 | } else if (MayExitMaxBECount != getCouldNotCompute()) { | ||||||||||
6989 | if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) | ||||||||||
6990 | MayExitMaxBECount = EL.MaxNotTaken; | ||||||||||
6991 | else { | ||||||||||
6992 | MayExitMaxBECount = | ||||||||||
6993 | getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); | ||||||||||
6994 | } | ||||||||||
6995 | } | ||||||||||
6996 | } | ||||||||||
6997 | const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : | ||||||||||
6998 | (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); | ||||||||||
6999 | // The loop backedge will be taken the maximum or zero times if there's | ||||||||||
7000 | // a single exit that must be taken the maximum or zero times. | ||||||||||
7001 | bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); | ||||||||||
7002 | return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, | ||||||||||
7003 | MaxBECount, MaxOrZero); | ||||||||||
7004 | } | ||||||||||
7005 | |||||||||||
7006 | ScalarEvolution::ExitLimit | ||||||||||
7007 | ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, | ||||||||||
7008 | bool AllowPredicates) { | ||||||||||
7009 | assert(L->contains(ExitingBlock) && "Exit count for non-loop block?")((L->contains(ExitingBlock) && "Exit count for non-loop block?" ) ? static_cast<void> (0) : __assert_fail ("L->contains(ExitingBlock) && \"Exit count for non-loop block?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7009, __PRETTY_FUNCTION__)); | ||||||||||
7010 | // If our exiting block does not dominate the latch, then its connection with | ||||||||||
7011 | // loop's exit limit may be far from trivial. | ||||||||||
7012 | const BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
7013 | if (!Latch || !DT.dominates(ExitingBlock, Latch)) | ||||||||||
7014 | return getCouldNotCompute(); | ||||||||||
7015 | |||||||||||
7016 | bool IsOnlyExit = (L->getExitingBlock() != nullptr); | ||||||||||
7017 | Instruction *Term = ExitingBlock->getTerminator(); | ||||||||||
7018 | if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { | ||||||||||
7019 | assert(BI->isConditional() && "If unconditional, it can't be in loop!")((BI->isConditional() && "If unconditional, it can't be in loop!" ) ? static_cast<void> (0) : __assert_fail ("BI->isConditional() && \"If unconditional, it can't be in loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7019, __PRETTY_FUNCTION__)); | ||||||||||
7020 | bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); | ||||||||||
7021 | assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&((ExitIfTrue == L->contains(BI->getSuccessor(1)) && "It should have one successor in loop and one exit block!") ? static_cast<void> (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7022, __PRETTY_FUNCTION__)) | ||||||||||
7022 | "It should have one successor in loop and one exit block!")((ExitIfTrue == L->contains(BI->getSuccessor(1)) && "It should have one successor in loop and one exit block!") ? static_cast<void> (0) : __assert_fail ("ExitIfTrue == L->contains(BI->getSuccessor(1)) && \"It should have one successor in loop and one exit block!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7022, __PRETTY_FUNCTION__)); | ||||||||||
7023 | // Proceed to the next level to examine the exit condition expression. | ||||||||||
7024 | return computeExitLimitFromCond( | ||||||||||
7025 | L, BI->getCondition(), ExitIfTrue, | ||||||||||
7026 | /*ControlsExit=*/IsOnlyExit, AllowPredicates); | ||||||||||
7027 | } | ||||||||||
7028 | |||||||||||
7029 | if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { | ||||||||||
7030 | // For switch, make sure that there is a single exit from the loop. | ||||||||||
7031 | BasicBlock *Exit = nullptr; | ||||||||||
7032 | for (auto *SBB : successors(ExitingBlock)) | ||||||||||
7033 | if (!L->contains(SBB)) { | ||||||||||
7034 | if (Exit) // Multiple exit successors. | ||||||||||
7035 | return getCouldNotCompute(); | ||||||||||
7036 | Exit = SBB; | ||||||||||
7037 | } | ||||||||||
7038 | assert(Exit && "Exiting block must have at least one exit")((Exit && "Exiting block must have at least one exit" ) ? static_cast<void> (0) : __assert_fail ("Exit && \"Exiting block must have at least one exit\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7038, __PRETTY_FUNCTION__)); | ||||||||||
7039 | return computeExitLimitFromSingleExitSwitch(L, SI, Exit, | ||||||||||
7040 | /*ControlsExit=*/IsOnlyExit); | ||||||||||
7041 | } | ||||||||||
7042 | |||||||||||
7043 | return getCouldNotCompute(); | ||||||||||
7044 | } | ||||||||||
7045 | |||||||||||
7046 | ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( | ||||||||||
7047 | const Loop *L, Value *ExitCond, bool ExitIfTrue, | ||||||||||
7048 | bool ControlsExit, bool AllowPredicates) { | ||||||||||
7049 | ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); | ||||||||||
7050 | return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, | ||||||||||
7051 | ControlsExit, AllowPredicates); | ||||||||||
7052 | } | ||||||||||
7053 | |||||||||||
7054 | Optional<ScalarEvolution::ExitLimit> | ||||||||||
7055 | ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, | ||||||||||
7056 | bool ExitIfTrue, bool ControlsExit, | ||||||||||
7057 | bool AllowPredicates) { | ||||||||||
7058 | (void)this->L; | ||||||||||
7059 | (void)this->ExitIfTrue; | ||||||||||
7060 | (void)this->AllowPredicates; | ||||||||||
7061 | |||||||||||
7062 | assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7064, __PRETTY_FUNCTION__)) | ||||||||||
7063 | this->AllowPredicates == AllowPredicates &&((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7064, __PRETTY_FUNCTION__)) | ||||||||||
7064 | "Variance in assumed invariant key components!")((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7064, __PRETTY_FUNCTION__)); | ||||||||||
7065 | auto Itr = TripCountMap.find({ExitCond, ControlsExit}); | ||||||||||
7066 | if (Itr == TripCountMap.end()) | ||||||||||
7067 | return None; | ||||||||||
7068 | return Itr->second; | ||||||||||
7069 | } | ||||||||||
7070 | |||||||||||
7071 | void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, | ||||||||||
7072 | bool ExitIfTrue, | ||||||||||
7073 | bool ControlsExit, | ||||||||||
7074 | bool AllowPredicates, | ||||||||||
7075 | const ExitLimit &EL) { | ||||||||||
7076 | assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7078, __PRETTY_FUNCTION__)) | ||||||||||
7077 | this->AllowPredicates == AllowPredicates &&((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7078, __PRETTY_FUNCTION__)) | ||||||||||
7078 | "Variance in assumed invariant key components!")((this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && "Variance in assumed invariant key components!") ? static_cast <void> (0) : __assert_fail ("this->L == L && this->ExitIfTrue == ExitIfTrue && this->AllowPredicates == AllowPredicates && \"Variance in assumed invariant key components!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7078, __PRETTY_FUNCTION__)); | ||||||||||
7079 | |||||||||||
7080 | auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); | ||||||||||
7081 | assert(InsertResult.second && "Expected successful insertion!")((InsertResult.second && "Expected successful insertion!" ) ? static_cast<void> (0) : __assert_fail ("InsertResult.second && \"Expected successful insertion!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7081, __PRETTY_FUNCTION__)); | ||||||||||
7082 | (void)InsertResult; | ||||||||||
7083 | (void)ExitIfTrue; | ||||||||||
7084 | } | ||||||||||
7085 | |||||||||||
7086 | ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( | ||||||||||
7087 | ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, | ||||||||||
7088 | bool ControlsExit, bool AllowPredicates) { | ||||||||||
7089 | |||||||||||
7090 | if (auto MaybeEL = | ||||||||||
7091 | Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) | ||||||||||
7092 | return *MaybeEL; | ||||||||||
7093 | |||||||||||
7094 | ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, | ||||||||||
7095 | ControlsExit, AllowPredicates); | ||||||||||
7096 | Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); | ||||||||||
7097 | return EL; | ||||||||||
7098 | } | ||||||||||
7099 | |||||||||||
7100 | ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( | ||||||||||
7101 | ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, | ||||||||||
7102 | bool ControlsExit, bool AllowPredicates) { | ||||||||||
7103 | // Check if the controlling expression for this loop is an And or Or. | ||||||||||
7104 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { | ||||||||||
7105 | if (BO->getOpcode() == Instruction::And) { | ||||||||||
7106 | // Recurse on the operands of the and. | ||||||||||
7107 | bool EitherMayExit = !ExitIfTrue; | ||||||||||
7108 | ExitLimit EL0 = computeExitLimitFromCondCached( | ||||||||||
7109 | Cache, L, BO->getOperand(0), ExitIfTrue, | ||||||||||
7110 | ControlsExit && !EitherMayExit, AllowPredicates); | ||||||||||
7111 | ExitLimit EL1 = computeExitLimitFromCondCached( | ||||||||||
7112 | Cache, L, BO->getOperand(1), ExitIfTrue, | ||||||||||
7113 | ControlsExit && !EitherMayExit, AllowPredicates); | ||||||||||
7114 | // Be robust against unsimplified IR for the form "and i1 X, true" | ||||||||||
7115 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) | ||||||||||
7116 | return CI->isOne() ? EL0 : EL1; | ||||||||||
7117 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) | ||||||||||
7118 | return CI->isOne() ? EL1 : EL0; | ||||||||||
7119 | const SCEV *BECount = getCouldNotCompute(); | ||||||||||
7120 | const SCEV *MaxBECount = getCouldNotCompute(); | ||||||||||
7121 | if (EitherMayExit) { | ||||||||||
7122 | // Both conditions must be true for the loop to continue executing. | ||||||||||
7123 | // Choose the less conservative count. | ||||||||||
7124 | if (EL0.ExactNotTaken == getCouldNotCompute() || | ||||||||||
7125 | EL1.ExactNotTaken == getCouldNotCompute()) | ||||||||||
7126 | BECount = getCouldNotCompute(); | ||||||||||
7127 | else | ||||||||||
7128 | BECount = | ||||||||||
7129 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); | ||||||||||
7130 | if (EL0.MaxNotTaken == getCouldNotCompute()) | ||||||||||
7131 | MaxBECount = EL1.MaxNotTaken; | ||||||||||
7132 | else if (EL1.MaxNotTaken == getCouldNotCompute()) | ||||||||||
7133 | MaxBECount = EL0.MaxNotTaken; | ||||||||||
7134 | else | ||||||||||
7135 | MaxBECount = | ||||||||||
7136 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); | ||||||||||
7137 | } else { | ||||||||||
7138 | // Both conditions must be true at the same time for the loop to exit. | ||||||||||
7139 | // For now, be conservative. | ||||||||||
7140 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) | ||||||||||
7141 | MaxBECount = EL0.MaxNotTaken; | ||||||||||
7142 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) | ||||||||||
7143 | BECount = EL0.ExactNotTaken; | ||||||||||
7144 | } | ||||||||||
7145 | |||||||||||
7146 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able | ||||||||||
7147 | // to be more aggressive when computing BECount than when computing | ||||||||||
7148 | // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and | ||||||||||
7149 | // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken | ||||||||||
7150 | // to not. | ||||||||||
7151 | if (isa<SCEVCouldNotCompute>(MaxBECount) && | ||||||||||
7152 | !isa<SCEVCouldNotCompute>(BECount)) | ||||||||||
7153 | MaxBECount = getConstant(getUnsignedRangeMax(BECount)); | ||||||||||
7154 | |||||||||||
7155 | return ExitLimit(BECount, MaxBECount, false, | ||||||||||
7156 | {&EL0.Predicates, &EL1.Predicates}); | ||||||||||
7157 | } | ||||||||||
7158 | if (BO->getOpcode() == Instruction::Or) { | ||||||||||
7159 | // Recurse on the operands of the or. | ||||||||||
7160 | bool EitherMayExit = ExitIfTrue; | ||||||||||
7161 | ExitLimit EL0 = computeExitLimitFromCondCached( | ||||||||||
7162 | Cache, L, BO->getOperand(0), ExitIfTrue, | ||||||||||
7163 | ControlsExit && !EitherMayExit, AllowPredicates); | ||||||||||
7164 | ExitLimit EL1 = computeExitLimitFromCondCached( | ||||||||||
7165 | Cache, L, BO->getOperand(1), ExitIfTrue, | ||||||||||
7166 | ControlsExit && !EitherMayExit, AllowPredicates); | ||||||||||
7167 | // Be robust against unsimplified IR for the form "or i1 X, true" | ||||||||||
7168 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) | ||||||||||
7169 | return CI->isZero() ? EL0 : EL1; | ||||||||||
7170 | if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) | ||||||||||
7171 | return CI->isZero() ? EL1 : EL0; | ||||||||||
7172 | const SCEV *BECount = getCouldNotCompute(); | ||||||||||
7173 | const SCEV *MaxBECount = getCouldNotCompute(); | ||||||||||
7174 | if (EitherMayExit) { | ||||||||||
7175 | // Both conditions must be false for the loop to continue executing. | ||||||||||
7176 | // Choose the less conservative count. | ||||||||||
7177 | if (EL0.ExactNotTaken == getCouldNotCompute() || | ||||||||||
7178 | EL1.ExactNotTaken == getCouldNotCompute()) | ||||||||||
7179 | BECount = getCouldNotCompute(); | ||||||||||
7180 | else | ||||||||||
7181 | BECount = | ||||||||||
7182 | getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); | ||||||||||
7183 | if (EL0.MaxNotTaken == getCouldNotCompute()) | ||||||||||
7184 | MaxBECount = EL1.MaxNotTaken; | ||||||||||
7185 | else if (EL1.MaxNotTaken == getCouldNotCompute()) | ||||||||||
7186 | MaxBECount = EL0.MaxNotTaken; | ||||||||||
7187 | else | ||||||||||
7188 | MaxBECount = | ||||||||||
7189 | getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); | ||||||||||
7190 | } else { | ||||||||||
7191 | // Both conditions must be false at the same time for the loop to exit. | ||||||||||
7192 | // For now, be conservative. | ||||||||||
7193 | if (EL0.MaxNotTaken == EL1.MaxNotTaken) | ||||||||||
7194 | MaxBECount = EL0.MaxNotTaken; | ||||||||||
7195 | if (EL0.ExactNotTaken == EL1.ExactNotTaken) | ||||||||||
7196 | BECount = EL0.ExactNotTaken; | ||||||||||
7197 | } | ||||||||||
7198 | // There are cases (e.g. PR26207) where computeExitLimitFromCond is able | ||||||||||
7199 | // to be more aggressive when computing BECount than when computing | ||||||||||
7200 | // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and | ||||||||||
7201 | // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken | ||||||||||
7202 | // to not. | ||||||||||
7203 | if (isa<SCEVCouldNotCompute>(MaxBECount) && | ||||||||||
7204 | !isa<SCEVCouldNotCompute>(BECount)) | ||||||||||
7205 | MaxBECount = getConstant(getUnsignedRangeMax(BECount)); | ||||||||||
7206 | |||||||||||
7207 | return ExitLimit(BECount, MaxBECount, false, | ||||||||||
7208 | {&EL0.Predicates, &EL1.Predicates}); | ||||||||||
7209 | } | ||||||||||
7210 | } | ||||||||||
7211 | |||||||||||
7212 | // With an icmp, it may be feasible to compute an exact backedge-taken count. | ||||||||||
7213 | // Proceed to the next level to examine the icmp. | ||||||||||
7214 | if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { | ||||||||||
7215 | ExitLimit EL = | ||||||||||
7216 | computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); | ||||||||||
7217 | if (EL.hasFullInfo() || !AllowPredicates) | ||||||||||
7218 | return EL; | ||||||||||
7219 | |||||||||||
7220 | // Try again, but use SCEV predicates this time. | ||||||||||
7221 | return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, | ||||||||||
7222 | /*AllowPredicates=*/true); | ||||||||||
7223 | } | ||||||||||
7224 | |||||||||||
7225 | // Check for a constant condition. These are normally stripped out by | ||||||||||
7226 | // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to | ||||||||||
7227 | // preserve the CFG and is temporarily leaving constant conditions | ||||||||||
7228 | // in place. | ||||||||||
7229 | if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { | ||||||||||
7230 | if (ExitIfTrue == !CI->getZExtValue()) | ||||||||||
7231 | // The backedge is always taken. | ||||||||||
7232 | return getCouldNotCompute(); | ||||||||||
7233 | else | ||||||||||
7234 | // The backedge is never taken. | ||||||||||
7235 | return getZero(CI->getType()); | ||||||||||
7236 | } | ||||||||||
7237 | |||||||||||
7238 | // If it's not an integer or pointer comparison then compute it the hard way. | ||||||||||
7239 | return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); | ||||||||||
7240 | } | ||||||||||
7241 | |||||||||||
7242 | ScalarEvolution::ExitLimit | ||||||||||
7243 | ScalarEvolution::computeExitLimitFromICmp(const Loop *L, | ||||||||||
7244 | ICmpInst *ExitCond, | ||||||||||
7245 | bool ExitIfTrue, | ||||||||||
7246 | bool ControlsExit, | ||||||||||
7247 | bool AllowPredicates) { | ||||||||||
7248 | // If the condition was exit on true, convert the condition to exit on false | ||||||||||
7249 | ICmpInst::Predicate Pred; | ||||||||||
7250 | if (!ExitIfTrue) | ||||||||||
7251 | Pred = ExitCond->getPredicate(); | ||||||||||
7252 | else | ||||||||||
7253 | Pred = ExitCond->getInversePredicate(); | ||||||||||
7254 | const ICmpInst::Predicate OriginalPred = Pred; | ||||||||||
7255 | |||||||||||
7256 | // Handle common loops like: for (X = "string"; *X; ++X) | ||||||||||
7257 | if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) | ||||||||||
7258 | if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { | ||||||||||
7259 | ExitLimit ItCnt = | ||||||||||
7260 | computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); | ||||||||||
7261 | if (ItCnt.hasAnyInfo()) | ||||||||||
7262 | return ItCnt; | ||||||||||
7263 | } | ||||||||||
7264 | |||||||||||
7265 | const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); | ||||||||||
7266 | const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); | ||||||||||
7267 | |||||||||||
7268 | // Try to evaluate any dependencies out of the loop. | ||||||||||
7269 | LHS = getSCEVAtScope(LHS, L); | ||||||||||
7270 | RHS = getSCEVAtScope(RHS, L); | ||||||||||
7271 | |||||||||||
7272 | // At this point, we would like to compute how many iterations of the | ||||||||||
7273 | // loop the predicate will return true for these inputs. | ||||||||||
7274 | if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { | ||||||||||
7275 | // If there is a loop-invariant, force it into the RHS. | ||||||||||
7276 | std::swap(LHS, RHS); | ||||||||||
7277 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
7278 | } | ||||||||||
7279 | |||||||||||
7280 | // Simplify the operands before analyzing them. | ||||||||||
7281 | (void)SimplifyICmpOperands(Pred, LHS, RHS); | ||||||||||
7282 | |||||||||||
7283 | // If we have a comparison of a chrec against a constant, try to use value | ||||||||||
7284 | // ranges to answer this query. | ||||||||||
7285 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) | ||||||||||
7286 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) | ||||||||||
7287 | if (AddRec->getLoop() == L) { | ||||||||||
7288 | // Form the constant range. | ||||||||||
7289 | ConstantRange CompRange = | ||||||||||
7290 | ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); | ||||||||||
7291 | |||||||||||
7292 | const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); | ||||||||||
7293 | if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; | ||||||||||
7294 | } | ||||||||||
7295 | |||||||||||
7296 | switch (Pred) { | ||||||||||
7297 | case ICmpInst::ICMP_NE: { // while (X != Y) | ||||||||||
7298 | // Convert to: while (X-Y != 0) | ||||||||||
7299 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, | ||||||||||
7300 | AllowPredicates); | ||||||||||
7301 | if (EL.hasAnyInfo()) return EL; | ||||||||||
7302 | break; | ||||||||||
7303 | } | ||||||||||
7304 | case ICmpInst::ICMP_EQ: { // while (X == Y) | ||||||||||
7305 | // Convert to: while (X-Y == 0) | ||||||||||
7306 | ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); | ||||||||||
7307 | if (EL.hasAnyInfo()) return EL; | ||||||||||
7308 | break; | ||||||||||
7309 | } | ||||||||||
7310 | case ICmpInst::ICMP_SLT: | ||||||||||
7311 | case ICmpInst::ICMP_ULT: { // while (X < Y) | ||||||||||
7312 | bool IsSigned = Pred == ICmpInst::ICMP_SLT; | ||||||||||
7313 | ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, | ||||||||||
7314 | AllowPredicates); | ||||||||||
7315 | if (EL.hasAnyInfo()) return EL; | ||||||||||
7316 | break; | ||||||||||
7317 | } | ||||||||||
7318 | case ICmpInst::ICMP_SGT: | ||||||||||
7319 | case ICmpInst::ICMP_UGT: { // while (X > Y) | ||||||||||
7320 | bool IsSigned = Pred == ICmpInst::ICMP_SGT; | ||||||||||
7321 | ExitLimit EL = | ||||||||||
7322 | howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, | ||||||||||
7323 | AllowPredicates); | ||||||||||
7324 | if (EL.hasAnyInfo()) return EL; | ||||||||||
7325 | break; | ||||||||||
7326 | } | ||||||||||
7327 | default: | ||||||||||
7328 | break; | ||||||||||
7329 | } | ||||||||||
7330 | |||||||||||
7331 | auto *ExhaustiveCount = | ||||||||||
7332 | computeExitCountExhaustively(L, ExitCond, ExitIfTrue); | ||||||||||
7333 | |||||||||||
7334 | if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) | ||||||||||
7335 | return ExhaustiveCount; | ||||||||||
7336 | |||||||||||
7337 | return computeShiftCompareExitLimit(ExitCond->getOperand(0), | ||||||||||
7338 | ExitCond->getOperand(1), L, OriginalPred); | ||||||||||
7339 | } | ||||||||||
7340 | |||||||||||
7341 | ScalarEvolution::ExitLimit | ||||||||||
7342 | ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, | ||||||||||
7343 | SwitchInst *Switch, | ||||||||||
7344 | BasicBlock *ExitingBlock, | ||||||||||
7345 | bool ControlsExit) { | ||||||||||
7346 | assert(!L->contains(ExitingBlock) && "Not an exiting block!")((!L->contains(ExitingBlock) && "Not an exiting block!" ) ? static_cast<void> (0) : __assert_fail ("!L->contains(ExitingBlock) && \"Not an exiting block!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7346, __PRETTY_FUNCTION__)); | ||||||||||
7347 | |||||||||||
7348 | // Give up if the exit is the default dest of a switch. | ||||||||||
7349 | if (Switch->getDefaultDest() == ExitingBlock) | ||||||||||
7350 | return getCouldNotCompute(); | ||||||||||
7351 | |||||||||||
7352 | assert(L->contains(Switch->getDefaultDest()) &&((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7353, __PRETTY_FUNCTION__)) | ||||||||||
7353 | "Default case must not exit the loop!")((L->contains(Switch->getDefaultDest()) && "Default case must not exit the loop!" ) ? static_cast<void> (0) : __assert_fail ("L->contains(Switch->getDefaultDest()) && \"Default case must not exit the loop!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7353, __PRETTY_FUNCTION__)); | ||||||||||
7354 | const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); | ||||||||||
7355 | const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); | ||||||||||
7356 | |||||||||||
7357 | // while (X != Y) --> while (X-Y != 0) | ||||||||||
7358 | ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); | ||||||||||
7359 | if (EL.hasAnyInfo()) | ||||||||||
7360 | return EL; | ||||||||||
7361 | |||||||||||
7362 | return getCouldNotCompute(); | ||||||||||
7363 | } | ||||||||||
7364 | |||||||||||
7365 | static ConstantInt * | ||||||||||
7366 | EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, | ||||||||||
7367 | ScalarEvolution &SE) { | ||||||||||
7368 | const SCEV *InVal = SE.getConstant(C); | ||||||||||
7369 | const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); | ||||||||||
7370 | assert(isa<SCEVConstant>(Val) &&((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?" ) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7371, __PRETTY_FUNCTION__)) | ||||||||||
7371 | "Evaluation of SCEV at constant didn't fold correctly?")((isa<SCEVConstant>(Val) && "Evaluation of SCEV at constant didn't fold correctly?" ) ? static_cast<void> (0) : __assert_fail ("isa<SCEVConstant>(Val) && \"Evaluation of SCEV at constant didn't fold correctly?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7371, __PRETTY_FUNCTION__)); | ||||||||||
7372 | return cast<SCEVConstant>(Val)->getValue(); | ||||||||||
7373 | } | ||||||||||
7374 | |||||||||||
7375 | /// Given an exit condition of 'icmp op load X, cst', try to see if we can | ||||||||||
7376 | /// compute the backedge execution count. | ||||||||||
7377 | ScalarEvolution::ExitLimit | ||||||||||
7378 | ScalarEvolution::computeLoadConstantCompareExitLimit( | ||||||||||
7379 | LoadInst *LI, | ||||||||||
7380 | Constant *RHS, | ||||||||||
7381 | const Loop *L, | ||||||||||
7382 | ICmpInst::Predicate predicate) { | ||||||||||
7383 | if (LI->isVolatile()) return getCouldNotCompute(); | ||||||||||
7384 | |||||||||||
7385 | // Check to see if the loaded pointer is a getelementptr of a global. | ||||||||||
7386 | // TODO: Use SCEV instead of manually grubbing with GEPs. | ||||||||||
7387 | GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); | ||||||||||
7388 | if (!GEP) return getCouldNotCompute(); | ||||||||||
7389 | |||||||||||
7390 | // Make sure that it is really a constant global we are gepping, with an | ||||||||||
7391 | // initializer, and make sure the first IDX is really 0. | ||||||||||
7392 | GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); | ||||||||||
7393 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || | ||||||||||
7394 | GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || | ||||||||||
7395 | !cast<Constant>(GEP->getOperand(1))->isNullValue()) | ||||||||||
7396 | return getCouldNotCompute(); | ||||||||||
7397 | |||||||||||
7398 | // Okay, we allow one non-constant index into the GEP instruction. | ||||||||||
7399 | Value *VarIdx = nullptr; | ||||||||||
7400 | std::vector<Constant*> Indexes; | ||||||||||
7401 | unsigned VarIdxNum = 0; | ||||||||||
7402 | for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) | ||||||||||
7403 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { | ||||||||||
7404 | Indexes.push_back(CI); | ||||||||||
7405 | } else if (!isa<ConstantInt>(GEP->getOperand(i))) { | ||||||||||
7406 | if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. | ||||||||||
7407 | VarIdx = GEP->getOperand(i); | ||||||||||
7408 | VarIdxNum = i-2; | ||||||||||
7409 | Indexes.push_back(nullptr); | ||||||||||
7410 | } | ||||||||||
7411 | |||||||||||
7412 | // Loop-invariant loads may be a byproduct of loop optimization. Skip them. | ||||||||||
7413 | if (!VarIdx) | ||||||||||
7414 | return getCouldNotCompute(); | ||||||||||
7415 | |||||||||||
7416 | // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. | ||||||||||
7417 | // Check to see if X is a loop variant variable value now. | ||||||||||
7418 | const SCEV *Idx = getSCEV(VarIdx); | ||||||||||
7419 | Idx = getSCEVAtScope(Idx, L); | ||||||||||
7420 | |||||||||||
7421 | // We can only recognize very limited forms of loop index expressions, in | ||||||||||
7422 | // particular, only affine AddRec's like {C1,+,C2}. | ||||||||||
7423 | const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); | ||||||||||
7424 | if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || | ||||||||||
7425 | !isa<SCEVConstant>(IdxExpr->getOperand(0)) || | ||||||||||
7426 | !isa<SCEVConstant>(IdxExpr->getOperand(1))) | ||||||||||
7427 | return getCouldNotCompute(); | ||||||||||
7428 | |||||||||||
7429 | unsigned MaxSteps = MaxBruteForceIterations; | ||||||||||
7430 | for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { | ||||||||||
7431 | ConstantInt *ItCst = ConstantInt::get( | ||||||||||
7432 | cast<IntegerType>(IdxExpr->getType()), IterationNum); | ||||||||||
7433 | ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); | ||||||||||
7434 | |||||||||||
7435 | // Form the GEP offset. | ||||||||||
7436 | Indexes[VarIdxNum] = Val; | ||||||||||
7437 | |||||||||||
7438 | Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), | ||||||||||
7439 | Indexes); | ||||||||||
7440 | if (!Result) break; // Cannot compute! | ||||||||||
7441 | |||||||||||
7442 | // Evaluate the condition for this iteration. | ||||||||||
7443 | Result = ConstantExpr::getICmp(predicate, Result, RHS); | ||||||||||
7444 | if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure | ||||||||||
7445 | if (cast<ConstantInt>(Result)->getValue().isMinValue()) { | ||||||||||
7446 | ++NumArrayLenItCounts; | ||||||||||
7447 | return getConstant(ItCst); // Found terminating iteration! | ||||||||||
7448 | } | ||||||||||
7449 | } | ||||||||||
7450 | return getCouldNotCompute(); | ||||||||||
7451 | } | ||||||||||
7452 | |||||||||||
7453 | ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( | ||||||||||
7454 | Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { | ||||||||||
7455 | ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); | ||||||||||
7456 | if (!RHS) | ||||||||||
7457 | return getCouldNotCompute(); | ||||||||||
7458 | |||||||||||
7459 | const BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
7460 | if (!Latch) | ||||||||||
7461 | return getCouldNotCompute(); | ||||||||||
7462 | |||||||||||
7463 | const BasicBlock *Predecessor = L->getLoopPredecessor(); | ||||||||||
7464 | if (!Predecessor) | ||||||||||
7465 | return getCouldNotCompute(); | ||||||||||
7466 | |||||||||||
7467 | // Return true if V is of the form "LHS `shift_op` <positive constant>". | ||||||||||
7468 | // Return LHS in OutLHS and shift_opt in OutOpCode. | ||||||||||
7469 | auto MatchPositiveShift = | ||||||||||
7470 | [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { | ||||||||||
7471 | |||||||||||
7472 | using namespace PatternMatch; | ||||||||||
7473 | |||||||||||
7474 | ConstantInt *ShiftAmt; | ||||||||||
7475 | if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) | ||||||||||
7476 | OutOpCode = Instruction::LShr; | ||||||||||
7477 | else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) | ||||||||||
7478 | OutOpCode = Instruction::AShr; | ||||||||||
7479 | else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) | ||||||||||
7480 | OutOpCode = Instruction::Shl; | ||||||||||
7481 | else | ||||||||||
7482 | return false; | ||||||||||
7483 | |||||||||||
7484 | return ShiftAmt->getValue().isStrictlyPositive(); | ||||||||||
7485 | }; | ||||||||||
7486 | |||||||||||
7487 | // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in | ||||||||||
7488 | // | ||||||||||
7489 | // loop: | ||||||||||
7490 | // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] | ||||||||||
7491 | // %iv.shifted = lshr i32 %iv, <positive constant> | ||||||||||
7492 | // | ||||||||||
7493 | // Return true on a successful match. Return the corresponding PHI node (%iv | ||||||||||
7494 | // above) in PNOut and the opcode of the shift operation in OpCodeOut. | ||||||||||
7495 | auto MatchShiftRecurrence = | ||||||||||
7496 | [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { | ||||||||||
7497 | Optional<Instruction::BinaryOps> PostShiftOpCode; | ||||||||||
7498 | |||||||||||
7499 | { | ||||||||||
7500 | Instruction::BinaryOps OpC; | ||||||||||
7501 | Value *V; | ||||||||||
7502 | |||||||||||
7503 | // If we encounter a shift instruction, "peel off" the shift operation, | ||||||||||
7504 | // and remember that we did so. Later when we inspect %iv's backedge | ||||||||||
7505 | // value, we will make sure that the backedge value uses the same | ||||||||||
7506 | // operation. | ||||||||||
7507 | // | ||||||||||
7508 | // Note: the peeled shift operation does not have to be the same | ||||||||||
7509 | // instruction as the one feeding into the PHI's backedge value. We only | ||||||||||
7510 | // really care about it being the same *kind* of shift instruction -- | ||||||||||
7511 | // that's all that is required for our later inferences to hold. | ||||||||||
7512 | if (MatchPositiveShift(LHS, V, OpC)) { | ||||||||||
7513 | PostShiftOpCode = OpC; | ||||||||||
7514 | LHS = V; | ||||||||||
7515 | } | ||||||||||
7516 | } | ||||||||||
7517 | |||||||||||
7518 | PNOut = dyn_cast<PHINode>(LHS); | ||||||||||
7519 | if (!PNOut || PNOut->getParent() != L->getHeader()) | ||||||||||
7520 | return false; | ||||||||||
7521 | |||||||||||
7522 | Value *BEValue = PNOut->getIncomingValueForBlock(Latch); | ||||||||||
7523 | Value *OpLHS; | ||||||||||
7524 | |||||||||||
7525 | return | ||||||||||
7526 | // The backedge value for the PHI node must be a shift by a positive | ||||||||||
7527 | // amount | ||||||||||
7528 | MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && | ||||||||||
7529 | |||||||||||
7530 | // of the PHI node itself | ||||||||||
7531 | OpLHS == PNOut && | ||||||||||
7532 | |||||||||||
7533 | // and the kind of shift should be match the kind of shift we peeled | ||||||||||
7534 | // off, if any. | ||||||||||
7535 | (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); | ||||||||||
7536 | }; | ||||||||||
7537 | |||||||||||
7538 | PHINode *PN; | ||||||||||
7539 | Instruction::BinaryOps OpCode; | ||||||||||
7540 | if (!MatchShiftRecurrence(LHS, PN, OpCode)) | ||||||||||
7541 | return getCouldNotCompute(); | ||||||||||
7542 | |||||||||||
7543 | const DataLayout &DL = getDataLayout(); | ||||||||||
7544 | |||||||||||
7545 | // The key rationale for this optimization is that for some kinds of shift | ||||||||||
7546 | // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 | ||||||||||
7547 | // within a finite number of iterations. If the condition guarding the | ||||||||||
7548 | // backedge (in the sense that the backedge is taken if the condition is true) | ||||||||||
7549 | // is false for the value the shift recurrence stabilizes to, then we know | ||||||||||
7550 | // that the backedge is taken only a finite number of times. | ||||||||||
7551 | |||||||||||
7552 | ConstantInt *StableValue = nullptr; | ||||||||||
7553 | switch (OpCode) { | ||||||||||
7554 | default: | ||||||||||
7555 | llvm_unreachable("Impossible case!")::llvm::llvm_unreachable_internal("Impossible case!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7555); | ||||||||||
7556 | |||||||||||
7557 | case Instruction::AShr: { | ||||||||||
7558 | // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most | ||||||||||
7559 | // bitwidth(K) iterations. | ||||||||||
7560 | Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); | ||||||||||
7561 | KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, | ||||||||||
7562 | Predecessor->getTerminator(), &DT); | ||||||||||
7563 | auto *Ty = cast<IntegerType>(RHS->getType()); | ||||||||||
7564 | if (Known.isNonNegative()) | ||||||||||
7565 | StableValue = ConstantInt::get(Ty, 0); | ||||||||||
7566 | else if (Known.isNegative()) | ||||||||||
7567 | StableValue = ConstantInt::get(Ty, -1, true); | ||||||||||
7568 | else | ||||||||||
7569 | return getCouldNotCompute(); | ||||||||||
7570 | |||||||||||
7571 | break; | ||||||||||
7572 | } | ||||||||||
7573 | case Instruction::LShr: | ||||||||||
7574 | case Instruction::Shl: | ||||||||||
7575 | // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} | ||||||||||
7576 | // stabilize to 0 in at most bitwidth(K) iterations. | ||||||||||
7577 | StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); | ||||||||||
7578 | break; | ||||||||||
7579 | } | ||||||||||
7580 | |||||||||||
7581 | auto *Result = | ||||||||||
7582 | ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); | ||||||||||
7583 | assert(Result->getType()->isIntegerTy(1) &&((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction" ) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7584, __PRETTY_FUNCTION__)) | ||||||||||
7584 | "Otherwise cannot be an operand to a branch instruction")((Result->getType()->isIntegerTy(1) && "Otherwise cannot be an operand to a branch instruction" ) ? static_cast<void> (0) : __assert_fail ("Result->getType()->isIntegerTy(1) && \"Otherwise cannot be an operand to a branch instruction\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7584, __PRETTY_FUNCTION__)); | ||||||||||
7585 | |||||||||||
7586 | if (Result->isZeroValue()) { | ||||||||||
7587 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); | ||||||||||
7588 | const SCEV *UpperBound = | ||||||||||
7589 | getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); | ||||||||||
7590 | return ExitLimit(getCouldNotCompute(), UpperBound, false); | ||||||||||
7591 | } | ||||||||||
7592 | |||||||||||
7593 | return getCouldNotCompute(); | ||||||||||
7594 | } | ||||||||||
7595 | |||||||||||
7596 | /// Return true if we can constant fold an instruction of the specified type, | ||||||||||
7597 | /// assuming that all operands were constants. | ||||||||||
7598 | static bool CanConstantFold(const Instruction *I) { | ||||||||||
7599 | if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || | ||||||||||
7600 | isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || | ||||||||||
7601 | isa<LoadInst>(I) || isa<ExtractValueInst>(I)) | ||||||||||
7602 | return true; | ||||||||||
7603 | |||||||||||
7604 | if (const CallInst *CI = dyn_cast<CallInst>(I)) | ||||||||||
7605 | if (const Function *F = CI->getCalledFunction()) | ||||||||||
7606 | return canConstantFoldCallTo(CI, F); | ||||||||||
7607 | return false; | ||||||||||
7608 | } | ||||||||||
7609 | |||||||||||
7610 | /// Determine whether this instruction can constant evolve within this loop | ||||||||||
7611 | /// assuming its operands can all constant evolve. | ||||||||||
7612 | static bool canConstantEvolve(Instruction *I, const Loop *L) { | ||||||||||
7613 | // An instruction outside of the loop can't be derived from a loop PHI. | ||||||||||
7614 | if (!L->contains(I)) return false; | ||||||||||
7615 | |||||||||||
7616 | if (isa<PHINode>(I)) { | ||||||||||
7617 | // We don't currently keep track of the control flow needed to evaluate | ||||||||||
7618 | // PHIs, so we cannot handle PHIs inside of loops. | ||||||||||
7619 | return L->getHeader() == I->getParent(); | ||||||||||
7620 | } | ||||||||||
7621 | |||||||||||
7622 | // If we won't be able to constant fold this expression even if the operands | ||||||||||
7623 | // are constants, bail early. | ||||||||||
7624 | return CanConstantFold(I); | ||||||||||
7625 | } | ||||||||||
7626 | |||||||||||
7627 | /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by | ||||||||||
7628 | /// recursing through each instruction operand until reaching a loop header phi. | ||||||||||
7629 | static PHINode * | ||||||||||
7630 | getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, | ||||||||||
7631 | DenseMap<Instruction *, PHINode *> &PHIMap, | ||||||||||
7632 | unsigned Depth) { | ||||||||||
7633 | if (Depth > MaxConstantEvolvingDepth) | ||||||||||
7634 | return nullptr; | ||||||||||
7635 | |||||||||||
7636 | // Otherwise, we can evaluate this instruction if all of its operands are | ||||||||||
7637 | // constant or derived from a PHI node themselves. | ||||||||||
7638 | PHINode *PHI = nullptr; | ||||||||||
7639 | for (Value *Op : UseInst->operands()) { | ||||||||||
7640 | if (isa<Constant>(Op)) continue; | ||||||||||
7641 | |||||||||||
7642 | Instruction *OpInst = dyn_cast<Instruction>(Op); | ||||||||||
7643 | if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; | ||||||||||
7644 | |||||||||||
7645 | PHINode *P = dyn_cast<PHINode>(OpInst); | ||||||||||
7646 | if (!P) | ||||||||||
7647 | // If this operand is already visited, reuse the prior result. | ||||||||||
7648 | // We may have P != PHI if this is the deepest point at which the | ||||||||||
7649 | // inconsistent paths meet. | ||||||||||
7650 | P = PHIMap.lookup(OpInst); | ||||||||||
7651 | if (!P) { | ||||||||||
7652 | // Recurse and memoize the results, whether a phi is found or not. | ||||||||||
7653 | // This recursive call invalidates pointers into PHIMap. | ||||||||||
7654 | P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); | ||||||||||
7655 | PHIMap[OpInst] = P; | ||||||||||
7656 | } | ||||||||||
7657 | if (!P) | ||||||||||
7658 | return nullptr; // Not evolving from PHI | ||||||||||
7659 | if (PHI && PHI != P) | ||||||||||
7660 | return nullptr; // Evolving from multiple different PHIs. | ||||||||||
7661 | PHI = P; | ||||||||||
7662 | } | ||||||||||
7663 | // This is a expression evolving from a constant PHI! | ||||||||||
7664 | return PHI; | ||||||||||
7665 | } | ||||||||||
7666 | |||||||||||
7667 | /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node | ||||||||||
7668 | /// in the loop that V is derived from. We allow arbitrary operations along the | ||||||||||
7669 | /// way, but the operands of an operation must either be constants or a value | ||||||||||
7670 | /// derived from a constant PHI. If this expression does not fit with these | ||||||||||
7671 | /// constraints, return null. | ||||||||||
7672 | static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { | ||||||||||
7673 | Instruction *I = dyn_cast<Instruction>(V); | ||||||||||
7674 | if (!I || !canConstantEvolve(I, L)) return nullptr; | ||||||||||
7675 | |||||||||||
7676 | if (PHINode *PN = dyn_cast<PHINode>(I)) | ||||||||||
7677 | return PN; | ||||||||||
7678 | |||||||||||
7679 | // Record non-constant instructions contained by the loop. | ||||||||||
7680 | DenseMap<Instruction *, PHINode *> PHIMap; | ||||||||||
7681 | return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); | ||||||||||
7682 | } | ||||||||||
7683 | |||||||||||
7684 | /// EvaluateExpression - Given an expression that passes the | ||||||||||
7685 | /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node | ||||||||||
7686 | /// in the loop has the value PHIVal. If we can't fold this expression for some | ||||||||||
7687 | /// reason, return null. | ||||||||||
7688 | static Constant *EvaluateExpression(Value *V, const Loop *L, | ||||||||||
7689 | DenseMap<Instruction *, Constant *> &Vals, | ||||||||||
7690 | const DataLayout &DL, | ||||||||||
7691 | const TargetLibraryInfo *TLI) { | ||||||||||
7692 | // Convenient constant check, but redundant for recursive calls. | ||||||||||
7693 | if (Constant *C = dyn_cast<Constant>(V)) return C; | ||||||||||
7694 | Instruction *I = dyn_cast<Instruction>(V); | ||||||||||
7695 | if (!I) return nullptr; | ||||||||||
7696 | |||||||||||
7697 | if (Constant *C = Vals.lookup(I)) return C; | ||||||||||
7698 | |||||||||||
7699 | // An instruction inside the loop depends on a value outside the loop that we | ||||||||||
7700 | // weren't given a mapping for, or a value such as a call inside the loop. | ||||||||||
7701 | if (!canConstantEvolve(I, L)) return nullptr; | ||||||||||
7702 | |||||||||||
7703 | // An unmapped PHI can be due to a branch or another loop inside this loop, | ||||||||||
7704 | // or due to this not being the initial iteration through a loop where we | ||||||||||
7705 | // couldn't compute the evolution of this particular PHI last time. | ||||||||||
7706 | if (isa<PHINode>(I)) return nullptr; | ||||||||||
7707 | |||||||||||
7708 | std::vector<Constant*> Operands(I->getNumOperands()); | ||||||||||
7709 | |||||||||||
7710 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { | ||||||||||
7711 | Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); | ||||||||||
7712 | if (!Operand) { | ||||||||||
7713 | Operands[i] = dyn_cast<Constant>(I->getOperand(i)); | ||||||||||
7714 | if (!Operands[i]) return nullptr; | ||||||||||
7715 | continue; | ||||||||||
7716 | } | ||||||||||
7717 | Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); | ||||||||||
7718 | Vals[Operand] = C; | ||||||||||
7719 | if (!C) return nullptr; | ||||||||||
7720 | Operands[i] = C; | ||||||||||
7721 | } | ||||||||||
7722 | |||||||||||
7723 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) | ||||||||||
7724 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], | ||||||||||
7725 | Operands[1], DL, TLI); | ||||||||||
7726 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { | ||||||||||
7727 | if (!LI->isVolatile()) | ||||||||||
7728 | return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); | ||||||||||
7729 | } | ||||||||||
7730 | return ConstantFoldInstOperands(I, Operands, DL, TLI); | ||||||||||
7731 | } | ||||||||||
7732 | |||||||||||
7733 | |||||||||||
7734 | // If every incoming value to PN except the one for BB is a specific Constant, | ||||||||||
7735 | // return that, else return nullptr. | ||||||||||
7736 | static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { | ||||||||||
7737 | Constant *IncomingVal = nullptr; | ||||||||||
7738 | |||||||||||
7739 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { | ||||||||||
7740 | if (PN->getIncomingBlock(i) == BB) | ||||||||||
7741 | continue; | ||||||||||
7742 | |||||||||||
7743 | auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); | ||||||||||
7744 | if (!CurrentVal) | ||||||||||
7745 | return nullptr; | ||||||||||
7746 | |||||||||||
7747 | if (IncomingVal != CurrentVal) { | ||||||||||
7748 | if (IncomingVal) | ||||||||||
7749 | return nullptr; | ||||||||||
7750 | IncomingVal = CurrentVal; | ||||||||||
7751 | } | ||||||||||
7752 | } | ||||||||||
7753 | |||||||||||
7754 | return IncomingVal; | ||||||||||
7755 | } | ||||||||||
7756 | |||||||||||
7757 | /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is | ||||||||||
7758 | /// in the header of its containing loop, we know the loop executes a | ||||||||||
7759 | /// constant number of times, and the PHI node is just a recurrence | ||||||||||
7760 | /// involving constants, fold it. | ||||||||||
7761 | Constant * | ||||||||||
7762 | ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, | ||||||||||
7763 | const APInt &BEs, | ||||||||||
7764 | const Loop *L) { | ||||||||||
7765 | auto I = ConstantEvolutionLoopExitValue.find(PN); | ||||||||||
7766 | if (I != ConstantEvolutionLoopExitValue.end()) | ||||||||||
7767 | return I->second; | ||||||||||
7768 | |||||||||||
7769 | if (BEs.ugt(MaxBruteForceIterations)) | ||||||||||
7770 | return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. | ||||||||||
7771 | |||||||||||
7772 | Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; | ||||||||||
7773 | |||||||||||
7774 | DenseMap<Instruction *, Constant *> CurrentIterVals; | ||||||||||
7775 | BasicBlock *Header = L->getHeader(); | ||||||||||
7776 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!" ) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7776, __PRETTY_FUNCTION__)); | ||||||||||
7777 | |||||||||||
7778 | BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
7779 | if (!Latch) | ||||||||||
7780 | return nullptr; | ||||||||||
7781 | |||||||||||
7782 | for (PHINode &PHI : Header->phis()) { | ||||||||||
7783 | if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) | ||||||||||
7784 | CurrentIterVals[&PHI] = StartCST; | ||||||||||
7785 | } | ||||||||||
7786 | if (!CurrentIterVals.count(PN)) | ||||||||||
7787 | return RetVal = nullptr; | ||||||||||
7788 | |||||||||||
7789 | Value *BEValue = PN->getIncomingValueForBlock(Latch); | ||||||||||
7790 | |||||||||||
7791 | // Execute the loop symbolically to determine the exit value. | ||||||||||
7792 | assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&((BEs.getActiveBits() < 8 * sizeof(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!" ) ? static_cast<void> (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7793, __PRETTY_FUNCTION__)) | ||||||||||
7793 | "BEs is <= MaxBruteForceIterations which is an 'unsigned'!")((BEs.getActiveBits() < 8 * sizeof(unsigned) && "BEs is <= MaxBruteForceIterations which is an 'unsigned'!" ) ? static_cast<void> (0) : __assert_fail ("BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && \"BEs is <= MaxBruteForceIterations which is an 'unsigned'!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7793, __PRETTY_FUNCTION__)); | ||||||||||
7794 | |||||||||||
7795 | unsigned NumIterations = BEs.getZExtValue(); // must be in range | ||||||||||
7796 | unsigned IterationNum = 0; | ||||||||||
7797 | const DataLayout &DL = getDataLayout(); | ||||||||||
7798 | for (; ; ++IterationNum) { | ||||||||||
7799 | if (IterationNum == NumIterations) | ||||||||||
7800 | return RetVal = CurrentIterVals[PN]; // Got exit value! | ||||||||||
7801 | |||||||||||
7802 | // Compute the value of the PHIs for the next iteration. | ||||||||||
7803 | // EvaluateExpression adds non-phi values to the CurrentIterVals map. | ||||||||||
7804 | DenseMap<Instruction *, Constant *> NextIterVals; | ||||||||||
7805 | Constant *NextPHI = | ||||||||||
7806 | EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); | ||||||||||
7807 | if (!NextPHI) | ||||||||||
7808 | return nullptr; // Couldn't evaluate! | ||||||||||
7809 | NextIterVals[PN] = NextPHI; | ||||||||||
7810 | |||||||||||
7811 | bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; | ||||||||||
7812 | |||||||||||
7813 | // Also evaluate the other PHI nodes. However, we don't get to stop if we | ||||||||||
7814 | // cease to be able to evaluate one of them or if they stop evolving, | ||||||||||
7815 | // because that doesn't necessarily prevent us from computing PN. | ||||||||||
7816 | SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; | ||||||||||
7817 | for (const auto &I : CurrentIterVals) { | ||||||||||
7818 | PHINode *PHI = dyn_cast<PHINode>(I.first); | ||||||||||
7819 | if (!PHI || PHI == PN || PHI->getParent() != Header) continue; | ||||||||||
7820 | PHIsToCompute.emplace_back(PHI, I.second); | ||||||||||
7821 | } | ||||||||||
7822 | // We use two distinct loops because EvaluateExpression may invalidate any | ||||||||||
7823 | // iterators into CurrentIterVals. | ||||||||||
7824 | for (const auto &I : PHIsToCompute) { | ||||||||||
7825 | PHINode *PHI = I.first; | ||||||||||
7826 | Constant *&NextPHI = NextIterVals[PHI]; | ||||||||||
7827 | if (!NextPHI) { // Not already computed. | ||||||||||
7828 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); | ||||||||||
7829 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); | ||||||||||
7830 | } | ||||||||||
7831 | if (NextPHI != I.second) | ||||||||||
7832 | StoppedEvolving = false; | ||||||||||
7833 | } | ||||||||||
7834 | |||||||||||
7835 | // If all entries in CurrentIterVals == NextIterVals then we can stop | ||||||||||
7836 | // iterating, the loop can't continue to change. | ||||||||||
7837 | if (StoppedEvolving) | ||||||||||
7838 | return RetVal = CurrentIterVals[PN]; | ||||||||||
7839 | |||||||||||
7840 | CurrentIterVals.swap(NextIterVals); | ||||||||||
7841 | } | ||||||||||
7842 | } | ||||||||||
7843 | |||||||||||
7844 | const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, | ||||||||||
7845 | Value *Cond, | ||||||||||
7846 | bool ExitWhen) { | ||||||||||
7847 | PHINode *PN = getConstantEvolvingPHI(Cond, L); | ||||||||||
7848 | if (!PN) return getCouldNotCompute(); | ||||||||||
7849 | |||||||||||
7850 | // If the loop is canonicalized, the PHI will have exactly two entries. | ||||||||||
7851 | // That's the only form we support here. | ||||||||||
7852 | if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); | ||||||||||
7853 | |||||||||||
7854 | DenseMap<Instruction *, Constant *> CurrentIterVals; | ||||||||||
7855 | BasicBlock *Header = L->getHeader(); | ||||||||||
7856 | assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!")((PN->getParent() == Header && "Can't evaluate PHI not in loop header!" ) ? static_cast<void> (0) : __assert_fail ("PN->getParent() == Header && \"Can't evaluate PHI not in loop header!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7856, __PRETTY_FUNCTION__)); | ||||||||||
7857 | |||||||||||
7858 | BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
7859 | assert(Latch && "Should follow from NumIncomingValues == 2!")((Latch && "Should follow from NumIncomingValues == 2!" ) ? static_cast<void> (0) : __assert_fail ("Latch && \"Should follow from NumIncomingValues == 2!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 7859, __PRETTY_FUNCTION__)); | ||||||||||
7860 | |||||||||||
7861 | for (PHINode &PHI : Header->phis()) { | ||||||||||
7862 | if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) | ||||||||||
7863 | CurrentIterVals[&PHI] = StartCST; | ||||||||||
7864 | } | ||||||||||
7865 | if (!CurrentIterVals.count(PN)) | ||||||||||
7866 | return getCouldNotCompute(); | ||||||||||
7867 | |||||||||||
7868 | // Okay, we find a PHI node that defines the trip count of this loop. Execute | ||||||||||
7869 | // the loop symbolically to determine when the condition gets a value of | ||||||||||
7870 | // "ExitWhen". | ||||||||||
7871 | unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. | ||||||||||
7872 | const DataLayout &DL = getDataLayout(); | ||||||||||
7873 | for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ | ||||||||||
7874 | auto *CondVal = dyn_cast_or_null<ConstantInt>( | ||||||||||
7875 | EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); | ||||||||||
7876 | |||||||||||
7877 | // Couldn't symbolically evaluate. | ||||||||||
7878 | if (!CondVal) return getCouldNotCompute(); | ||||||||||
7879 | |||||||||||
7880 | if (CondVal->getValue() == uint64_t(ExitWhen)) { | ||||||||||
7881 | ++NumBruteForceTripCountsComputed; | ||||||||||
7882 | return getConstant(Type::getInt32Ty(getContext()), IterationNum); | ||||||||||
7883 | } | ||||||||||
7884 | |||||||||||
7885 | // Update all the PHI nodes for the next iteration. | ||||||||||
7886 | DenseMap<Instruction *, Constant *> NextIterVals; | ||||||||||
7887 | |||||||||||
7888 | // Create a list of which PHIs we need to compute. We want to do this before | ||||||||||
7889 | // calling EvaluateExpression on them because that may invalidate iterators | ||||||||||
7890 | // into CurrentIterVals. | ||||||||||
7891 | SmallVector<PHINode *, 8> PHIsToCompute; | ||||||||||
7892 | for (const auto &I : CurrentIterVals) { | ||||||||||
7893 | PHINode *PHI = dyn_cast<PHINode>(I.first); | ||||||||||
7894 | if (!PHI || PHI->getParent() != Header) continue; | ||||||||||
7895 | PHIsToCompute.push_back(PHI); | ||||||||||
7896 | } | ||||||||||
7897 | for (PHINode *PHI : PHIsToCompute) { | ||||||||||
7898 | Constant *&NextPHI = NextIterVals[PHI]; | ||||||||||
7899 | if (NextPHI) continue; // Already computed! | ||||||||||
7900 | |||||||||||
7901 | Value *BEValue = PHI->getIncomingValueForBlock(Latch); | ||||||||||
7902 | NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); | ||||||||||
7903 | } | ||||||||||
7904 | CurrentIterVals.swap(NextIterVals); | ||||||||||
7905 | } | ||||||||||
7906 | |||||||||||
7907 | // Too many iterations were needed to evaluate. | ||||||||||
7908 | return getCouldNotCompute(); | ||||||||||
7909 | } | ||||||||||
7910 | |||||||||||
7911 | const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { | ||||||||||
7912 | SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = | ||||||||||
7913 | ValuesAtScopes[V]; | ||||||||||
7914 | // Check to see if we've folded this expression at this loop before. | ||||||||||
7915 | for (auto &LS : Values) | ||||||||||
7916 | if (LS.first == L) | ||||||||||
7917 | return LS.second ? LS.second : V; | ||||||||||
7918 | |||||||||||
7919 | Values.emplace_back(L, nullptr); | ||||||||||
7920 | |||||||||||
7921 | // Otherwise compute it. | ||||||||||
7922 | const SCEV *C = computeSCEVAtScope(V, L); | ||||||||||
7923 | for (auto &LS : reverse(ValuesAtScopes[V])) | ||||||||||
7924 | if (LS.first == L) { | ||||||||||
7925 | LS.second = C; | ||||||||||
7926 | break; | ||||||||||
7927 | } | ||||||||||
7928 | return C; | ||||||||||
7929 | } | ||||||||||
7930 | |||||||||||
7931 | /// This builds up a Constant using the ConstantExpr interface. That way, we | ||||||||||
7932 | /// will return Constants for objects which aren't represented by a | ||||||||||
7933 | /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. | ||||||||||
7934 | /// Returns NULL if the SCEV isn't representable as a Constant. | ||||||||||
7935 | static Constant *BuildConstantFromSCEV(const SCEV *V) { | ||||||||||
7936 | switch (static_cast<SCEVTypes>(V->getSCEVType())) { | ||||||||||
7937 | case scCouldNotCompute: | ||||||||||
7938 | case scAddRecExpr: | ||||||||||
7939 | break; | ||||||||||
7940 | case scConstant: | ||||||||||
7941 | return cast<SCEVConstant>(V)->getValue(); | ||||||||||
7942 | case scUnknown: | ||||||||||
7943 | return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); | ||||||||||
7944 | case scSignExtend: { | ||||||||||
7945 | const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); | ||||||||||
7946 | if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) | ||||||||||
7947 | return ConstantExpr::getSExt(CastOp, SS->getType()); | ||||||||||
7948 | break; | ||||||||||
7949 | } | ||||||||||
7950 | case scZeroExtend: { | ||||||||||
7951 | const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); | ||||||||||
7952 | if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) | ||||||||||
7953 | return ConstantExpr::getZExt(CastOp, SZ->getType()); | ||||||||||
7954 | break; | ||||||||||
7955 | } | ||||||||||
7956 | case scTruncate: { | ||||||||||
7957 | const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); | ||||||||||
7958 | if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) | ||||||||||
7959 | return ConstantExpr::getTrunc(CastOp, ST->getType()); | ||||||||||
7960 | break; | ||||||||||
7961 | } | ||||||||||
7962 | case scAddExpr: { | ||||||||||
7963 | const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); | ||||||||||
7964 | if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { | ||||||||||
7965 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { | ||||||||||
7966 | unsigned AS = PTy->getAddressSpace(); | ||||||||||
7967 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); | ||||||||||
7968 | C = ConstantExpr::getBitCast(C, DestPtrTy); | ||||||||||
7969 | } | ||||||||||
7970 | for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { | ||||||||||
7971 | Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); | ||||||||||
7972 | if (!C2) return nullptr; | ||||||||||
7973 | |||||||||||
7974 | // First pointer! | ||||||||||
7975 | if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { | ||||||||||
7976 | unsigned AS = C2->getType()->getPointerAddressSpace(); | ||||||||||
7977 | std::swap(C, C2); | ||||||||||
7978 | Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); | ||||||||||
7979 | // The offsets have been converted to bytes. We can add bytes to an | ||||||||||
7980 | // i8* by GEP with the byte count in the first index. | ||||||||||
7981 | C = ConstantExpr::getBitCast(C, DestPtrTy); | ||||||||||
7982 | } | ||||||||||
7983 | |||||||||||
7984 | // Don't bother trying to sum two pointers. We probably can't | ||||||||||
7985 | // statically compute a load that results from it anyway. | ||||||||||
7986 | if (C2->getType()->isPointerTy()) | ||||||||||
7987 | return nullptr; | ||||||||||
7988 | |||||||||||
7989 | if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { | ||||||||||
7990 | if (PTy->getElementType()->isStructTy()) | ||||||||||
7991 | C2 = ConstantExpr::getIntegerCast( | ||||||||||
7992 | C2, Type::getInt32Ty(C->getContext()), true); | ||||||||||
7993 | C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); | ||||||||||
7994 | } else | ||||||||||
7995 | C = ConstantExpr::getAdd(C, C2); | ||||||||||
7996 | } | ||||||||||
7997 | return C; | ||||||||||
7998 | } | ||||||||||
7999 | break; | ||||||||||
8000 | } | ||||||||||
8001 | case scMulExpr: { | ||||||||||
8002 | const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); | ||||||||||
8003 | if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { | ||||||||||
8004 | // Don't bother with pointers at all. | ||||||||||
8005 | if (C->getType()->isPointerTy()) return nullptr; | ||||||||||
8006 | for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { | ||||||||||
8007 | Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); | ||||||||||
8008 | if (!C2 || C2->getType()->isPointerTy()) return nullptr; | ||||||||||
8009 | C = ConstantExpr::getMul(C, C2); | ||||||||||
8010 | } | ||||||||||
8011 | return C; | ||||||||||
8012 | } | ||||||||||
8013 | break; | ||||||||||
8014 | } | ||||||||||
8015 | case scUDivExpr: { | ||||||||||
8016 | const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); | ||||||||||
8017 | if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) | ||||||||||
8018 | if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) | ||||||||||
8019 | if (LHS->getType() == RHS->getType()) | ||||||||||
8020 | return ConstantExpr::getUDiv(LHS, RHS); | ||||||||||
8021 | break; | ||||||||||
8022 | } | ||||||||||
8023 | case scSMaxExpr: | ||||||||||
8024 | case scUMaxExpr: | ||||||||||
8025 | case scSMinExpr: | ||||||||||
8026 | case scUMinExpr: | ||||||||||
8027 | break; // TODO: smax, umax, smin, umax. | ||||||||||
8028 | } | ||||||||||
8029 | return nullptr; | ||||||||||
8030 | } | ||||||||||
8031 | |||||||||||
8032 | const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { | ||||||||||
8033 | if (isa<SCEVConstant>(V)) return V; | ||||||||||
8034 | |||||||||||
8035 | // If this instruction is evolved from a constant-evolving PHI, compute the | ||||||||||
8036 | // exit value from the loop without using SCEVs. | ||||||||||
8037 | if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { | ||||||||||
8038 | if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { | ||||||||||
8039 | if (PHINode *PN = dyn_cast<PHINode>(I)) { | ||||||||||
8040 | const Loop *CurrLoop = this->LI[I->getParent()]; | ||||||||||
8041 | // Looking for loop exit value. | ||||||||||
8042 | if (CurrLoop && CurrLoop->getParentLoop() == L && | ||||||||||
8043 | PN->getParent() == CurrLoop->getHeader()) { | ||||||||||
8044 | // Okay, there is no closed form solution for the PHI node. Check | ||||||||||
8045 | // to see if the loop that contains it has a known backedge-taken | ||||||||||
8046 | // count. If so, we may be able to force computation of the exit | ||||||||||
8047 | // value. | ||||||||||
8048 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); | ||||||||||
8049 | // This trivial case can show up in some degenerate cases where | ||||||||||
8050 | // the incoming IR has not yet been fully simplified. | ||||||||||
8051 | if (BackedgeTakenCount->isZero()) { | ||||||||||
8052 | Value *InitValue = nullptr; | ||||||||||
8053 | bool MultipleInitValues = false; | ||||||||||
8054 | for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { | ||||||||||
8055 | if (!CurrLoop->contains(PN->getIncomingBlock(i))) { | ||||||||||
8056 | if (!InitValue) | ||||||||||
8057 | InitValue = PN->getIncomingValue(i); | ||||||||||
8058 | else if (InitValue != PN->getIncomingValue(i)) { | ||||||||||
8059 | MultipleInitValues = true; | ||||||||||
8060 | break; | ||||||||||
8061 | } | ||||||||||
8062 | } | ||||||||||
8063 | } | ||||||||||
8064 | if (!MultipleInitValues && InitValue) | ||||||||||
8065 | return getSCEV(InitValue); | ||||||||||
8066 | } | ||||||||||
8067 | // Do we have a loop invariant value flowing around the backedge | ||||||||||
8068 | // for a loop which must execute the backedge? | ||||||||||
8069 | if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && | ||||||||||
8070 | isKnownPositive(BackedgeTakenCount) && | ||||||||||
8071 | PN->getNumIncomingValues() == 2) { | ||||||||||
8072 | |||||||||||
8073 | unsigned InLoopPred = | ||||||||||
8074 | CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; | ||||||||||
8075 | Value *BackedgeVal = PN->getIncomingValue(InLoopPred); | ||||||||||
8076 | if (CurrLoop->isLoopInvariant(BackedgeVal)) | ||||||||||
8077 | return getSCEV(BackedgeVal); | ||||||||||
8078 | } | ||||||||||
8079 | if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { | ||||||||||
8080 | // Okay, we know how many times the containing loop executes. If | ||||||||||
8081 | // this is a constant evolving PHI node, get the final value at | ||||||||||
8082 | // the specified iteration number. | ||||||||||
8083 | Constant *RV = getConstantEvolutionLoopExitValue( | ||||||||||
8084 | PN, BTCC->getAPInt(), CurrLoop); | ||||||||||
8085 | if (RV) return getSCEV(RV); | ||||||||||
8086 | } | ||||||||||
8087 | } | ||||||||||
8088 | |||||||||||
8089 | // If there is a single-input Phi, evaluate it at our scope. If we can | ||||||||||
8090 | // prove that this replacement does not break LCSSA form, use new value. | ||||||||||
8091 | if (PN->getNumOperands() == 1) { | ||||||||||
8092 | const SCEV *Input = getSCEV(PN->getOperand(0)); | ||||||||||
8093 | const SCEV *InputAtScope = getSCEVAtScope(Input, L); | ||||||||||
8094 | // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, | ||||||||||
8095 | // for the simplest case just support constants. | ||||||||||
8096 | if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; | ||||||||||
8097 | } | ||||||||||
8098 | } | ||||||||||
8099 | |||||||||||
8100 | // Okay, this is an expression that we cannot symbolically evaluate | ||||||||||
8101 | // into a SCEV. Check to see if it's possible to symbolically evaluate | ||||||||||
8102 | // the arguments into constants, and if so, try to constant propagate the | ||||||||||
8103 | // result. This is particularly useful for computing loop exit values. | ||||||||||
8104 | if (CanConstantFold(I)) { | ||||||||||
8105 | SmallVector<Constant *, 4> Operands; | ||||||||||
8106 | bool MadeImprovement = false; | ||||||||||
8107 | for (Value *Op : I->operands()) { | ||||||||||
8108 | if (Constant *C = dyn_cast<Constant>(Op)) { | ||||||||||
8109 | Operands.push_back(C); | ||||||||||
8110 | continue; | ||||||||||
8111 | } | ||||||||||
8112 | |||||||||||
8113 | // If any of the operands is non-constant and if they are | ||||||||||
8114 | // non-integer and non-pointer, don't even try to analyze them | ||||||||||
8115 | // with scev techniques. | ||||||||||
8116 | if (!isSCEVable(Op->getType())) | ||||||||||
8117 | return V; | ||||||||||
8118 | |||||||||||
8119 | const SCEV *OrigV = getSCEV(Op); | ||||||||||
8120 | const SCEV *OpV = getSCEVAtScope(OrigV, L); | ||||||||||
8121 | MadeImprovement |= OrigV != OpV; | ||||||||||
8122 | |||||||||||
8123 | Constant *C = BuildConstantFromSCEV(OpV); | ||||||||||
8124 | if (!C) return V; | ||||||||||
8125 | if (C->getType() != Op->getType()) | ||||||||||
8126 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, | ||||||||||
8127 | Op->getType(), | ||||||||||
8128 | false), | ||||||||||
8129 | C, Op->getType()); | ||||||||||
8130 | Operands.push_back(C); | ||||||||||
8131 | } | ||||||||||
8132 | |||||||||||
8133 | // Check to see if getSCEVAtScope actually made an improvement. | ||||||||||
8134 | if (MadeImprovement) { | ||||||||||
8135 | Constant *C = nullptr; | ||||||||||
8136 | const DataLayout &DL = getDataLayout(); | ||||||||||
8137 | if (const CmpInst *CI = dyn_cast<CmpInst>(I)) | ||||||||||
8138 | C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], | ||||||||||
8139 | Operands[1], DL, &TLI); | ||||||||||
8140 | else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { | ||||||||||
8141 | if (!Load->isVolatile()) | ||||||||||
8142 | C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), | ||||||||||
8143 | DL); | ||||||||||
8144 | } else | ||||||||||
8145 | C = ConstantFoldInstOperands(I, Operands, DL, &TLI); | ||||||||||
8146 | if (!C) return V; | ||||||||||
8147 | return getSCEV(C); | ||||||||||
8148 | } | ||||||||||
8149 | } | ||||||||||
8150 | } | ||||||||||
8151 | |||||||||||
8152 | // This is some other type of SCEVUnknown, just return it. | ||||||||||
8153 | return V; | ||||||||||
8154 | } | ||||||||||
8155 | |||||||||||
8156 | if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { | ||||||||||
8157 | // Avoid performing the look-up in the common case where the specified | ||||||||||
8158 | // expression has no loop-variant portions. | ||||||||||
8159 | for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { | ||||||||||
8160 | const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); | ||||||||||
8161 | if (OpAtScope != Comm->getOperand(i)) { | ||||||||||
8162 | // Okay, at least one of these operands is loop variant but might be | ||||||||||
8163 | // foldable. Build a new instance of the folded commutative expression. | ||||||||||
8164 | SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), | ||||||||||
8165 | Comm->op_begin()+i); | ||||||||||
8166 | NewOps.push_back(OpAtScope); | ||||||||||
8167 | |||||||||||
8168 | for (++i; i != e; ++i) { | ||||||||||
8169 | OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); | ||||||||||
8170 | NewOps.push_back(OpAtScope); | ||||||||||
8171 | } | ||||||||||
8172 | if (isa<SCEVAddExpr>(Comm)) | ||||||||||
8173 | return getAddExpr(NewOps, Comm->getNoWrapFlags()); | ||||||||||
8174 | if (isa<SCEVMulExpr>(Comm)) | ||||||||||
8175 | return getMulExpr(NewOps, Comm->getNoWrapFlags()); | ||||||||||
8176 | if (isa<SCEVMinMaxExpr>(Comm)) | ||||||||||
8177 | return getMinMaxExpr(Comm->getSCEVType(), NewOps); | ||||||||||
8178 | llvm_unreachable("Unknown commutative SCEV type!")::llvm::llvm_unreachable_internal("Unknown commutative SCEV type!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8178); | ||||||||||
8179 | } | ||||||||||
8180 | } | ||||||||||
8181 | // If we got here, all operands are loop invariant. | ||||||||||
8182 | return Comm; | ||||||||||
8183 | } | ||||||||||
8184 | |||||||||||
8185 | if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { | ||||||||||
8186 | const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); | ||||||||||
8187 | const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); | ||||||||||
8188 | if (LHS == Div->getLHS() && RHS == Div->getRHS()) | ||||||||||
8189 | return Div; // must be loop invariant | ||||||||||
8190 | return getUDivExpr(LHS, RHS); | ||||||||||
8191 | } | ||||||||||
8192 | |||||||||||
8193 | // If this is a loop recurrence for a loop that does not contain L, then we | ||||||||||
8194 | // are dealing with the final value computed by the loop. | ||||||||||
8195 | if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { | ||||||||||
8196 | // First, attempt to evaluate each operand. | ||||||||||
8197 | // Avoid performing the look-up in the common case where the specified | ||||||||||
8198 | // expression has no loop-variant portions. | ||||||||||
8199 | for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { | ||||||||||
8200 | const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); | ||||||||||
8201 | if (OpAtScope == AddRec->getOperand(i)) | ||||||||||
8202 | continue; | ||||||||||
8203 | |||||||||||
8204 | // Okay, at least one of these operands is loop variant but might be | ||||||||||
8205 | // foldable. Build a new instance of the folded commutative expression. | ||||||||||
8206 | SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), | ||||||||||
8207 | AddRec->op_begin()+i); | ||||||||||
8208 | NewOps.push_back(OpAtScope); | ||||||||||
8209 | for (++i; i != e; ++i) | ||||||||||
8210 | NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); | ||||||||||
8211 | |||||||||||
8212 | const SCEV *FoldedRec = | ||||||||||
8213 | getAddRecExpr(NewOps, AddRec->getLoop(), | ||||||||||
8214 | AddRec->getNoWrapFlags(SCEV::FlagNW)); | ||||||||||
8215 | AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); | ||||||||||
8216 | // The addrec may be folded to a nonrecurrence, for example, if the | ||||||||||
8217 | // induction variable is multiplied by zero after constant folding. Go | ||||||||||
8218 | // ahead and return the folded value. | ||||||||||
8219 | if (!AddRec) | ||||||||||
8220 | return FoldedRec; | ||||||||||
8221 | break; | ||||||||||
8222 | } | ||||||||||
8223 | |||||||||||
8224 | // If the scope is outside the addrec's loop, evaluate it by using the | ||||||||||
8225 | // loop exit value of the addrec. | ||||||||||
8226 | if (!AddRec->getLoop()->contains(L)) { | ||||||||||
8227 | // To evaluate this recurrence, we need to know how many times the AddRec | ||||||||||
8228 | // loop iterates. Compute this now. | ||||||||||
8229 | const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); | ||||||||||
8230 | if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; | ||||||||||
8231 | |||||||||||
8232 | // Then, evaluate the AddRec. | ||||||||||
8233 | return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); | ||||||||||
8234 | } | ||||||||||
8235 | |||||||||||
8236 | return AddRec; | ||||||||||
8237 | } | ||||||||||
8238 | |||||||||||
8239 | if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { | ||||||||||
8240 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); | ||||||||||
8241 | if (Op == Cast->getOperand()) | ||||||||||
8242 | return Cast; // must be loop invariant | ||||||||||
8243 | return getZeroExtendExpr(Op, Cast->getType()); | ||||||||||
8244 | } | ||||||||||
8245 | |||||||||||
8246 | if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { | ||||||||||
8247 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); | ||||||||||
8248 | if (Op == Cast->getOperand()) | ||||||||||
8249 | return Cast; // must be loop invariant | ||||||||||
8250 | return getSignExtendExpr(Op, Cast->getType()); | ||||||||||
8251 | } | ||||||||||
8252 | |||||||||||
8253 | if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { | ||||||||||
8254 | const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); | ||||||||||
8255 | if (Op == Cast->getOperand()) | ||||||||||
8256 | return Cast; // must be loop invariant | ||||||||||
8257 | return getTruncateExpr(Op, Cast->getType()); | ||||||||||
8258 | } | ||||||||||
8259 | |||||||||||
8260 | llvm_unreachable("Unknown SCEV type!")::llvm::llvm_unreachable_internal("Unknown SCEV type!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8260); | ||||||||||
8261 | } | ||||||||||
8262 | |||||||||||
8263 | const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { | ||||||||||
8264 | return getSCEVAtScope(getSCEV(V), L); | ||||||||||
8265 | } | ||||||||||
8266 | |||||||||||
8267 | const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { | ||||||||||
8268 | if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) | ||||||||||
8269 | return stripInjectiveFunctions(ZExt->getOperand()); | ||||||||||
8270 | if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) | ||||||||||
8271 | return stripInjectiveFunctions(SExt->getOperand()); | ||||||||||
8272 | return S; | ||||||||||
8273 | } | ||||||||||
8274 | |||||||||||
8275 | /// Finds the minimum unsigned root of the following equation: | ||||||||||
8276 | /// | ||||||||||
8277 | /// A * X = B (mod N) | ||||||||||
8278 | /// | ||||||||||
8279 | /// where N = 2^BW and BW is the common bit width of A and B. The signedness of | ||||||||||
8280 | /// A and B isn't important. | ||||||||||
8281 | /// | ||||||||||
8282 | /// If the equation does not have a solution, SCEVCouldNotCompute is returned. | ||||||||||
8283 | static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, | ||||||||||
8284 | ScalarEvolution &SE) { | ||||||||||
8285 | uint32_t BW = A.getBitWidth(); | ||||||||||
8286 | assert(BW == SE.getTypeSizeInBits(B->getType()))((BW == SE.getTypeSizeInBits(B->getType())) ? static_cast< void> (0) : __assert_fail ("BW == SE.getTypeSizeInBits(B->getType())" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8286, __PRETTY_FUNCTION__)); | ||||||||||
8287 | assert(A != 0 && "A must be non-zero.")((A != 0 && "A must be non-zero.") ? static_cast<void > (0) : __assert_fail ("A != 0 && \"A must be non-zero.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8287, __PRETTY_FUNCTION__)); | ||||||||||
8288 | |||||||||||
8289 | // 1. D = gcd(A, N) | ||||||||||
8290 | // | ||||||||||
8291 | // The gcd of A and N may have only one prime factor: 2. The number of | ||||||||||
8292 | // trailing zeros in A is its multiplicity | ||||||||||
8293 | uint32_t Mult2 = A.countTrailingZeros(); | ||||||||||
8294 | // D = 2^Mult2 | ||||||||||
8295 | |||||||||||
8296 | // 2. Check if B is divisible by D. | ||||||||||
8297 | // | ||||||||||
8298 | // B is divisible by D if and only if the multiplicity of prime factor 2 for B | ||||||||||
8299 | // is not less than multiplicity of this prime factor for D. | ||||||||||
8300 | if (SE.GetMinTrailingZeros(B) < Mult2) | ||||||||||
8301 | return SE.getCouldNotCompute(); | ||||||||||
8302 | |||||||||||
8303 | // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic | ||||||||||
8304 | // modulo (N / D). | ||||||||||
8305 | // | ||||||||||
8306 | // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent | ||||||||||
8307 | // (N / D) in general. The inverse itself always fits into BW bits, though, | ||||||||||
8308 | // so we immediately truncate it. | ||||||||||
8309 | APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D | ||||||||||
8310 | APInt Mod(BW + 1, 0); | ||||||||||
8311 | Mod.setBit(BW - Mult2); // Mod = N / D | ||||||||||
8312 | APInt I = AD.multiplicativeInverse(Mod).trunc(BW); | ||||||||||
8313 | |||||||||||
8314 | // 4. Compute the minimum unsigned root of the equation: | ||||||||||
8315 | // I * (B / D) mod (N / D) | ||||||||||
8316 | // To simplify the computation, we factor out the divide by D: | ||||||||||
8317 | // (I * B mod N) / D | ||||||||||
8318 | const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); | ||||||||||
8319 | return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); | ||||||||||
8320 | } | ||||||||||
8321 | |||||||||||
8322 | /// For a given quadratic addrec, generate coefficients of the corresponding | ||||||||||
8323 | /// quadratic equation, multiplied by a common value to ensure that they are | ||||||||||
8324 | /// integers. | ||||||||||
8325 | /// The returned value is a tuple { A, B, C, M, BitWidth }, where | ||||||||||
8326 | /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C | ||||||||||
8327 | /// were multiplied by, and BitWidth is the bit width of the original addrec | ||||||||||
8328 | /// coefficients. | ||||||||||
8329 | /// This function returns None if the addrec coefficients are not compile- | ||||||||||
8330 | /// time constants. | ||||||||||
8331 | static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> | ||||||||||
8332 | GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { | ||||||||||
8333 | assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!")((AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!" ) ? static_cast<void> (0) : __assert_fail ("AddRec->getNumOperands() == 3 && \"This is not a quadratic chrec!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8333, __PRETTY_FUNCTION__)); | ||||||||||
8334 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); | ||||||||||
8335 | const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); | ||||||||||
8336 | const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); | ||||||||||
8337 | LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: " << *AddRec << '\n'; } } while (false) | ||||||||||
8338 | << *AddRec << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": analyzing quadratic addrec: " << *AddRec << '\n'; } } while (false); | ||||||||||
8339 | |||||||||||
8340 | // We currently can only solve this if the coefficients are constants. | ||||||||||
8341 | if (!LC || !MC || !NC) { | ||||||||||
8342 | LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": coefficients are not constant\n" ; } } while (false); | ||||||||||
8343 | return None; | ||||||||||
8344 | } | ||||||||||
8345 | |||||||||||
8346 | APInt L = LC->getAPInt(); | ||||||||||
8347 | APInt M = MC->getAPInt(); | ||||||||||
8348 | APInt N = NC->getAPInt(); | ||||||||||
8349 | assert(!N.isNullValue() && "This is not a quadratic addrec")((!N.isNullValue() && "This is not a quadratic addrec" ) ? static_cast<void> (0) : __assert_fail ("!N.isNullValue() && \"This is not a quadratic addrec\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8349, __PRETTY_FUNCTION__)); | ||||||||||
8350 | |||||||||||
8351 | unsigned BitWidth = LC->getAPInt().getBitWidth(); | ||||||||||
8352 | unsigned NewWidth = BitWidth + 1; | ||||||||||
8353 | LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: " << BitWidth << '\n'; } } while (false) | ||||||||||
8354 | << BitWidth << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": addrec coeff bw: " << BitWidth << '\n'; } } while (false); | ||||||||||
8355 | // The sign-extension (as opposed to a zero-extension) here matches the | ||||||||||
8356 | // extension used in SolveQuadraticEquationWrap (with the same motivation). | ||||||||||
8357 | N = N.sext(NewWidth); | ||||||||||
8358 | M = M.sext(NewWidth); | ||||||||||
8359 | L = L.sext(NewWidth); | ||||||||||
8360 | |||||||||||
8361 | // The increments are M, M+N, M+2N, ..., so the accumulated values are | ||||||||||
8362 | // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, | ||||||||||
8363 | // L+M, L+2M+N, L+3M+3N, ... | ||||||||||
8364 | // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. | ||||||||||
8365 | // | ||||||||||
8366 | // The equation Acc = 0 is then | ||||||||||
8367 | // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. | ||||||||||
8368 | // In a quadratic form it becomes: | ||||||||||
8369 | // N n^2 + (2M-N) n + 2L = 0. | ||||||||||
8370 | |||||||||||
8371 | APInt A = N; | ||||||||||
8372 | APInt B = 2 * M - A; | ||||||||||
8373 | APInt C = 2 * L; | ||||||||||
8374 | APInt T = APInt(NewWidth, 2); | ||||||||||
8375 | LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << Bdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": equation " << A << "x^2 + " << B << "x + " << C << ", coeff bw: " << NewWidth << ", multiplied by " << T << '\n'; } } while (false) | ||||||||||
8376 | << "x + " << C << ", coeff bw: " << NewWidthdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": equation " << A << "x^2 + " << B << "x + " << C << ", coeff bw: " << NewWidth << ", multiplied by " << T << '\n'; } } while (false) | ||||||||||
8377 | << ", multiplied by " << T << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": equation " << A << "x^2 + " << B << "x + " << C << ", coeff bw: " << NewWidth << ", multiplied by " << T << '\n'; } } while (false); | ||||||||||
8378 | return std::make_tuple(A, B, C, T, BitWidth); | ||||||||||
8379 | } | ||||||||||
8380 | |||||||||||
8381 | /// Helper function to compare optional APInts: | ||||||||||
8382 | /// (a) if X and Y both exist, return min(X, Y), | ||||||||||
8383 | /// (b) if neither X nor Y exist, return None, | ||||||||||
8384 | /// (c) if exactly one of X and Y exists, return that value. | ||||||||||
8385 | static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { | ||||||||||
8386 | if (X.hasValue() && Y.hasValue()) { | ||||||||||
8387 | unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); | ||||||||||
8388 | APInt XW = X->sextOrSelf(W); | ||||||||||
8389 | APInt YW = Y->sextOrSelf(W); | ||||||||||
8390 | return XW.slt(YW) ? *X : *Y; | ||||||||||
8391 | } | ||||||||||
8392 | if (!X.hasValue() && !Y.hasValue()) | ||||||||||
8393 | return None; | ||||||||||
8394 | return X.hasValue() ? *X : *Y; | ||||||||||
8395 | } | ||||||||||
8396 | |||||||||||
8397 | /// Helper function to truncate an optional APInt to a given BitWidth. | ||||||||||
8398 | /// When solving addrec-related equations, it is preferable to return a value | ||||||||||
8399 | /// that has the same bit width as the original addrec's coefficients. If the | ||||||||||
8400 | /// solution fits in the original bit width, truncate it (except for i1). | ||||||||||
8401 | /// Returning a value of a different bit width may inhibit some optimizations. | ||||||||||
8402 | /// | ||||||||||
8403 | /// In general, a solution to a quadratic equation generated from an addrec | ||||||||||
8404 | /// may require BW+1 bits, where BW is the bit width of the addrec's | ||||||||||
8405 | /// coefficients. The reason is that the coefficients of the quadratic | ||||||||||
8406 | /// equation are BW+1 bits wide (to avoid truncation when converting from | ||||||||||
8407 | /// the addrec to the equation). | ||||||||||
8408 | static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { | ||||||||||
8409 | if (!X.hasValue()) | ||||||||||
8410 | return None; | ||||||||||
8411 | unsigned W = X->getBitWidth(); | ||||||||||
8412 | if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) | ||||||||||
8413 | return X->trunc(BitWidth); | ||||||||||
8414 | return X; | ||||||||||
8415 | } | ||||||||||
8416 | |||||||||||
8417 | /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n | ||||||||||
8418 | /// iterations. The values L, M, N are assumed to be signed, and they | ||||||||||
8419 | /// should all have the same bit widths. | ||||||||||
8420 | /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, | ||||||||||
8421 | /// where BW is the bit width of the addrec's coefficients. | ||||||||||
8422 | /// If the calculated value is a BW-bit integer (for BW > 1), it will be | ||||||||||
8423 | /// returned as such, otherwise the bit width of the returned value may | ||||||||||
8424 | /// be greater than BW. | ||||||||||
8425 | /// | ||||||||||
8426 | /// This function returns None if | ||||||||||
8427 | /// (a) the addrec coefficients are not constant, or | ||||||||||
8428 | /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases | ||||||||||
8429 | /// like x^2 = 5, no integer solutions exist, in other cases an integer | ||||||||||
8430 | /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. | ||||||||||
8431 | static Optional<APInt> | ||||||||||
8432 | SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { | ||||||||||
8433 | APInt A, B, C, M; | ||||||||||
8434 | unsigned BitWidth; | ||||||||||
8435 | auto T = GetQuadraticEquation(AddRec); | ||||||||||
8436 | if (!T.hasValue()) | ||||||||||
8437 | return None; | ||||||||||
8438 | |||||||||||
8439 | std::tie(A, B, C, M, BitWidth) = *T; | ||||||||||
8440 | LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": solving for unsigned overflow\n" ; } } while (false); | ||||||||||
8441 | Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); | ||||||||||
8442 | if (!X.hasValue()) | ||||||||||
8443 | return None; | ||||||||||
8444 | |||||||||||
8445 | ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); | ||||||||||
8446 | ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); | ||||||||||
8447 | if (!V->isZero()) | ||||||||||
8448 | return None; | ||||||||||
8449 | |||||||||||
8450 | return TruncIfPossible(X, BitWidth); | ||||||||||
8451 | } | ||||||||||
8452 | |||||||||||
8453 | /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n | ||||||||||
8454 | /// iterations. The values M, N are assumed to be signed, and they | ||||||||||
8455 | /// should all have the same bit widths. | ||||||||||
8456 | /// Find the least n such that c(n) does not belong to the given range, | ||||||||||
8457 | /// while c(n-1) does. | ||||||||||
8458 | /// | ||||||||||
8459 | /// This function returns None if | ||||||||||
8460 | /// (a) the addrec coefficients are not constant, or | ||||||||||
8461 | /// (b) SolveQuadraticEquationWrap was unable to find a solution for the | ||||||||||
8462 | /// bounds of the range. | ||||||||||
8463 | static Optional<APInt> | ||||||||||
8464 | SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, | ||||||||||
8465 | const ConstantRange &Range, ScalarEvolution &SE) { | ||||||||||
8466 | assert(AddRec->getOperand(0)->isZero() &&((AddRec->getOperand(0)->isZero() && "Starting value of addrec should be 0" ) ? static_cast<void> (0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8467, __PRETTY_FUNCTION__)) | ||||||||||
8467 | "Starting value of addrec should be 0")((AddRec->getOperand(0)->isZero() && "Starting value of addrec should be 0" ) ? static_cast<void> (0) : __assert_fail ("AddRec->getOperand(0)->isZero() && \"Starting value of addrec should be 0\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8467, __PRETTY_FUNCTION__)); | ||||||||||
8468 | LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": solving boundary crossing for range " << Range << ", addrec " << *AddRec << '\n'; } } while (false) | ||||||||||
8469 | << Range << ", addrec " << *AddRec << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << __func__ << ": solving boundary crossing for range " << Range << ", addrec " << *AddRec << '\n'; } } while (false); | ||||||||||
8470 | // This case is handled in getNumIterationsInRange. Here we can assume that | ||||||||||
8471 | // we start in the range. | ||||||||||
8472 | assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&((Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType ()), 0)) && "Addrec's initial value should be in range" ) ? static_cast<void> (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8473, __PRETTY_FUNCTION__)) | ||||||||||
8473 | "Addrec's initial value should be in range")((Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType ()), 0)) && "Addrec's initial value should be in range" ) ? static_cast<void> (0) : __assert_fail ("Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && \"Addrec's initial value should be in range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8473, __PRETTY_FUNCTION__)); | ||||||||||
8474 | |||||||||||
8475 | APInt A, B, C, M; | ||||||||||
8476 | unsigned BitWidth; | ||||||||||
8477 | auto T = GetQuadraticEquation(AddRec); | ||||||||||
8478 | if (!T.hasValue()) | ||||||||||
8479 | return None; | ||||||||||
8480 | |||||||||||
8481 | // Be careful about the return value: there can be two reasons for not | ||||||||||
8482 | // returning an actual number. First, if no solutions to the equations | ||||||||||
8483 | // were found, and second, if the solutions don't leave the given range. | ||||||||||
8484 | // The first case means that the actual solution is "unknown", the second | ||||||||||
8485 | // means that it's known, but not valid. If the solution is unknown, we | ||||||||||
8486 | // cannot make any conclusions. | ||||||||||
8487 | // Return a pair: the optional solution and a flag indicating if the | ||||||||||
8488 | // solution was found. | ||||||||||
8489 | auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { | ||||||||||
8490 | // Solve for signed overflow and unsigned overflow, pick the lower | ||||||||||
8491 | // solution. | ||||||||||
8492 | LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: checking boundary " << Bound << " (before multiplying by " << M << ")\n"; } } while (false) | ||||||||||
8493 | << Bound << " (before multiplying by " << M << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: checking boundary " << Bound << " (before multiplying by " << M << ")\n"; } } while (false); | ||||||||||
8494 | Bound *= M; // The quadratic equation multiplier. | ||||||||||
8495 | |||||||||||
8496 | Optional<APInt> SO = None; | ||||||||||
8497 | if (BitWidth > 1) { | ||||||||||
8498 | LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for " "signed overflow\n"; } } while (false) | ||||||||||
8499 | "signed overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for " "signed overflow\n"; } } while (false); | ||||||||||
8500 | SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); | ||||||||||
8501 | } | ||||||||||
8502 | LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for " "unsigned overflow\n"; } } while (false) | ||||||||||
8503 | "unsigned overflow\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { dbgs() << "SolveQuadraticAddRecRange: solving for " "unsigned overflow\n"; } } while (false); | ||||||||||
8504 | Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, | ||||||||||
8505 | BitWidth+1); | ||||||||||
8506 | |||||||||||
8507 | auto LeavesRange = [&] (const APInt &X) { | ||||||||||
8508 | ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); | ||||||||||
8509 | ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); | ||||||||||
8510 | if (Range.contains(V0->getValue())) | ||||||||||
8511 | return false; | ||||||||||
8512 | // X should be at least 1, so X-1 is non-negative. | ||||||||||
8513 | ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); | ||||||||||
8514 | ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); | ||||||||||
8515 | if (Range.contains(V1->getValue())) | ||||||||||
8516 | return true; | ||||||||||
8517 | return false; | ||||||||||
8518 | }; | ||||||||||
8519 | |||||||||||
8520 | // If SolveQuadraticEquationWrap returns None, it means that there can | ||||||||||
8521 | // be a solution, but the function failed to find it. We cannot treat it | ||||||||||
8522 | // as "no solution". | ||||||||||
8523 | if (!SO.hasValue() || !UO.hasValue()) | ||||||||||
8524 | return { None, false }; | ||||||||||
8525 | |||||||||||
8526 | // Check the smaller value first to see if it leaves the range. | ||||||||||
8527 | // At this point, both SO and UO must have values. | ||||||||||
8528 | Optional<APInt> Min = MinOptional(SO, UO); | ||||||||||
8529 | if (LeavesRange(*Min)) | ||||||||||
8530 | return { Min, true }; | ||||||||||
8531 | Optional<APInt> Max = Min == SO ? UO : SO; | ||||||||||
8532 | if (LeavesRange(*Max)) | ||||||||||
8533 | return { Max, true }; | ||||||||||
8534 | |||||||||||
8535 | // Solutions were found, but were eliminated, hence the "true". | ||||||||||
8536 | return { None, true }; | ||||||||||
8537 | }; | ||||||||||
8538 | |||||||||||
8539 | std::tie(A, B, C, M, BitWidth) = *T; | ||||||||||
8540 | // Lower bound is inclusive, subtract 1 to represent the exiting value. | ||||||||||
8541 | APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; | ||||||||||
8542 | APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); | ||||||||||
8543 | auto SL = SolveForBoundary(Lower); | ||||||||||
8544 | auto SU = SolveForBoundary(Upper); | ||||||||||
8545 | // If any of the solutions was unknown, no meaninigful conclusions can | ||||||||||
8546 | // be made. | ||||||||||
8547 | if (!SL.second || !SU.second) | ||||||||||
8548 | return None; | ||||||||||
8549 | |||||||||||
8550 | // Claim: The correct solution is not some value between Min and Max. | ||||||||||
8551 | // | ||||||||||
8552 | // Justification: Assuming that Min and Max are different values, one of | ||||||||||
8553 | // them is when the first signed overflow happens, the other is when the | ||||||||||
8554 | // first unsigned overflow happens. Crossing the range boundary is only | ||||||||||
8555 | // possible via an overflow (treating 0 as a special case of it, modeling | ||||||||||
8556 | // an overflow as crossing k*2^W for some k). | ||||||||||
8557 | // | ||||||||||
8558 | // The interesting case here is when Min was eliminated as an invalid | ||||||||||
8559 | // solution, but Max was not. The argument is that if there was another | ||||||||||
8560 | // overflow between Min and Max, it would also have been eliminated if | ||||||||||
8561 | // it was considered. | ||||||||||
8562 | // | ||||||||||
8563 | // For a given boundary, it is possible to have two overflows of the same | ||||||||||
8564 | // type (signed/unsigned) without having the other type in between: this | ||||||||||
8565 | // can happen when the vertex of the parabola is between the iterations | ||||||||||
8566 | // corresponding to the overflows. This is only possible when the two | ||||||||||
8567 | // overflows cross k*2^W for the same k. In such case, if the second one | ||||||||||
8568 | // left the range (and was the first one to do so), the first overflow | ||||||||||
8569 | // would have to enter the range, which would mean that either we had left | ||||||||||
8570 | // the range before or that we started outside of it. Both of these cases | ||||||||||
8571 | // are contradictions. | ||||||||||
8572 | // | ||||||||||
8573 | // Claim: In the case where SolveForBoundary returns None, the correct | ||||||||||
8574 | // solution is not some value between the Max for this boundary and the | ||||||||||
8575 | // Min of the other boundary. | ||||||||||
8576 | // | ||||||||||
8577 | // Justification: Assume that we had such Max_A and Min_B corresponding | ||||||||||
8578 | // to range boundaries A and B and such that Max_A < Min_B. If there was | ||||||||||
8579 | // a solution between Max_A and Min_B, it would have to be caused by an | ||||||||||
8580 | // overflow corresponding to either A or B. It cannot correspond to B, | ||||||||||
8581 | // since Min_B is the first occurrence of such an overflow. If it | ||||||||||
8582 | // corresponded to A, it would have to be either a signed or an unsigned | ||||||||||
8583 | // overflow that is larger than both eliminated overflows for A. But | ||||||||||
8584 | // between the eliminated overflows and this overflow, the values would | ||||||||||
8585 | // cover the entire value space, thus crossing the other boundary, which | ||||||||||
8586 | // is a contradiction. | ||||||||||
8587 | |||||||||||
8588 | return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); | ||||||||||
8589 | } | ||||||||||
8590 | |||||||||||
8591 | ScalarEvolution::ExitLimit | ||||||||||
8592 | ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, | ||||||||||
8593 | bool AllowPredicates) { | ||||||||||
8594 | |||||||||||
8595 | // This is only used for loops with a "x != y" exit test. The exit condition | ||||||||||
8596 | // is now expressed as a single expression, V = x-y. So the exit test is | ||||||||||
8597 | // effectively V != 0. We know and take advantage of the fact that this | ||||||||||
8598 | // expression only being used in a comparison by zero context. | ||||||||||
8599 | |||||||||||
8600 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; | ||||||||||
8601 | // If the value is a constant | ||||||||||
8602 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { | ||||||||||
8603 | // If the value is already zero, the branch will execute zero times. | ||||||||||
8604 | if (C->getValue()->isZero()) return C; | ||||||||||
8605 | return getCouldNotCompute(); // Otherwise it will loop infinitely. | ||||||||||
8606 | } | ||||||||||
8607 | |||||||||||
8608 | const SCEVAddRecExpr *AddRec = | ||||||||||
8609 | dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); | ||||||||||
8610 | |||||||||||
8611 | if (!AddRec && AllowPredicates) | ||||||||||
8612 | // Try to make this an AddRec using runtime tests, in the first X | ||||||||||
8613 | // iterations of this loop, where X is the SCEV expression found by the | ||||||||||
8614 | // algorithm below. | ||||||||||
8615 | AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); | ||||||||||
8616 | |||||||||||
8617 | if (!AddRec || AddRec->getLoop() != L) | ||||||||||
8618 | return getCouldNotCompute(); | ||||||||||
8619 | |||||||||||
8620 | // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of | ||||||||||
8621 | // the quadratic equation to solve it. | ||||||||||
8622 | if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { | ||||||||||
8623 | // We can only use this value if the chrec ends up with an exact zero | ||||||||||
8624 | // value at this index. When solving for "X*X != 5", for example, we | ||||||||||
8625 | // should not accept a root of 2. | ||||||||||
8626 | if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { | ||||||||||
8627 | const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); | ||||||||||
8628 | return ExitLimit(R, R, false, Predicates); | ||||||||||
8629 | } | ||||||||||
8630 | return getCouldNotCompute(); | ||||||||||
8631 | } | ||||||||||
8632 | |||||||||||
8633 | // Otherwise we can only handle this if it is affine. | ||||||||||
8634 | if (!AddRec->isAffine()) | ||||||||||
8635 | return getCouldNotCompute(); | ||||||||||
8636 | |||||||||||
8637 | // If this is an affine expression, the execution count of this branch is | ||||||||||
8638 | // the minimum unsigned root of the following equation: | ||||||||||
8639 | // | ||||||||||
8640 | // Start + Step*N = 0 (mod 2^BW) | ||||||||||
8641 | // | ||||||||||
8642 | // equivalent to: | ||||||||||
8643 | // | ||||||||||
8644 | // Step*N = -Start (mod 2^BW) | ||||||||||
8645 | // | ||||||||||
8646 | // where BW is the common bit width of Start and Step. | ||||||||||
8647 | |||||||||||
8648 | // Get the initial value for the loop. | ||||||||||
8649 | const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); | ||||||||||
8650 | const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); | ||||||||||
8651 | |||||||||||
8652 | // For now we handle only constant steps. | ||||||||||
8653 | // | ||||||||||
8654 | // TODO: Handle a nonconstant Step given AddRec<NUW>. If the | ||||||||||
8655 | // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap | ||||||||||
8656 | // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. | ||||||||||
8657 | // We have not yet seen any such cases. | ||||||||||
8658 | const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); | ||||||||||
8659 | if (!StepC || StepC->getValue()->isZero()) | ||||||||||
8660 | return getCouldNotCompute(); | ||||||||||
8661 | |||||||||||
8662 | // For positive steps (counting up until unsigned overflow): | ||||||||||
8663 | // N = -Start/Step (as unsigned) | ||||||||||
8664 | // For negative steps (counting down to zero): | ||||||||||
8665 | // N = Start/-Step | ||||||||||
8666 | // First compute the unsigned distance from zero in the direction of Step. | ||||||||||
8667 | bool CountDown = StepC->getAPInt().isNegative(); | ||||||||||
8668 | const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); | ||||||||||
8669 | |||||||||||
8670 | // Handle unitary steps, which cannot wraparound. | ||||||||||
8671 | // 1*N = -Start; -1*N = Start (mod 2^BW), so: | ||||||||||
8672 | // N = Distance (as unsigned) | ||||||||||
8673 | if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { | ||||||||||
8674 | APInt MaxBECount = getUnsignedRangeMax(Distance); | ||||||||||
8675 | |||||||||||
8676 | // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, | ||||||||||
8677 | // we end up with a loop whose backedge-taken count is n - 1. Detect this | ||||||||||
8678 | // case, and see if we can improve the bound. | ||||||||||
8679 | // | ||||||||||
8680 | // Explicitly handling this here is necessary because getUnsignedRange | ||||||||||
8681 | // isn't context-sensitive; it doesn't know that we only care about the | ||||||||||
8682 | // range inside the loop. | ||||||||||
8683 | const SCEV *Zero = getZero(Distance->getType()); | ||||||||||
8684 | const SCEV *One = getOne(Distance->getType()); | ||||||||||
8685 | const SCEV *DistancePlusOne = getAddExpr(Distance, One); | ||||||||||
8686 | if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { | ||||||||||
8687 | // If Distance + 1 doesn't overflow, we can compute the maximum distance | ||||||||||
8688 | // as "unsigned_max(Distance + 1) - 1". | ||||||||||
8689 | ConstantRange CR = getUnsignedRange(DistancePlusOne); | ||||||||||
8690 | MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); | ||||||||||
8691 | } | ||||||||||
8692 | return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); | ||||||||||
8693 | } | ||||||||||
8694 | |||||||||||
8695 | // If the condition controls loop exit (the loop exits only if the expression | ||||||||||
8696 | // is true) and the addition is no-wrap we can use unsigned divide to | ||||||||||
8697 | // compute the backedge count. In this case, the step may not divide the | ||||||||||
8698 | // distance, but we don't care because if the condition is "missed" the loop | ||||||||||
8699 | // will have undefined behavior due to wrapping. | ||||||||||
8700 | if (ControlsExit && AddRec->hasNoSelfWrap() && | ||||||||||
8701 | loopHasNoAbnormalExits(AddRec->getLoop())) { | ||||||||||
8702 | const SCEV *Exact = | ||||||||||
8703 | getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); | ||||||||||
8704 | const SCEV *Max = | ||||||||||
8705 | Exact == getCouldNotCompute() | ||||||||||
8706 | ? Exact | ||||||||||
8707 | : getConstant(getUnsignedRangeMax(Exact)); | ||||||||||
8708 | return ExitLimit(Exact, Max, false, Predicates); | ||||||||||
8709 | } | ||||||||||
8710 | |||||||||||
8711 | // Solve the general equation. | ||||||||||
8712 | const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), | ||||||||||
8713 | getNegativeSCEV(Start), *this); | ||||||||||
8714 | const SCEV *M = E == getCouldNotCompute() | ||||||||||
8715 | ? E | ||||||||||
8716 | : getConstant(getUnsignedRangeMax(E)); | ||||||||||
8717 | return ExitLimit(E, M, false, Predicates); | ||||||||||
8718 | } | ||||||||||
8719 | |||||||||||
8720 | ScalarEvolution::ExitLimit | ||||||||||
8721 | ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { | ||||||||||
8722 | // Loops that look like: while (X == 0) are very strange indeed. We don't | ||||||||||
8723 | // handle them yet except for the trivial case. This could be expanded in the | ||||||||||
8724 | // future as needed. | ||||||||||
8725 | |||||||||||
8726 | // If the value is a constant, check to see if it is known to be non-zero | ||||||||||
8727 | // already. If so, the backedge will execute zero times. | ||||||||||
8728 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { | ||||||||||
8729 | if (!C->getValue()->isZero()) | ||||||||||
8730 | return getZero(C->getType()); | ||||||||||
8731 | return getCouldNotCompute(); // Otherwise it will loop infinitely. | ||||||||||
8732 | } | ||||||||||
8733 | |||||||||||
8734 | // We could implement others, but I really doubt anyone writes loops like | ||||||||||
8735 | // this, and if they did, they would already be constant folded. | ||||||||||
8736 | return getCouldNotCompute(); | ||||||||||
8737 | } | ||||||||||
8738 | |||||||||||
8739 | std::pair<const BasicBlock *, const BasicBlock *> | ||||||||||
8740 | ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) | ||||||||||
8741 | const { | ||||||||||
8742 | // If the block has a unique predecessor, then there is no path from the | ||||||||||
8743 | // predecessor to the block that does not go through the direct edge | ||||||||||
8744 | // from the predecessor to the block. | ||||||||||
8745 | if (const BasicBlock *Pred = BB->getSinglePredecessor()) | ||||||||||
8746 | return {Pred, BB}; | ||||||||||
8747 | |||||||||||
8748 | // A loop's header is defined to be a block that dominates the loop. | ||||||||||
8749 | // If the header has a unique predecessor outside the loop, it must be | ||||||||||
8750 | // a block that has exactly one successor that can reach the loop. | ||||||||||
8751 | if (const Loop *L = LI.getLoopFor(BB)) | ||||||||||
8752 | return {L->getLoopPredecessor(), L->getHeader()}; | ||||||||||
8753 | |||||||||||
8754 | return {nullptr, nullptr}; | ||||||||||
8755 | } | ||||||||||
8756 | |||||||||||
8757 | /// SCEV structural equivalence is usually sufficient for testing whether two | ||||||||||
8758 | /// expressions are equal, however for the purposes of looking for a condition | ||||||||||
8759 | /// guarding a loop, it can be useful to be a little more general, since a | ||||||||||
8760 | /// front-end may have replicated the controlling expression. | ||||||||||
8761 | static bool HasSameValue(const SCEV *A, const SCEV *B) { | ||||||||||
8762 | // Quick check to see if they are the same SCEV. | ||||||||||
8763 | if (A == B) return true; | ||||||||||
8764 | |||||||||||
8765 | auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { | ||||||||||
8766 | // Not all instructions that are "identical" compute the same value. For | ||||||||||
8767 | // instance, two distinct alloca instructions allocating the same type are | ||||||||||
8768 | // identical and do not read memory; but compute distinct values. | ||||||||||
8769 | return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); | ||||||||||
8770 | }; | ||||||||||
8771 | |||||||||||
8772 | // Otherwise, if they're both SCEVUnknown, it's possible that they hold | ||||||||||
8773 | // two different instructions with the same value. Check for this case. | ||||||||||
8774 | if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) | ||||||||||
8775 | if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) | ||||||||||
8776 | if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) | ||||||||||
8777 | if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) | ||||||||||
8778 | if (ComputesEqualValues(AI, BI)) | ||||||||||
8779 | return true; | ||||||||||
8780 | |||||||||||
8781 | // Otherwise assume they may have a different value. | ||||||||||
8782 | return false; | ||||||||||
8783 | } | ||||||||||
8784 | |||||||||||
8785 | bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, | ||||||||||
8786 | const SCEV *&LHS, const SCEV *&RHS, | ||||||||||
8787 | unsigned Depth) { | ||||||||||
8788 | bool Changed = false; | ||||||||||
8789 | // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or | ||||||||||
8790 | // '0 != 0'. | ||||||||||
8791 | auto TrivialCase = [&](bool TriviallyTrue) { | ||||||||||
8792 | LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); | ||||||||||
8793 | Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; | ||||||||||
8794 | return true; | ||||||||||
8795 | }; | ||||||||||
8796 | // If we hit the max recursion limit bail out. | ||||||||||
8797 | if (Depth >= 3) | ||||||||||
8798 | return false; | ||||||||||
8799 | |||||||||||
8800 | // Canonicalize a constant to the right side. | ||||||||||
8801 | if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { | ||||||||||
8802 | // Check for both operands constant. | ||||||||||
8803 | if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { | ||||||||||
8804 | if (ConstantExpr::getICmp(Pred, | ||||||||||
8805 | LHSC->getValue(), | ||||||||||
8806 | RHSC->getValue())->isNullValue()) | ||||||||||
8807 | return TrivialCase(false); | ||||||||||
8808 | else | ||||||||||
8809 | return TrivialCase(true); | ||||||||||
8810 | } | ||||||||||
8811 | // Otherwise swap the operands to put the constant on the right. | ||||||||||
8812 | std::swap(LHS, RHS); | ||||||||||
8813 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
8814 | Changed = true; | ||||||||||
8815 | } | ||||||||||
8816 | |||||||||||
8817 | // If we're comparing an addrec with a value which is loop-invariant in the | ||||||||||
8818 | // addrec's loop, put the addrec on the left. Also make a dominance check, | ||||||||||
8819 | // as both operands could be addrecs loop-invariant in each other's loop. | ||||||||||
8820 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { | ||||||||||
8821 | const Loop *L = AR->getLoop(); | ||||||||||
8822 | if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { | ||||||||||
8823 | std::swap(LHS, RHS); | ||||||||||
8824 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
8825 | Changed = true; | ||||||||||
8826 | } | ||||||||||
8827 | } | ||||||||||
8828 | |||||||||||
8829 | // If there's a constant operand, canonicalize comparisons with boundary | ||||||||||
8830 | // cases, and canonicalize *-or-equal comparisons to regular comparisons. | ||||||||||
8831 | if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { | ||||||||||
8832 | const APInt &RA = RC->getAPInt(); | ||||||||||
8833 | |||||||||||
8834 | bool SimplifiedByConstantRange = false; | ||||||||||
8835 | |||||||||||
8836 | if (!ICmpInst::isEquality(Pred)) { | ||||||||||
8837 | ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); | ||||||||||
8838 | if (ExactCR.isFullSet()) | ||||||||||
8839 | return TrivialCase(true); | ||||||||||
8840 | else if (ExactCR.isEmptySet()) | ||||||||||
8841 | return TrivialCase(false); | ||||||||||
8842 | |||||||||||
8843 | APInt NewRHS; | ||||||||||
8844 | CmpInst::Predicate NewPred; | ||||||||||
8845 | if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && | ||||||||||
8846 | ICmpInst::isEquality(NewPred)) { | ||||||||||
8847 | // We were able to convert an inequality to an equality. | ||||||||||
8848 | Pred = NewPred; | ||||||||||
8849 | RHS = getConstant(NewRHS); | ||||||||||
8850 | Changed = SimplifiedByConstantRange = true; | ||||||||||
8851 | } | ||||||||||
8852 | } | ||||||||||
8853 | |||||||||||
8854 | if (!SimplifiedByConstantRange) { | ||||||||||
8855 | switch (Pred) { | ||||||||||
8856 | default: | ||||||||||
8857 | break; | ||||||||||
8858 | case ICmpInst::ICMP_EQ: | ||||||||||
8859 | case ICmpInst::ICMP_NE: | ||||||||||
8860 | // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. | ||||||||||
8861 | if (!RA) | ||||||||||
8862 | if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) | ||||||||||
8863 | if (const SCEVMulExpr *ME = | ||||||||||
8864 | dyn_cast<SCEVMulExpr>(AE->getOperand(0))) | ||||||||||
8865 | if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && | ||||||||||
8866 | ME->getOperand(0)->isAllOnesValue()) { | ||||||||||
8867 | RHS = AE->getOperand(1); | ||||||||||
8868 | LHS = ME->getOperand(1); | ||||||||||
8869 | Changed = true; | ||||||||||
8870 | } | ||||||||||
8871 | break; | ||||||||||
8872 | |||||||||||
8873 | |||||||||||
8874 | // The "Should have been caught earlier!" messages refer to the fact | ||||||||||
8875 | // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above | ||||||||||
8876 | // should have fired on the corresponding cases, and canonicalized the | ||||||||||
8877 | // check to trivial case. | ||||||||||
8878 | |||||||||||
8879 | case ICmpInst::ICMP_UGE: | ||||||||||
8880 | assert(!RA.isMinValue() && "Should have been caught earlier!")((!RA.isMinValue() && "Should have been caught earlier!" ) ? static_cast<void> (0) : __assert_fail ("!RA.isMinValue() && \"Should have been caught earlier!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8880, __PRETTY_FUNCTION__)); | ||||||||||
8881 | Pred = ICmpInst::ICMP_UGT; | ||||||||||
8882 | RHS = getConstant(RA - 1); | ||||||||||
8883 | Changed = true; | ||||||||||
8884 | break; | ||||||||||
8885 | case ICmpInst::ICMP_ULE: | ||||||||||
8886 | assert(!RA.isMaxValue() && "Should have been caught earlier!")((!RA.isMaxValue() && "Should have been caught earlier!" ) ? static_cast<void> (0) : __assert_fail ("!RA.isMaxValue() && \"Should have been caught earlier!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8886, __PRETTY_FUNCTION__)); | ||||||||||
8887 | Pred = ICmpInst::ICMP_ULT; | ||||||||||
8888 | RHS = getConstant(RA + 1); | ||||||||||
8889 | Changed = true; | ||||||||||
8890 | break; | ||||||||||
8891 | case ICmpInst::ICMP_SGE: | ||||||||||
8892 | assert(!RA.isMinSignedValue() && "Should have been caught earlier!")((!RA.isMinSignedValue() && "Should have been caught earlier!" ) ? static_cast<void> (0) : __assert_fail ("!RA.isMinSignedValue() && \"Should have been caught earlier!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8892, __PRETTY_FUNCTION__)); | ||||||||||
8893 | Pred = ICmpInst::ICMP_SGT; | ||||||||||
8894 | RHS = getConstant(RA - 1); | ||||||||||
8895 | Changed = true; | ||||||||||
8896 | break; | ||||||||||
8897 | case ICmpInst::ICMP_SLE: | ||||||||||
8898 | assert(!RA.isMaxSignedValue() && "Should have been caught earlier!")((!RA.isMaxSignedValue() && "Should have been caught earlier!" ) ? static_cast<void> (0) : __assert_fail ("!RA.isMaxSignedValue() && \"Should have been caught earlier!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 8898, __PRETTY_FUNCTION__)); | ||||||||||
8899 | Pred = ICmpInst::ICMP_SLT; | ||||||||||
8900 | RHS = getConstant(RA + 1); | ||||||||||
8901 | Changed = true; | ||||||||||
8902 | break; | ||||||||||
8903 | } | ||||||||||
8904 | } | ||||||||||
8905 | } | ||||||||||
8906 | |||||||||||
8907 | // Check for obvious equality. | ||||||||||
8908 | if (HasSameValue(LHS, RHS)) { | ||||||||||
8909 | if (ICmpInst::isTrueWhenEqual(Pred)) | ||||||||||
8910 | return TrivialCase(true); | ||||||||||
8911 | if (ICmpInst::isFalseWhenEqual(Pred)) | ||||||||||
8912 | return TrivialCase(false); | ||||||||||
8913 | } | ||||||||||
8914 | |||||||||||
8915 | // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by | ||||||||||
8916 | // adding or subtracting 1 from one of the operands. | ||||||||||
8917 | switch (Pred) { | ||||||||||
8918 | case ICmpInst::ICMP_SLE: | ||||||||||
8919 | if (!getSignedRangeMax(RHS).isMaxSignedValue()) { | ||||||||||
8920 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, | ||||||||||
8921 | SCEV::FlagNSW); | ||||||||||
8922 | Pred = ICmpInst::ICMP_SLT; | ||||||||||
8923 | Changed = true; | ||||||||||
8924 | } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { | ||||||||||
8925 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, | ||||||||||
8926 | SCEV::FlagNSW); | ||||||||||
8927 | Pred = ICmpInst::ICMP_SLT; | ||||||||||
8928 | Changed = true; | ||||||||||
8929 | } | ||||||||||
8930 | break; | ||||||||||
8931 | case ICmpInst::ICMP_SGE: | ||||||||||
8932 | if (!getSignedRangeMin(RHS).isMinSignedValue()) { | ||||||||||
8933 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, | ||||||||||
8934 | SCEV::FlagNSW); | ||||||||||
8935 | Pred = ICmpInst::ICMP_SGT; | ||||||||||
8936 | Changed = true; | ||||||||||
8937 | } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { | ||||||||||
8938 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, | ||||||||||
8939 | SCEV::FlagNSW); | ||||||||||
8940 | Pred = ICmpInst::ICMP_SGT; | ||||||||||
8941 | Changed = true; | ||||||||||
8942 | } | ||||||||||
8943 | break; | ||||||||||
8944 | case ICmpInst::ICMP_ULE: | ||||||||||
8945 | if (!getUnsignedRangeMax(RHS).isMaxValue()) { | ||||||||||
8946 | RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, | ||||||||||
8947 | SCEV::FlagNUW); | ||||||||||
8948 | Pred = ICmpInst::ICMP_ULT; | ||||||||||
8949 | Changed = true; | ||||||||||
8950 | } else if (!getUnsignedRangeMin(LHS).isMinValue()) { | ||||||||||
8951 | LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); | ||||||||||
8952 | Pred = ICmpInst::ICMP_ULT; | ||||||||||
8953 | Changed = true; | ||||||||||
8954 | } | ||||||||||
8955 | break; | ||||||||||
8956 | case ICmpInst::ICMP_UGE: | ||||||||||
8957 | if (!getUnsignedRangeMin(RHS).isMinValue()) { | ||||||||||
8958 | RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); | ||||||||||
8959 | Pred = ICmpInst::ICMP_UGT; | ||||||||||
8960 | Changed = true; | ||||||||||
8961 | } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { | ||||||||||
8962 | LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, | ||||||||||
8963 | SCEV::FlagNUW); | ||||||||||
8964 | Pred = ICmpInst::ICMP_UGT; | ||||||||||
8965 | Changed = true; | ||||||||||
8966 | } | ||||||||||
8967 | break; | ||||||||||
8968 | default: | ||||||||||
8969 | break; | ||||||||||
8970 | } | ||||||||||
8971 | |||||||||||
8972 | // TODO: More simplifications are possible here. | ||||||||||
8973 | |||||||||||
8974 | // Recursively simplify until we either hit a recursion limit or nothing | ||||||||||
8975 | // changes. | ||||||||||
8976 | if (Changed) | ||||||||||
8977 | return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); | ||||||||||
8978 | |||||||||||
8979 | return Changed; | ||||||||||
8980 | } | ||||||||||
8981 | |||||||||||
8982 | bool ScalarEvolution::isKnownNegative(const SCEV *S) { | ||||||||||
8983 | return getSignedRangeMax(S).isNegative(); | ||||||||||
8984 | } | ||||||||||
8985 | |||||||||||
8986 | bool ScalarEvolution::isKnownPositive(const SCEV *S) { | ||||||||||
8987 | return getSignedRangeMin(S).isStrictlyPositive(); | ||||||||||
8988 | } | ||||||||||
8989 | |||||||||||
8990 | bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { | ||||||||||
8991 | return !getSignedRangeMin(S).isNegative(); | ||||||||||
8992 | } | ||||||||||
8993 | |||||||||||
8994 | bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { | ||||||||||
8995 | return !getSignedRangeMax(S).isStrictlyPositive(); | ||||||||||
8996 | } | ||||||||||
8997 | |||||||||||
8998 | bool ScalarEvolution::isKnownNonZero(const SCEV *S) { | ||||||||||
8999 | return isKnownNegative(S) || isKnownPositive(S); | ||||||||||
9000 | } | ||||||||||
9001 | |||||||||||
9002 | std::pair<const SCEV *, const SCEV *> | ||||||||||
9003 | ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { | ||||||||||
9004 | // Compute SCEV on entry of loop L. | ||||||||||
9005 | const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); | ||||||||||
9006 | if (Start == getCouldNotCompute()) | ||||||||||
9007 | return { Start, Start }; | ||||||||||
9008 | // Compute post increment SCEV for loop L. | ||||||||||
9009 | const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); | ||||||||||
9010 | assert(PostInc != getCouldNotCompute() && "Unexpected could not compute")((PostInc != getCouldNotCompute() && "Unexpected could not compute" ) ? static_cast<void> (0) : __assert_fail ("PostInc != getCouldNotCompute() && \"Unexpected could not compute\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9010, __PRETTY_FUNCTION__)); | ||||||||||
9011 | return { Start, PostInc }; | ||||||||||
9012 | } | ||||||||||
9013 | |||||||||||
9014 | bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, | ||||||||||
9015 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9016 | // First collect all loops. | ||||||||||
9017 | SmallPtrSet<const Loop *, 8> LoopsUsed; | ||||||||||
9018 | getUsedLoops(LHS, LoopsUsed); | ||||||||||
9019 | getUsedLoops(RHS, LoopsUsed); | ||||||||||
9020 | |||||||||||
9021 | if (LoopsUsed.empty()) | ||||||||||
9022 | return false; | ||||||||||
9023 | |||||||||||
9024 | // Domination relationship must be a linear order on collected loops. | ||||||||||
9025 | #ifndef NDEBUG | ||||||||||
9026 | for (auto *L1 : LoopsUsed) | ||||||||||
9027 | for (auto *L2 : LoopsUsed) | ||||||||||
9028 | assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT .dominates(L2->getHeader(), L1->getHeader())) && "Domination relationship is not a linear order") ? static_cast <void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9030, __PRETTY_FUNCTION__)) | ||||||||||
9029 | DT.dominates(L2->getHeader(), L1->getHeader())) &&(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT .dominates(L2->getHeader(), L1->getHeader())) && "Domination relationship is not a linear order") ? static_cast <void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9030, __PRETTY_FUNCTION__)) | ||||||||||
9030 | "Domination relationship is not a linear order")(((DT.dominates(L1->getHeader(), L2->getHeader()) || DT .dominates(L2->getHeader(), L1->getHeader())) && "Domination relationship is not a linear order") ? static_cast <void> (0) : __assert_fail ("(DT.dominates(L1->getHeader(), L2->getHeader()) || DT.dominates(L2->getHeader(), L1->getHeader())) && \"Domination relationship is not a linear order\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9030, __PRETTY_FUNCTION__)); | ||||||||||
9031 | #endif | ||||||||||
9032 | |||||||||||
9033 | const Loop *MDL = | ||||||||||
9034 | *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), | ||||||||||
9035 | [&](const Loop *L1, const Loop *L2) { | ||||||||||
9036 | return DT.properlyDominates(L1->getHeader(), L2->getHeader()); | ||||||||||
9037 | }); | ||||||||||
9038 | |||||||||||
9039 | // Get init and post increment value for LHS. | ||||||||||
9040 | auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); | ||||||||||
9041 | // if LHS contains unknown non-invariant SCEV then bail out. | ||||||||||
9042 | if (SplitLHS.first == getCouldNotCompute()) | ||||||||||
9043 | return false; | ||||||||||
9044 | assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC")((SplitLHS.second != getCouldNotCompute() && "Unexpected CNC" ) ? static_cast<void> (0) : __assert_fail ("SplitLHS.second != getCouldNotCompute() && \"Unexpected CNC\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9044, __PRETTY_FUNCTION__)); | ||||||||||
9045 | // Get init and post increment value for RHS. | ||||||||||
9046 | auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); | ||||||||||
9047 | // if RHS contains unknown non-invariant SCEV then bail out. | ||||||||||
9048 | if (SplitRHS.first == getCouldNotCompute()) | ||||||||||
9049 | return false; | ||||||||||
9050 | assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC")((SplitRHS.second != getCouldNotCompute() && "Unexpected CNC" ) ? static_cast<void> (0) : __assert_fail ("SplitRHS.second != getCouldNotCompute() && \"Unexpected CNC\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9050, __PRETTY_FUNCTION__)); | ||||||||||
9051 | // It is possible that init SCEV contains an invariant load but it does | ||||||||||
9052 | // not dominate MDL and is not available at MDL loop entry, so we should | ||||||||||
9053 | // check it here. | ||||||||||
9054 | if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || | ||||||||||
9055 | !isAvailableAtLoopEntry(SplitRHS.first, MDL)) | ||||||||||
9056 | return false; | ||||||||||
9057 | |||||||||||
9058 | // It seems backedge guard check is faster than entry one so in some cases | ||||||||||
9059 | // it can speed up whole estimation by short circuit | ||||||||||
9060 | return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, | ||||||||||
9061 | SplitRHS.second) && | ||||||||||
9062 | isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); | ||||||||||
9063 | } | ||||||||||
9064 | |||||||||||
9065 | bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, | ||||||||||
9066 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9067 | // Canonicalize the inputs first. | ||||||||||
9068 | (void)SimplifyICmpOperands(Pred, LHS, RHS); | ||||||||||
9069 | |||||||||||
9070 | if (isKnownViaInduction(Pred, LHS, RHS)) | ||||||||||
9071 | return true; | ||||||||||
9072 | |||||||||||
9073 | if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) | ||||||||||
9074 | return true; | ||||||||||
9075 | |||||||||||
9076 | // Otherwise see what can be done with some simple reasoning. | ||||||||||
9077 | return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); | ||||||||||
9078 | } | ||||||||||
9079 | |||||||||||
9080 | bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, | ||||||||||
9081 | const SCEVAddRecExpr *LHS, | ||||||||||
9082 | const SCEV *RHS) { | ||||||||||
9083 | const Loop *L = LHS->getLoop(); | ||||||||||
9084 | return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && | ||||||||||
9085 | isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); | ||||||||||
9086 | } | ||||||||||
9087 | |||||||||||
9088 | bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, | ||||||||||
9089 | ICmpInst::Predicate Pred, | ||||||||||
9090 | bool &Increasing) { | ||||||||||
9091 | bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); | ||||||||||
9092 | |||||||||||
9093 | #ifndef NDEBUG | ||||||||||
9094 | // Verify an invariant: inverting the predicate should turn a monotonically | ||||||||||
9095 | // increasing change to a monotonically decreasing one, and vice versa. | ||||||||||
9096 | bool IncreasingSwapped; | ||||||||||
9097 | bool ResultSwapped = isMonotonicPredicateImpl( | ||||||||||
9098 | LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); | ||||||||||
9099 | |||||||||||
9100 | assert(Result == ResultSwapped && "should be able to analyze both!")((Result == ResultSwapped && "should be able to analyze both!" ) ? static_cast<void> (0) : __assert_fail ("Result == ResultSwapped && \"should be able to analyze both!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9100, __PRETTY_FUNCTION__)); | ||||||||||
9101 | if (ResultSwapped) | ||||||||||
9102 | assert(Increasing == !IncreasingSwapped &&((Increasing == !IncreasingSwapped && "monotonicity should flip as we flip the predicate" ) ? static_cast<void> (0) : __assert_fail ("Increasing == !IncreasingSwapped && \"monotonicity should flip as we flip the predicate\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9103, __PRETTY_FUNCTION__)) | ||||||||||
9103 | "monotonicity should flip as we flip the predicate")((Increasing == !IncreasingSwapped && "monotonicity should flip as we flip the predicate" ) ? static_cast<void> (0) : __assert_fail ("Increasing == !IncreasingSwapped && \"monotonicity should flip as we flip the predicate\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9103, __PRETTY_FUNCTION__)); | ||||||||||
9104 | #endif | ||||||||||
9105 | |||||||||||
9106 | return Result; | ||||||||||
9107 | } | ||||||||||
9108 | |||||||||||
9109 | bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, | ||||||||||
9110 | ICmpInst::Predicate Pred, | ||||||||||
9111 | bool &Increasing) { | ||||||||||
9112 | |||||||||||
9113 | // A zero step value for LHS means the induction variable is essentially a | ||||||||||
9114 | // loop invariant value. We don't really depend on the predicate actually | ||||||||||
9115 | // flipping from false to true (for increasing predicates, and the other way | ||||||||||
9116 | // around for decreasing predicates), all we care about is that *if* the | ||||||||||
9117 | // predicate changes then it only changes from false to true. | ||||||||||
9118 | // | ||||||||||
9119 | // A zero step value in itself is not very useful, but there may be places | ||||||||||
9120 | // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be | ||||||||||
9121 | // as general as possible. | ||||||||||
9122 | |||||||||||
9123 | switch (Pred) { | ||||||||||
9124 | default: | ||||||||||
9125 | return false; // Conservative answer | ||||||||||
9126 | |||||||||||
9127 | case ICmpInst::ICMP_UGT: | ||||||||||
9128 | case ICmpInst::ICMP_UGE: | ||||||||||
9129 | case ICmpInst::ICMP_ULT: | ||||||||||
9130 | case ICmpInst::ICMP_ULE: | ||||||||||
9131 | if (!LHS->hasNoUnsignedWrap()) | ||||||||||
9132 | return false; | ||||||||||
9133 | |||||||||||
9134 | Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; | ||||||||||
9135 | return true; | ||||||||||
9136 | |||||||||||
9137 | case ICmpInst::ICMP_SGT: | ||||||||||
9138 | case ICmpInst::ICMP_SGE: | ||||||||||
9139 | case ICmpInst::ICMP_SLT: | ||||||||||
9140 | case ICmpInst::ICMP_SLE: { | ||||||||||
9141 | if (!LHS->hasNoSignedWrap()) | ||||||||||
9142 | return false; | ||||||||||
9143 | |||||||||||
9144 | const SCEV *Step = LHS->getStepRecurrence(*this); | ||||||||||
9145 | |||||||||||
9146 | if (isKnownNonNegative(Step)) { | ||||||||||
9147 | Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; | ||||||||||
9148 | return true; | ||||||||||
9149 | } | ||||||||||
9150 | |||||||||||
9151 | if (isKnownNonPositive(Step)) { | ||||||||||
9152 | Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; | ||||||||||
9153 | return true; | ||||||||||
9154 | } | ||||||||||
9155 | |||||||||||
9156 | return false; | ||||||||||
9157 | } | ||||||||||
9158 | |||||||||||
9159 | } | ||||||||||
9160 | |||||||||||
9161 | llvm_unreachable("switch has default clause!")::llvm::llvm_unreachable_internal("switch has default clause!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9161); | ||||||||||
9162 | } | ||||||||||
9163 | |||||||||||
9164 | bool ScalarEvolution::isLoopInvariantPredicate( | ||||||||||
9165 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, | ||||||||||
9166 | ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, | ||||||||||
9167 | const SCEV *&InvariantRHS) { | ||||||||||
9168 | |||||||||||
9169 | // If there is a loop-invariant, force it into the RHS, otherwise bail out. | ||||||||||
9170 | if (!isLoopInvariant(RHS, L)) { | ||||||||||
9171 | if (!isLoopInvariant(LHS, L)) | ||||||||||
9172 | return false; | ||||||||||
9173 | |||||||||||
9174 | std::swap(LHS, RHS); | ||||||||||
9175 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
9176 | } | ||||||||||
9177 | |||||||||||
9178 | const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); | ||||||||||
9179 | if (!ArLHS || ArLHS->getLoop() != L) | ||||||||||
9180 | return false; | ||||||||||
9181 | |||||||||||
9182 | bool Increasing; | ||||||||||
9183 | if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) | ||||||||||
9184 | return false; | ||||||||||
9185 | |||||||||||
9186 | // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to | ||||||||||
9187 | // true as the loop iterates, and the backedge is control dependent on | ||||||||||
9188 | // "ArLHS `Pred` RHS" == true then we can reason as follows: | ||||||||||
9189 | // | ||||||||||
9190 | // * if the predicate was false in the first iteration then the predicate | ||||||||||
9191 | // is never evaluated again, since the loop exits without taking the | ||||||||||
9192 | // backedge. | ||||||||||
9193 | // * if the predicate was true in the first iteration then it will | ||||||||||
9194 | // continue to be true for all future iterations since it is | ||||||||||
9195 | // monotonically increasing. | ||||||||||
9196 | // | ||||||||||
9197 | // For both the above possibilities, we can replace the loop varying | ||||||||||
9198 | // predicate with its value on the first iteration of the loop (which is | ||||||||||
9199 | // loop invariant). | ||||||||||
9200 | // | ||||||||||
9201 | // A similar reasoning applies for a monotonically decreasing predicate, by | ||||||||||
9202 | // replacing true with false and false with true in the above two bullets. | ||||||||||
9203 | |||||||||||
9204 | auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); | ||||||||||
9205 | |||||||||||
9206 | if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) | ||||||||||
9207 | return false; | ||||||||||
9208 | |||||||||||
9209 | InvariantPred = Pred; | ||||||||||
9210 | InvariantLHS = ArLHS->getStart(); | ||||||||||
9211 | InvariantRHS = RHS; | ||||||||||
9212 | return true; | ||||||||||
9213 | } | ||||||||||
9214 | |||||||||||
9215 | bool ScalarEvolution::isKnownPredicateViaConstantRanges( | ||||||||||
9216 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9217 | if (HasSameValue(LHS, RHS)) | ||||||||||
9218 | return ICmpInst::isTrueWhenEqual(Pred); | ||||||||||
9219 | |||||||||||
9220 | // This code is split out from isKnownPredicate because it is called from | ||||||||||
9221 | // within isLoopEntryGuardedByCond. | ||||||||||
9222 | |||||||||||
9223 | auto CheckRanges = | ||||||||||
9224 | [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { | ||||||||||
9225 | return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) | ||||||||||
9226 | .contains(RangeLHS); | ||||||||||
9227 | }; | ||||||||||
9228 | |||||||||||
9229 | // The check at the top of the function catches the case where the values are | ||||||||||
9230 | // known to be equal. | ||||||||||
9231 | if (Pred == CmpInst::ICMP_EQ) | ||||||||||
9232 | return false; | ||||||||||
9233 | |||||||||||
9234 | if (Pred == CmpInst::ICMP_NE) | ||||||||||
9235 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || | ||||||||||
9236 | CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || | ||||||||||
9237 | isKnownNonZero(getMinusSCEV(LHS, RHS)); | ||||||||||
9238 | |||||||||||
9239 | if (CmpInst::isSigned(Pred)) | ||||||||||
9240 | return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); | ||||||||||
9241 | |||||||||||
9242 | return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); | ||||||||||
9243 | } | ||||||||||
9244 | |||||||||||
9245 | bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, | ||||||||||
9246 | const SCEV *LHS, | ||||||||||
9247 | const SCEV *RHS) { | ||||||||||
9248 | // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. | ||||||||||
9249 | // Return Y via OutY. | ||||||||||
9250 | auto MatchBinaryAddToConst = | ||||||||||
9251 | [this](const SCEV *Result, const SCEV *X, APInt &OutY, | ||||||||||
9252 | SCEV::NoWrapFlags ExpectedFlags) { | ||||||||||
9253 | const SCEV *NonConstOp, *ConstOp; | ||||||||||
9254 | SCEV::NoWrapFlags FlagsPresent; | ||||||||||
9255 | |||||||||||
9256 | if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || | ||||||||||
9257 | !isa<SCEVConstant>(ConstOp) || NonConstOp != X) | ||||||||||
9258 | return false; | ||||||||||
9259 | |||||||||||
9260 | OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); | ||||||||||
9261 | return (FlagsPresent & ExpectedFlags) == ExpectedFlags; | ||||||||||
9262 | }; | ||||||||||
9263 | |||||||||||
9264 | APInt C; | ||||||||||
9265 | |||||||||||
9266 | switch (Pred) { | ||||||||||
9267 | default: | ||||||||||
9268 | break; | ||||||||||
9269 | |||||||||||
9270 | case ICmpInst::ICMP_SGE: | ||||||||||
9271 | std::swap(LHS, RHS); | ||||||||||
9272 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
9273 | case ICmpInst::ICMP_SLE: | ||||||||||
9274 | // X s<= (X + C)<nsw> if C >= 0 | ||||||||||
9275 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) | ||||||||||
9276 | return true; | ||||||||||
9277 | |||||||||||
9278 | // (X + C)<nsw> s<= X if C <= 0 | ||||||||||
9279 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && | ||||||||||
9280 | !C.isStrictlyPositive()) | ||||||||||
9281 | return true; | ||||||||||
9282 | break; | ||||||||||
9283 | |||||||||||
9284 | case ICmpInst::ICMP_SGT: | ||||||||||
9285 | std::swap(LHS, RHS); | ||||||||||
9286 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
9287 | case ICmpInst::ICMP_SLT: | ||||||||||
9288 | // X s< (X + C)<nsw> if C > 0 | ||||||||||
9289 | if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && | ||||||||||
9290 | C.isStrictlyPositive()) | ||||||||||
9291 | return true; | ||||||||||
9292 | |||||||||||
9293 | // (X + C)<nsw> s< X if C < 0 | ||||||||||
9294 | if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) | ||||||||||
9295 | return true; | ||||||||||
9296 | break; | ||||||||||
9297 | } | ||||||||||
9298 | |||||||||||
9299 | return false; | ||||||||||
9300 | } | ||||||||||
9301 | |||||||||||
9302 | bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, | ||||||||||
9303 | const SCEV *LHS, | ||||||||||
9304 | const SCEV *RHS) { | ||||||||||
9305 | if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) | ||||||||||
9306 | return false; | ||||||||||
9307 | |||||||||||
9308 | // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on | ||||||||||
9309 | // the stack can result in exponential time complexity. | ||||||||||
9310 | SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); | ||||||||||
9311 | |||||||||||
9312 | // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L | ||||||||||
9313 | // | ||||||||||
9314 | // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use | ||||||||||
9315 | // isKnownPredicate. isKnownPredicate is more powerful, but also more | ||||||||||
9316 | // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the | ||||||||||
9317 | // interesting cases seen in practice. We can consider "upgrading" L >= 0 to | ||||||||||
9318 | // use isKnownPredicate later if needed. | ||||||||||
9319 | return isKnownNonNegative(RHS) && | ||||||||||
9320 | isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && | ||||||||||
9321 | isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); | ||||||||||
9322 | } | ||||||||||
9323 | |||||||||||
9324 | bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, | ||||||||||
9325 | ICmpInst::Predicate Pred, | ||||||||||
9326 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9327 | // No need to even try if we know the module has no guards. | ||||||||||
9328 | if (!HasGuards) | ||||||||||
9329 | return false; | ||||||||||
9330 | |||||||||||
9331 | return any_of(*BB, [&](const Instruction &I) { | ||||||||||
9332 | using namespace llvm::PatternMatch; | ||||||||||
9333 | |||||||||||
9334 | Value *Condition; | ||||||||||
9335 | return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( | ||||||||||
9336 | m_Value(Condition))) && | ||||||||||
9337 | isImpliedCond(Pred, LHS, RHS, Condition, false); | ||||||||||
9338 | }); | ||||||||||
9339 | } | ||||||||||
9340 | |||||||||||
9341 | /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is | ||||||||||
9342 | /// protected by a conditional between LHS and RHS. This is used to | ||||||||||
9343 | /// to eliminate casts. | ||||||||||
9344 | bool | ||||||||||
9345 | ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, | ||||||||||
9346 | ICmpInst::Predicate Pred, | ||||||||||
9347 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9348 | // Interpret a null as meaning no loop, where there is obviously no guard | ||||||||||
9349 | // (interprocedural conditions notwithstanding). | ||||||||||
9350 | if (!L) return true; | ||||||||||
9351 | |||||||||||
9352 | if (VerifyIR) | ||||||||||
9353 | assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&((!verifyFunction(*L->getHeader()->getParent(), &dbgs ()) && "This cannot be done on broken IR!") ? static_cast <void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9354, __PRETTY_FUNCTION__)) | ||||||||||
9354 | "This cannot be done on broken IR!")((!verifyFunction(*L->getHeader()->getParent(), &dbgs ()) && "This cannot be done on broken IR!") ? static_cast <void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9354, __PRETTY_FUNCTION__)); | ||||||||||
9355 | |||||||||||
9356 | |||||||||||
9357 | if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) | ||||||||||
9358 | return true; | ||||||||||
9359 | |||||||||||
9360 | BasicBlock *Latch = L->getLoopLatch(); | ||||||||||
9361 | if (!Latch) | ||||||||||
9362 | return false; | ||||||||||
9363 | |||||||||||
9364 | BranchInst *LoopContinuePredicate = | ||||||||||
9365 | dyn_cast<BranchInst>(Latch->getTerminator()); | ||||||||||
9366 | if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && | ||||||||||
9367 | isImpliedCond(Pred, LHS, RHS, | ||||||||||
9368 | LoopContinuePredicate->getCondition(), | ||||||||||
9369 | LoopContinuePredicate->getSuccessor(0) != L->getHeader())) | ||||||||||
9370 | return true; | ||||||||||
9371 | |||||||||||
9372 | // We don't want more than one activation of the following loops on the stack | ||||||||||
9373 | // -- that can lead to O(n!) time complexity. | ||||||||||
9374 | if (WalkingBEDominatingConds) | ||||||||||
9375 | return false; | ||||||||||
9376 | |||||||||||
9377 | SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); | ||||||||||
9378 | |||||||||||
9379 | // See if we can exploit a trip count to prove the predicate. | ||||||||||
9380 | const auto &BETakenInfo = getBackedgeTakenInfo(L); | ||||||||||
9381 | const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); | ||||||||||
9382 | if (LatchBECount != getCouldNotCompute()) { | ||||||||||
9383 | // We know that Latch branches back to the loop header exactly | ||||||||||
9384 | // LatchBECount times. This means the backdege condition at Latch is | ||||||||||
9385 | // equivalent to "{0,+,1} u< LatchBECount". | ||||||||||
9386 | Type *Ty = LatchBECount->getType(); | ||||||||||
9387 | auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); | ||||||||||
9388 | const SCEV *LoopCounter = | ||||||||||
9389 | getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); | ||||||||||
9390 | if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, | ||||||||||
9391 | LatchBECount)) | ||||||||||
9392 | return true; | ||||||||||
9393 | } | ||||||||||
9394 | |||||||||||
9395 | // Check conditions due to any @llvm.assume intrinsics. | ||||||||||
9396 | for (auto &AssumeVH : AC.assumptions()) { | ||||||||||
9397 | if (!AssumeVH) | ||||||||||
9398 | continue; | ||||||||||
9399 | auto *CI = cast<CallInst>(AssumeVH); | ||||||||||
9400 | if (!DT.dominates(CI, Latch->getTerminator())) | ||||||||||
9401 | continue; | ||||||||||
9402 | |||||||||||
9403 | if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) | ||||||||||
9404 | return true; | ||||||||||
9405 | } | ||||||||||
9406 | |||||||||||
9407 | // If the loop is not reachable from the entry block, we risk running into an | ||||||||||
9408 | // infinite loop as we walk up into the dom tree. These loops do not matter | ||||||||||
9409 | // anyway, so we just return a conservative answer when we see them. | ||||||||||
9410 | if (!DT.isReachableFromEntry(L->getHeader())) | ||||||||||
9411 | return false; | ||||||||||
9412 | |||||||||||
9413 | if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) | ||||||||||
9414 | return true; | ||||||||||
9415 | |||||||||||
9416 | for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; | ||||||||||
9417 | DTN != HeaderDTN; DTN = DTN->getIDom()) { | ||||||||||
9418 | assert(DTN && "should reach the loop header before reaching the root!")((DTN && "should reach the loop header before reaching the root!" ) ? static_cast<void> (0) : __assert_fail ("DTN && \"should reach the loop header before reaching the root!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9418, __PRETTY_FUNCTION__)); | ||||||||||
9419 | |||||||||||
9420 | BasicBlock *BB = DTN->getBlock(); | ||||||||||
9421 | if (isImpliedViaGuard(BB, Pred, LHS, RHS)) | ||||||||||
9422 | return true; | ||||||||||
9423 | |||||||||||
9424 | BasicBlock *PBB = BB->getSinglePredecessor(); | ||||||||||
9425 | if (!PBB) | ||||||||||
9426 | continue; | ||||||||||
9427 | |||||||||||
9428 | BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); | ||||||||||
9429 | if (!ContinuePredicate || !ContinuePredicate->isConditional()) | ||||||||||
9430 | continue; | ||||||||||
9431 | |||||||||||
9432 | Value *Condition = ContinuePredicate->getCondition(); | ||||||||||
9433 | |||||||||||
9434 | // If we have an edge `E` within the loop body that dominates the only | ||||||||||
9435 | // latch, the condition guarding `E` also guards the backedge. This | ||||||||||
9436 | // reasoning works only for loops with a single latch. | ||||||||||
9437 | |||||||||||
9438 | BasicBlockEdge DominatingEdge(PBB, BB); | ||||||||||
9439 | if (DominatingEdge.isSingleEdge()) { | ||||||||||
9440 | // We're constructively (and conservatively) enumerating edges within the | ||||||||||
9441 | // loop body that dominate the latch. The dominator tree better agree | ||||||||||
9442 | // with us on this: | ||||||||||
9443 | assert(DT.dominates(DominatingEdge, Latch) && "should be!")((DT.dominates(DominatingEdge, Latch) && "should be!" ) ? static_cast<void> (0) : __assert_fail ("DT.dominates(DominatingEdge, Latch) && \"should be!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9443, __PRETTY_FUNCTION__)); | ||||||||||
9444 | |||||||||||
9445 | if (isImpliedCond(Pred, LHS, RHS, Condition, | ||||||||||
9446 | BB != ContinuePredicate->getSuccessor(0))) | ||||||||||
9447 | return true; | ||||||||||
9448 | } | ||||||||||
9449 | } | ||||||||||
9450 | |||||||||||
9451 | return false; | ||||||||||
9452 | } | ||||||||||
9453 | |||||||||||
9454 | bool | ||||||||||
9455 | ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, | ||||||||||
9456 | ICmpInst::Predicate Pred, | ||||||||||
9457 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
9458 | // Interpret a null as meaning no loop, where there is obviously no guard | ||||||||||
9459 | // (interprocedural conditions notwithstanding). | ||||||||||
9460 | if (!L) return false; | ||||||||||
9461 | |||||||||||
9462 | if (VerifyIR) | ||||||||||
9463 | assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&((!verifyFunction(*L->getHeader()->getParent(), &dbgs ()) && "This cannot be done on broken IR!") ? static_cast <void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9464, __PRETTY_FUNCTION__)) | ||||||||||
9464 | "This cannot be done on broken IR!")((!verifyFunction(*L->getHeader()->getParent(), &dbgs ()) && "This cannot be done on broken IR!") ? static_cast <void> (0) : __assert_fail ("!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && \"This cannot be done on broken IR!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9464, __PRETTY_FUNCTION__)); | ||||||||||
9465 | |||||||||||
9466 | // Both LHS and RHS must be available at loop entry. | ||||||||||
9467 | assert(isAvailableAtLoopEntry(LHS, L) &&((isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry" ) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9468, __PRETTY_FUNCTION__)) | ||||||||||
9468 | "LHS is not available at Loop Entry")((isAvailableAtLoopEntry(LHS, L) && "LHS is not available at Loop Entry" ) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(LHS, L) && \"LHS is not available at Loop Entry\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9468, __PRETTY_FUNCTION__)); | ||||||||||
9469 | assert(isAvailableAtLoopEntry(RHS, L) &&((isAvailableAtLoopEntry(RHS, L) && "RHS is not available at Loop Entry" ) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9470, __PRETTY_FUNCTION__)) | ||||||||||
9470 | "RHS is not available at Loop Entry")((isAvailableAtLoopEntry(RHS, L) && "RHS is not available at Loop Entry" ) ? static_cast<void> (0) : __assert_fail ("isAvailableAtLoopEntry(RHS, L) && \"RHS is not available at Loop Entry\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9470, __PRETTY_FUNCTION__)); | ||||||||||
9471 | |||||||||||
9472 | if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) | ||||||||||
9473 | return true; | ||||||||||
9474 | |||||||||||
9475 | // If we cannot prove strict comparison (e.g. a > b), maybe we can prove | ||||||||||
9476 | // the facts (a >= b && a != b) separately. A typical situation is when the | ||||||||||
9477 | // non-strict comparison is known from ranges and non-equality is known from | ||||||||||
9478 | // dominating predicates. If we are proving strict comparison, we always try | ||||||||||
9479 | // to prove non-equality and non-strict comparison separately. | ||||||||||
9480 | auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); | ||||||||||
9481 | const bool ProvingStrictComparison = (Pred != NonStrictPredicate); | ||||||||||
9482 | bool ProvedNonStrictComparison = false; | ||||||||||
9483 | bool ProvedNonEquality = false; | ||||||||||
9484 | |||||||||||
9485 | if (ProvingStrictComparison) { | ||||||||||
9486 | ProvedNonStrictComparison = | ||||||||||
9487 | isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); | ||||||||||
9488 | ProvedNonEquality = | ||||||||||
9489 | isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); | ||||||||||
9490 | if (ProvedNonStrictComparison && ProvedNonEquality) | ||||||||||
9491 | return true; | ||||||||||
9492 | } | ||||||||||
9493 | |||||||||||
9494 | // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. | ||||||||||
9495 | auto ProveViaGuard = [&](const BasicBlock *Block) { | ||||||||||
9496 | if (isImpliedViaGuard(Block, Pred, LHS, RHS)) | ||||||||||
9497 | return true; | ||||||||||
9498 | if (ProvingStrictComparison) { | ||||||||||
9499 | if (!ProvedNonStrictComparison) | ||||||||||
9500 | ProvedNonStrictComparison = | ||||||||||
9501 | isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); | ||||||||||
9502 | if (!ProvedNonEquality) | ||||||||||
9503 | ProvedNonEquality = | ||||||||||
9504 | isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); | ||||||||||
9505 | if (ProvedNonStrictComparison && ProvedNonEquality) | ||||||||||
9506 | return true; | ||||||||||
9507 | } | ||||||||||
9508 | return false; | ||||||||||
9509 | }; | ||||||||||
9510 | |||||||||||
9511 | // Try to prove (Pred, LHS, RHS) using isImpliedCond. | ||||||||||
9512 | auto ProveViaCond = [&](const Value *Condition, bool Inverse) { | ||||||||||
9513 | if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) | ||||||||||
9514 | return true; | ||||||||||
9515 | if (ProvingStrictComparison) { | ||||||||||
9516 | if (!ProvedNonStrictComparison) | ||||||||||
9517 | ProvedNonStrictComparison = | ||||||||||
9518 | isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); | ||||||||||
9519 | if (!ProvedNonEquality) | ||||||||||
9520 | ProvedNonEquality = | ||||||||||
9521 | isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); | ||||||||||
9522 | if (ProvedNonStrictComparison && ProvedNonEquality) | ||||||||||
9523 | return true; | ||||||||||
9524 | } | ||||||||||
9525 | return false; | ||||||||||
9526 | }; | ||||||||||
9527 | |||||||||||
9528 | // Starting at the loop predecessor, climb up the predecessor chain, as long | ||||||||||
9529 | // as there are predecessors that can be found that have unique successors | ||||||||||
9530 | // leading to the original header. | ||||||||||
9531 | for (std::pair<const BasicBlock *, const BasicBlock *> Pair( | ||||||||||
9532 | L->getLoopPredecessor(), L->getHeader()); | ||||||||||
9533 | Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { | ||||||||||
9534 | |||||||||||
9535 | if (ProveViaGuard(Pair.first)) | ||||||||||
9536 | return true; | ||||||||||
9537 | |||||||||||
9538 | const BranchInst *LoopEntryPredicate = | ||||||||||
9539 | dyn_cast<BranchInst>(Pair.first->getTerminator()); | ||||||||||
9540 | if (!LoopEntryPredicate || | ||||||||||
9541 | LoopEntryPredicate->isUnconditional()) | ||||||||||
9542 | continue; | ||||||||||
9543 | |||||||||||
9544 | if (ProveViaCond(LoopEntryPredicate->getCondition(), | ||||||||||
9545 | LoopEntryPredicate->getSuccessor(0) != Pair.second)) | ||||||||||
9546 | return true; | ||||||||||
9547 | } | ||||||||||
9548 | |||||||||||
9549 | // Check conditions due to any @llvm.assume intrinsics. | ||||||||||
9550 | for (auto &AssumeVH : AC.assumptions()) { | ||||||||||
9551 | if (!AssumeVH) | ||||||||||
9552 | continue; | ||||||||||
9553 | auto *CI = cast<CallInst>(AssumeVH); | ||||||||||
9554 | if (!DT.dominates(CI, L->getHeader())) | ||||||||||
9555 | continue; | ||||||||||
9556 | |||||||||||
9557 | if (ProveViaCond(CI->getArgOperand(0), false)) | ||||||||||
9558 | return true; | ||||||||||
9559 | } | ||||||||||
9560 | |||||||||||
9561 | return false; | ||||||||||
9562 | } | ||||||||||
9563 | |||||||||||
9564 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, | ||||||||||
9565 | const SCEV *RHS, | ||||||||||
9566 | const Value *FoundCondValue, bool Inverse) { | ||||||||||
9567 | if (!PendingLoopPredicates.insert(FoundCondValue).second) | ||||||||||
9568 | return false; | ||||||||||
9569 | |||||||||||
9570 | auto ClearOnExit = | ||||||||||
9571 | make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); | ||||||||||
9572 | |||||||||||
9573 | // Recursively handle And and Or conditions. | ||||||||||
9574 | if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { | ||||||||||
9575 | if (BO->getOpcode() == Instruction::And) { | ||||||||||
9576 | if (!Inverse) | ||||||||||
9577 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || | ||||||||||
9578 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); | ||||||||||
9579 | } else if (BO->getOpcode() == Instruction::Or) { | ||||||||||
9580 | if (Inverse) | ||||||||||
9581 | return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || | ||||||||||
9582 | isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); | ||||||||||
9583 | } | ||||||||||
9584 | } | ||||||||||
9585 | |||||||||||
9586 | const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); | ||||||||||
9587 | if (!ICI) return false; | ||||||||||
9588 | |||||||||||
9589 | // Now that we found a conditional branch that dominates the loop or controls | ||||||||||
9590 | // the loop latch. Check to see if it is the comparison we are looking for. | ||||||||||
9591 | ICmpInst::Predicate FoundPred; | ||||||||||
9592 | if (Inverse) | ||||||||||
9593 | FoundPred = ICI->getInversePredicate(); | ||||||||||
9594 | else | ||||||||||
9595 | FoundPred = ICI->getPredicate(); | ||||||||||
9596 | |||||||||||
9597 | const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); | ||||||||||
9598 | const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); | ||||||||||
9599 | |||||||||||
9600 | return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); | ||||||||||
9601 | } | ||||||||||
9602 | |||||||||||
9603 | bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, | ||||||||||
9604 | const SCEV *RHS, | ||||||||||
9605 | ICmpInst::Predicate FoundPred, | ||||||||||
9606 | const SCEV *FoundLHS, | ||||||||||
9607 | const SCEV *FoundRHS) { | ||||||||||
9608 | // Balance the types. | ||||||||||
9609 | if (getTypeSizeInBits(LHS->getType()) < | ||||||||||
9610 | getTypeSizeInBits(FoundLHS->getType())) { | ||||||||||
9611 | if (CmpInst::isSigned(Pred)) { | ||||||||||
9612 | LHS = getSignExtendExpr(LHS, FoundLHS->getType()); | ||||||||||
9613 | RHS = getSignExtendExpr(RHS, FoundLHS->getType()); | ||||||||||
9614 | } else { | ||||||||||
9615 | LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); | ||||||||||
9616 | RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); | ||||||||||
9617 | } | ||||||||||
9618 | } else if (getTypeSizeInBits(LHS->getType()) > | ||||||||||
9619 | getTypeSizeInBits(FoundLHS->getType())) { | ||||||||||
9620 | if (CmpInst::isSigned(FoundPred)) { | ||||||||||
9621 | FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); | ||||||||||
9622 | FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); | ||||||||||
9623 | } else { | ||||||||||
9624 | FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); | ||||||||||
9625 | FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); | ||||||||||
9626 | } | ||||||||||
9627 | } | ||||||||||
9628 | |||||||||||
9629 | // Canonicalize the query to match the way instcombine will have | ||||||||||
9630 | // canonicalized the comparison. | ||||||||||
9631 | if (SimplifyICmpOperands(Pred, LHS, RHS)) | ||||||||||
9632 | if (LHS == RHS) | ||||||||||
9633 | return CmpInst::isTrueWhenEqual(Pred); | ||||||||||
9634 | if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) | ||||||||||
9635 | if (FoundLHS == FoundRHS) | ||||||||||
9636 | return CmpInst::isFalseWhenEqual(FoundPred); | ||||||||||
9637 | |||||||||||
9638 | // Check to see if we can make the LHS or RHS match. | ||||||||||
9639 | if (LHS == FoundRHS || RHS == FoundLHS) { | ||||||||||
9640 | if (isa<SCEVConstant>(RHS)) { | ||||||||||
9641 | std::swap(FoundLHS, FoundRHS); | ||||||||||
9642 | FoundPred = ICmpInst::getSwappedPredicate(FoundPred); | ||||||||||
9643 | } else { | ||||||||||
9644 | std::swap(LHS, RHS); | ||||||||||
9645 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
9646 | } | ||||||||||
9647 | } | ||||||||||
9648 | |||||||||||
9649 | // Check whether the found predicate is the same as the desired predicate. | ||||||||||
9650 | if (FoundPred == Pred) | ||||||||||
9651 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); | ||||||||||
9652 | |||||||||||
9653 | // Check whether swapping the found predicate makes it the same as the | ||||||||||
9654 | // desired predicate. | ||||||||||
9655 | if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { | ||||||||||
9656 | if (isa<SCEVConstant>(RHS)) | ||||||||||
9657 | return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); | ||||||||||
9658 | else | ||||||||||
9659 | return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), | ||||||||||
9660 | RHS, LHS, FoundLHS, FoundRHS); | ||||||||||
9661 | } | ||||||||||
9662 | |||||||||||
9663 | // Unsigned comparison is the same as signed comparison when both the operands | ||||||||||
9664 | // are non-negative. | ||||||||||
9665 | if (CmpInst::isUnsigned(FoundPred) && | ||||||||||
9666 | CmpInst::getSignedPredicate(FoundPred) == Pred && | ||||||||||
9667 | isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) | ||||||||||
9668 | return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); | ||||||||||
9669 | |||||||||||
9670 | // Check if we can make progress by sharpening ranges. | ||||||||||
9671 | if (FoundPred == ICmpInst::ICMP_NE && | ||||||||||
9672 | (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { | ||||||||||
9673 | |||||||||||
9674 | const SCEVConstant *C = nullptr; | ||||||||||
9675 | const SCEV *V = nullptr; | ||||||||||
9676 | |||||||||||
9677 | if (isa<SCEVConstant>(FoundLHS)) { | ||||||||||
9678 | C = cast<SCEVConstant>(FoundLHS); | ||||||||||
9679 | V = FoundRHS; | ||||||||||
9680 | } else { | ||||||||||
9681 | C = cast<SCEVConstant>(FoundRHS); | ||||||||||
9682 | V = FoundLHS; | ||||||||||
9683 | } | ||||||||||
9684 | |||||||||||
9685 | // The guarding predicate tells us that C != V. If the known range | ||||||||||
9686 | // of V is [C, t), we can sharpen the range to [C + 1, t). The | ||||||||||
9687 | // range we consider has to correspond to same signedness as the | ||||||||||
9688 | // predicate we're interested in folding. | ||||||||||
9689 | |||||||||||
9690 | APInt Min = ICmpInst::isSigned(Pred) ? | ||||||||||
9691 | getSignedRangeMin(V) : getUnsignedRangeMin(V); | ||||||||||
9692 | |||||||||||
9693 | if (Min == C->getAPInt()) { | ||||||||||
9694 | // Given (V >= Min && V != Min) we conclude V >= (Min + 1). | ||||||||||
9695 | // This is true even if (Min + 1) wraps around -- in case of | ||||||||||
9696 | // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). | ||||||||||
9697 | |||||||||||
9698 | APInt SharperMin = Min + 1; | ||||||||||
9699 | |||||||||||
9700 | switch (Pred) { | ||||||||||
9701 | case ICmpInst::ICMP_SGE: | ||||||||||
9702 | case ICmpInst::ICMP_UGE: | ||||||||||
9703 | // We know V `Pred` SharperMin. If this implies LHS `Pred` | ||||||||||
9704 | // RHS, we're done. | ||||||||||
9705 | if (isImpliedCondOperands(Pred, LHS, RHS, V, | ||||||||||
9706 | getConstant(SharperMin))) | ||||||||||
9707 | return true; | ||||||||||
9708 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
9709 | |||||||||||
9710 | case ICmpInst::ICMP_SGT: | ||||||||||
9711 | case ICmpInst::ICMP_UGT: | ||||||||||
9712 | // We know from the range information that (V `Pred` Min || | ||||||||||
9713 | // V == Min). We know from the guarding condition that !(V | ||||||||||
9714 | // == Min). This gives us | ||||||||||
9715 | // | ||||||||||
9716 | // V `Pred` Min || V == Min && !(V == Min) | ||||||||||
9717 | // => V `Pred` Min | ||||||||||
9718 | // | ||||||||||
9719 | // If V `Pred` Min implies LHS `Pred` RHS, we're done. | ||||||||||
9720 | |||||||||||
9721 | if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) | ||||||||||
9722 | return true; | ||||||||||
9723 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
9724 | |||||||||||
9725 | default: | ||||||||||
9726 | // No change | ||||||||||
9727 | break; | ||||||||||
9728 | } | ||||||||||
9729 | } | ||||||||||
9730 | } | ||||||||||
9731 | |||||||||||
9732 | // Check whether the actual condition is beyond sufficient. | ||||||||||
9733 | if (FoundPred == ICmpInst::ICMP_EQ) | ||||||||||
9734 | if (ICmpInst::isTrueWhenEqual(Pred)) | ||||||||||
9735 | if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) | ||||||||||
9736 | return true; | ||||||||||
9737 | if (Pred == ICmpInst::ICMP_NE) | ||||||||||
9738 | if (!ICmpInst::isTrueWhenEqual(FoundPred)) | ||||||||||
9739 | if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) | ||||||||||
9740 | return true; | ||||||||||
9741 | |||||||||||
9742 | // Otherwise assume the worst. | ||||||||||
9743 | return false; | ||||||||||
9744 | } | ||||||||||
9745 | |||||||||||
9746 | bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, | ||||||||||
9747 | const SCEV *&L, const SCEV *&R, | ||||||||||
9748 | SCEV::NoWrapFlags &Flags) { | ||||||||||
9749 | const auto *AE = dyn_cast<SCEVAddExpr>(Expr); | ||||||||||
9750 | if (!AE || AE->getNumOperands() != 2) | ||||||||||
9751 | return false; | ||||||||||
9752 | |||||||||||
9753 | L = AE->getOperand(0); | ||||||||||
9754 | R = AE->getOperand(1); | ||||||||||
9755 | Flags = AE->getNoWrapFlags(); | ||||||||||
9756 | return true; | ||||||||||
9757 | } | ||||||||||
9758 | |||||||||||
9759 | Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, | ||||||||||
9760 | const SCEV *Less) { | ||||||||||
9761 | // We avoid subtracting expressions here because this function is usually | ||||||||||
9762 | // fairly deep in the call stack (i.e. is called many times). | ||||||||||
9763 | |||||||||||
9764 | // X - X = 0. | ||||||||||
9765 | if (More == Less) | ||||||||||
9766 | return APInt(getTypeSizeInBits(More->getType()), 0); | ||||||||||
9767 | |||||||||||
9768 | if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { | ||||||||||
9769 | const auto *LAR = cast<SCEVAddRecExpr>(Less); | ||||||||||
9770 | const auto *MAR = cast<SCEVAddRecExpr>(More); | ||||||||||
9771 | |||||||||||
9772 | if (LAR->getLoop() != MAR->getLoop()) | ||||||||||
9773 | return None; | ||||||||||
9774 | |||||||||||
9775 | // We look at affine expressions only; not for correctness but to keep | ||||||||||
9776 | // getStepRecurrence cheap. | ||||||||||
9777 | if (!LAR->isAffine() || !MAR->isAffine()) | ||||||||||
9778 | return None; | ||||||||||
9779 | |||||||||||
9780 | if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) | ||||||||||
9781 | return None; | ||||||||||
9782 | |||||||||||
9783 | Less = LAR->getStart(); | ||||||||||
9784 | More = MAR->getStart(); | ||||||||||
9785 | |||||||||||
9786 | // fall through | ||||||||||
9787 | } | ||||||||||
9788 | |||||||||||
9789 | if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { | ||||||||||
9790 | const auto &M = cast<SCEVConstant>(More)->getAPInt(); | ||||||||||
9791 | const auto &L = cast<SCEVConstant>(Less)->getAPInt(); | ||||||||||
9792 | return M - L; | ||||||||||
9793 | } | ||||||||||
9794 | |||||||||||
9795 | SCEV::NoWrapFlags Flags; | ||||||||||
9796 | const SCEV *LLess = nullptr, *RLess = nullptr; | ||||||||||
9797 | const SCEV *LMore = nullptr, *RMore = nullptr; | ||||||||||
9798 | const SCEVConstant *C1 = nullptr, *C2 = nullptr; | ||||||||||
9799 | // Compare (X + C1) vs X. | ||||||||||
9800 | if (splitBinaryAdd(Less, LLess, RLess, Flags)) | ||||||||||
9801 | if ((C1 = dyn_cast<SCEVConstant>(LLess))) | ||||||||||
9802 | if (RLess == More) | ||||||||||
9803 | return -(C1->getAPInt()); | ||||||||||
9804 | |||||||||||
9805 | // Compare X vs (X + C2). | ||||||||||
9806 | if (splitBinaryAdd(More, LMore, RMore, Flags)) | ||||||||||
9807 | if ((C2 = dyn_cast<SCEVConstant>(LMore))) | ||||||||||
9808 | if (RMore == Less) | ||||||||||
9809 | return C2->getAPInt(); | ||||||||||
9810 | |||||||||||
9811 | // Compare (X + C1) vs (X + C2). | ||||||||||
9812 | if (C1 && C2 && RLess == RMore) | ||||||||||
9813 | return C2->getAPInt() - C1->getAPInt(); | ||||||||||
9814 | |||||||||||
9815 | return None; | ||||||||||
9816 | } | ||||||||||
9817 | |||||||||||
9818 | bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( | ||||||||||
9819 | ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, | ||||||||||
9820 | const SCEV *FoundLHS, const SCEV *FoundRHS) { | ||||||||||
9821 | if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) | ||||||||||
9822 | return false; | ||||||||||
9823 | |||||||||||
9824 | const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); | ||||||||||
9825 | if (!AddRecLHS) | ||||||||||
9826 | return false; | ||||||||||
9827 | |||||||||||
9828 | const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); | ||||||||||
9829 | if (!AddRecFoundLHS) | ||||||||||
9830 | return false; | ||||||||||
9831 | |||||||||||
9832 | // We'd like to let SCEV reason about control dependencies, so we constrain | ||||||||||
9833 | // both the inequalities to be about add recurrences on the same loop. This | ||||||||||
9834 | // way we can use isLoopEntryGuardedByCond later. | ||||||||||
9835 | |||||||||||
9836 | const Loop *L = AddRecFoundLHS->getLoop(); | ||||||||||
9837 | if (L != AddRecLHS->getLoop()) | ||||||||||
9838 | return false; | ||||||||||
9839 | |||||||||||
9840 | // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) | ||||||||||
9841 | // | ||||||||||
9842 | // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) | ||||||||||
9843 | // ... (2) | ||||||||||
9844 | // | ||||||||||
9845 | // Informal proof for (2), assuming (1) [*]: | ||||||||||
9846 | // | ||||||||||
9847 | // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] | ||||||||||
9848 | // | ||||||||||
9849 | // Then | ||||||||||
9850 | // | ||||||||||
9851 | // FoundLHS s< FoundRHS s< INT_MIN - C | ||||||||||
9852 | // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] | ||||||||||
9853 | // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] | ||||||||||
9854 | // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< | ||||||||||
9855 | // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] | ||||||||||
9856 | // <=> FoundLHS + C s< FoundRHS + C | ||||||||||
9857 | // | ||||||||||
9858 | // [*]: (1) can be proved by ruling out overflow. | ||||||||||
9859 | // | ||||||||||
9860 | // [**]: This can be proved by analyzing all the four possibilities: | ||||||||||
9861 | // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and | ||||||||||
9862 | // (A s>= 0, B s>= 0). | ||||||||||
9863 | // | ||||||||||
9864 | // Note: | ||||||||||
9865 | // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" | ||||||||||
9866 | // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS | ||||||||||
9867 | // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS | ||||||||||
9868 | // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is | ||||||||||
9869 | // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + | ||||||||||
9870 | // C)". | ||||||||||
9871 | |||||||||||
9872 | Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); | ||||||||||
9873 | Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); | ||||||||||
9874 | if (!LDiff || !RDiff || *LDiff != *RDiff) | ||||||||||
9875 | return false; | ||||||||||
9876 | |||||||||||
9877 | if (LDiff->isMinValue()) | ||||||||||
9878 | return true; | ||||||||||
9879 | |||||||||||
9880 | APInt FoundRHSLimit; | ||||||||||
9881 | |||||||||||
9882 | if (Pred == CmpInst::ICMP_ULT) { | ||||||||||
9883 | FoundRHSLimit = -(*RDiff); | ||||||||||
9884 | } else { | ||||||||||
9885 | assert(Pred == CmpInst::ICMP_SLT && "Checked above!")((Pred == CmpInst::ICMP_SLT && "Checked above!") ? static_cast <void> (0) : __assert_fail ("Pred == CmpInst::ICMP_SLT && \"Checked above!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9885, __PRETTY_FUNCTION__)); | ||||||||||
9886 | FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; | ||||||||||
9887 | } | ||||||||||
9888 | |||||||||||
9889 | // Try to prove (1) or (2), as needed. | ||||||||||
9890 | return isAvailableAtLoopEntry(FoundRHS, L) && | ||||||||||
9891 | isLoopEntryGuardedByCond(L, Pred, FoundRHS, | ||||||||||
9892 | getConstant(FoundRHSLimit)); | ||||||||||
9893 | } | ||||||||||
9894 | |||||||||||
9895 | bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, | ||||||||||
9896 | const SCEV *LHS, const SCEV *RHS, | ||||||||||
9897 | const SCEV *FoundLHS, | ||||||||||
9898 | const SCEV *FoundRHS, unsigned Depth) { | ||||||||||
9899 | const PHINode *LPhi = nullptr, *RPhi = nullptr; | ||||||||||
9900 | |||||||||||
9901 | auto ClearOnExit = make_scope_exit([&]() { | ||||||||||
9902 | if (LPhi) { | ||||||||||
9903 | bool Erased = PendingMerges.erase(LPhi); | ||||||||||
9904 | assert(Erased && "Failed to erase LPhi!")((Erased && "Failed to erase LPhi!") ? static_cast< void> (0) : __assert_fail ("Erased && \"Failed to erase LPhi!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9904, __PRETTY_FUNCTION__)); | ||||||||||
9905 | (void)Erased; | ||||||||||
9906 | } | ||||||||||
9907 | if (RPhi) { | ||||||||||
9908 | bool Erased = PendingMerges.erase(RPhi); | ||||||||||
9909 | assert(Erased && "Failed to erase RPhi!")((Erased && "Failed to erase RPhi!") ? static_cast< void> (0) : __assert_fail ("Erased && \"Failed to erase RPhi!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9909, __PRETTY_FUNCTION__)); | ||||||||||
9910 | (void)Erased; | ||||||||||
9911 | } | ||||||||||
9912 | }); | ||||||||||
9913 | |||||||||||
9914 | // Find respective Phis and check that they are not being pending. | ||||||||||
9915 | if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) | ||||||||||
9916 | if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { | ||||||||||
9917 | if (!PendingMerges.insert(Phi).second) | ||||||||||
9918 | return false; | ||||||||||
9919 | LPhi = Phi; | ||||||||||
9920 | } | ||||||||||
9921 | if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) | ||||||||||
9922 | if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { | ||||||||||
9923 | // If we detect a loop of Phi nodes being processed by this method, for | ||||||||||
9924 | // example: | ||||||||||
9925 | // | ||||||||||
9926 | // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] | ||||||||||
9927 | // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] | ||||||||||
9928 | // | ||||||||||
9929 | // we don't want to deal with a case that complex, so return conservative | ||||||||||
9930 | // answer false. | ||||||||||
9931 | if (!PendingMerges.insert(Phi).second) | ||||||||||
9932 | return false; | ||||||||||
9933 | RPhi = Phi; | ||||||||||
9934 | } | ||||||||||
9935 | |||||||||||
9936 | // If none of LHS, RHS is a Phi, nothing to do here. | ||||||||||
9937 | if (!LPhi && !RPhi) | ||||||||||
9938 | return false; | ||||||||||
9939 | |||||||||||
9940 | // If there is a SCEVUnknown Phi we are interested in, make it left. | ||||||||||
9941 | if (!LPhi) { | ||||||||||
9942 | std::swap(LHS, RHS); | ||||||||||
9943 | std::swap(FoundLHS, FoundRHS); | ||||||||||
9944 | std::swap(LPhi, RPhi); | ||||||||||
9945 | Pred = ICmpInst::getSwappedPredicate(Pred); | ||||||||||
9946 | } | ||||||||||
9947 | |||||||||||
9948 | assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!")((LPhi && "LPhi should definitely be a SCEVUnknown Phi!" ) ? static_cast<void> (0) : __assert_fail ("LPhi && \"LPhi should definitely be a SCEVUnknown Phi!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9948, __PRETTY_FUNCTION__)); | ||||||||||
9949 | const BasicBlock *LBB = LPhi->getParent(); | ||||||||||
9950 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); | ||||||||||
9951 | |||||||||||
9952 | auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { | ||||||||||
9953 | return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || | ||||||||||
9954 | isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || | ||||||||||
9955 | isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); | ||||||||||
9956 | }; | ||||||||||
9957 | |||||||||||
9958 | if (RPhi && RPhi->getParent() == LBB) { | ||||||||||
9959 | // Case one: RHS is also a SCEVUnknown Phi from the same basic block. | ||||||||||
9960 | // If we compare two Phis from the same block, and for each entry block | ||||||||||
9961 | // the predicate is true for incoming values from this block, then the | ||||||||||
9962 | // predicate is also true for the Phis. | ||||||||||
9963 | for (const BasicBlock *IncBB : predecessors(LBB)) { | ||||||||||
9964 | const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); | ||||||||||
9965 | const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); | ||||||||||
9966 | if (!ProvedEasily(L, R)) | ||||||||||
9967 | return false; | ||||||||||
9968 | } | ||||||||||
9969 | } else if (RAR && RAR->getLoop()->getHeader() == LBB) { | ||||||||||
9970 | // Case two: RHS is also a Phi from the same basic block, and it is an | ||||||||||
9971 | // AddRec. It means that there is a loop which has both AddRec and Unknown | ||||||||||
9972 | // PHIs, for it we can compare incoming values of AddRec from above the loop | ||||||||||
9973 | // and latch with their respective incoming values of LPhi. | ||||||||||
9974 | // TODO: Generalize to handle loops with many inputs in a header. | ||||||||||
9975 | if (LPhi->getNumIncomingValues() != 2) return false; | ||||||||||
9976 | |||||||||||
9977 | auto *RLoop = RAR->getLoop(); | ||||||||||
9978 | auto *Predecessor = RLoop->getLoopPredecessor(); | ||||||||||
9979 | assert(Predecessor && "Loop with AddRec with no predecessor?")((Predecessor && "Loop with AddRec with no predecessor?" ) ? static_cast<void> (0) : __assert_fail ("Predecessor && \"Loop with AddRec with no predecessor?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9979, __PRETTY_FUNCTION__)); | ||||||||||
9980 | const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); | ||||||||||
9981 | if (!ProvedEasily(L1, RAR->getStart())) | ||||||||||
9982 | return false; | ||||||||||
9983 | auto *Latch = RLoop->getLoopLatch(); | ||||||||||
9984 | assert(Latch && "Loop with AddRec with no latch?")((Latch && "Loop with AddRec with no latch?") ? static_cast <void> (0) : __assert_fail ("Latch && \"Loop with AddRec with no latch?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 9984, __PRETTY_FUNCTION__)); | ||||||||||
9985 | const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); | ||||||||||
9986 | if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) | ||||||||||
9987 | return false; | ||||||||||
9988 | } else { | ||||||||||
9989 | // In all other cases go over inputs of LHS and compare each of them to RHS, | ||||||||||
9990 | // the predicate is true for (LHS, RHS) if it is true for all such pairs. | ||||||||||
9991 | // At this point RHS is either a non-Phi, or it is a Phi from some block | ||||||||||
9992 | // different from LBB. | ||||||||||
9993 | for (const BasicBlock *IncBB : predecessors(LBB)) { | ||||||||||
9994 | // Check that RHS is available in this block. | ||||||||||
9995 | if (!dominates(RHS, IncBB)) | ||||||||||
9996 | return false; | ||||||||||
9997 | const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); | ||||||||||
9998 | if (!ProvedEasily(L, RHS)) | ||||||||||
9999 | return false; | ||||||||||
10000 | } | ||||||||||
10001 | } | ||||||||||
10002 | return true; | ||||||||||
10003 | } | ||||||||||
10004 | |||||||||||
10005 | bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, | ||||||||||
10006 | const SCEV *LHS, const SCEV *RHS, | ||||||||||
10007 | const SCEV *FoundLHS, | ||||||||||
10008 | const SCEV *FoundRHS) { | ||||||||||
10009 | if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) | ||||||||||
10010 | return true; | ||||||||||
10011 | |||||||||||
10012 | if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) | ||||||||||
10013 | return true; | ||||||||||
10014 | |||||||||||
10015 | return isImpliedCondOperandsHelper(Pred, LHS, RHS, | ||||||||||
10016 | FoundLHS, FoundRHS) || | ||||||||||
10017 | // ~x < ~y --> x > y | ||||||||||
10018 | isImpliedCondOperandsHelper(Pred, LHS, RHS, | ||||||||||
10019 | getNotSCEV(FoundRHS), | ||||||||||
10020 | getNotSCEV(FoundLHS)); | ||||||||||
10021 | } | ||||||||||
10022 | |||||||||||
10023 | /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? | ||||||||||
10024 | template <typename MinMaxExprType> | ||||||||||
10025 | static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, | ||||||||||
10026 | const SCEV *Candidate) { | ||||||||||
10027 | const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); | ||||||||||
10028 | if (!MinMaxExpr) | ||||||||||
10029 | return false; | ||||||||||
10030 | |||||||||||
10031 | return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); | ||||||||||
10032 | } | ||||||||||
10033 | |||||||||||
10034 | static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, | ||||||||||
10035 | ICmpInst::Predicate Pred, | ||||||||||
10036 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
10037 | // If both sides are affine addrecs for the same loop, with equal | ||||||||||
10038 | // steps, and we know the recurrences don't wrap, then we only | ||||||||||
10039 | // need to check the predicate on the starting values. | ||||||||||
10040 | |||||||||||
10041 | if (!ICmpInst::isRelational(Pred)) | ||||||||||
10042 | return false; | ||||||||||
10043 | |||||||||||
10044 | const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); | ||||||||||
10045 | if (!LAR) | ||||||||||
10046 | return false; | ||||||||||
10047 | const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); | ||||||||||
10048 | if (!RAR) | ||||||||||
10049 | return false; | ||||||||||
10050 | if (LAR->getLoop() != RAR->getLoop()) | ||||||||||
10051 | return false; | ||||||||||
10052 | if (!LAR->isAffine() || !RAR->isAffine()) | ||||||||||
10053 | return false; | ||||||||||
10054 | |||||||||||
10055 | if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) | ||||||||||
10056 | return false; | ||||||||||
10057 | |||||||||||
10058 | SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? | ||||||||||
10059 | SCEV::FlagNSW : SCEV::FlagNUW; | ||||||||||
10060 | if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) | ||||||||||
10061 | return false; | ||||||||||
10062 | |||||||||||
10063 | return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); | ||||||||||
10064 | } | ||||||||||
10065 | |||||||||||
10066 | /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max | ||||||||||
10067 | /// expression? | ||||||||||
10068 | static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, | ||||||||||
10069 | ICmpInst::Predicate Pred, | ||||||||||
10070 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
10071 | switch (Pred) { | ||||||||||
10072 | default: | ||||||||||
10073 | return false; | ||||||||||
10074 | |||||||||||
10075 | case ICmpInst::ICMP_SGE: | ||||||||||
10076 | std::swap(LHS, RHS); | ||||||||||
10077 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
10078 | case ICmpInst::ICMP_SLE: | ||||||||||
10079 | return | ||||||||||
10080 | // min(A, ...) <= A | ||||||||||
10081 | IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || | ||||||||||
10082 | // A <= max(A, ...) | ||||||||||
10083 | IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); | ||||||||||
10084 | |||||||||||
10085 | case ICmpInst::ICMP_UGE: | ||||||||||
10086 | std::swap(LHS, RHS); | ||||||||||
10087 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
10088 | case ICmpInst::ICMP_ULE: | ||||||||||
10089 | return | ||||||||||
10090 | // min(A, ...) <= A | ||||||||||
10091 | IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || | ||||||||||
10092 | // A <= max(A, ...) | ||||||||||
10093 | IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); | ||||||||||
10094 | } | ||||||||||
10095 | |||||||||||
10096 | llvm_unreachable("covered switch fell through?!")::llvm::llvm_unreachable_internal("covered switch fell through?!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10096); | ||||||||||
10097 | } | ||||||||||
10098 | |||||||||||
10099 | bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, | ||||||||||
10100 | const SCEV *LHS, const SCEV *RHS, | ||||||||||
10101 | const SCEV *FoundLHS, | ||||||||||
10102 | const SCEV *FoundRHS, | ||||||||||
10103 | unsigned Depth) { | ||||||||||
10104 | assert(getTypeSizeInBits(LHS->getType()) ==((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS ->getType()) && "LHS and RHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10106, __PRETTY_FUNCTION__)) | ||||||||||
10105 | getTypeSizeInBits(RHS->getType()) &&((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS ->getType()) && "LHS and RHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10106, __PRETTY_FUNCTION__)) | ||||||||||
10106 | "LHS and RHS have different sizes?")((getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS ->getType()) && "LHS and RHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(LHS->getType()) == getTypeSizeInBits(RHS->getType()) && \"LHS and RHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10106, __PRETTY_FUNCTION__)); | ||||||||||
10107 | assert(getTypeSizeInBits(FoundLHS->getType()) ==((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits (FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10109, __PRETTY_FUNCTION__)) | ||||||||||
10108 | getTypeSizeInBits(FoundRHS->getType()) &&((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits (FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10109, __PRETTY_FUNCTION__)) | ||||||||||
10109 | "FoundLHS and FoundRHS have different sizes?")((getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits (FoundRHS->getType()) && "FoundLHS and FoundRHS have different sizes?" ) ? static_cast<void> (0) : __assert_fail ("getTypeSizeInBits(FoundLHS->getType()) == getTypeSizeInBits(FoundRHS->getType()) && \"FoundLHS and FoundRHS have different sizes?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10109, __PRETTY_FUNCTION__)); | ||||||||||
10110 | // We want to avoid hurting the compile time with analysis of too big trees. | ||||||||||
10111 | if (Depth > MaxSCEVOperationsImplicationDepth) | ||||||||||
10112 | return false; | ||||||||||
10113 | // We only want to work with ICMP_SGT comparison so far. | ||||||||||
10114 | // TODO: Extend to ICMP_UGT? | ||||||||||
10115 | if (Pred == ICmpInst::ICMP_SLT) { | ||||||||||
10116 | Pred = ICmpInst::ICMP_SGT; | ||||||||||
10117 | std::swap(LHS, RHS); | ||||||||||
10118 | std::swap(FoundLHS, FoundRHS); | ||||||||||
10119 | } | ||||||||||
10120 | if (Pred != ICmpInst::ICMP_SGT) | ||||||||||
10121 | return false; | ||||||||||
10122 | |||||||||||
10123 | auto GetOpFromSExt = [&](const SCEV *S) { | ||||||||||
10124 | if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) | ||||||||||
10125 | return Ext->getOperand(); | ||||||||||
10126 | // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off | ||||||||||
10127 | // the constant in some cases. | ||||||||||
10128 | return S; | ||||||||||
10129 | }; | ||||||||||
10130 | |||||||||||
10131 | // Acquire values from extensions. | ||||||||||
10132 | auto *OrigLHS = LHS; | ||||||||||
10133 | auto *OrigFoundLHS = FoundLHS; | ||||||||||
10134 | LHS = GetOpFromSExt(LHS); | ||||||||||
10135 | FoundLHS = GetOpFromSExt(FoundLHS); | ||||||||||
10136 | |||||||||||
10137 | // Is the SGT predicate can be proved trivially or using the found context. | ||||||||||
10138 | auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { | ||||||||||
10139 | return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || | ||||||||||
10140 | isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, | ||||||||||
10141 | FoundRHS, Depth + 1); | ||||||||||
10142 | }; | ||||||||||
10143 | |||||||||||
10144 | if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { | ||||||||||
10145 | // We want to avoid creation of any new non-constant SCEV. Since we are | ||||||||||
10146 | // going to compare the operands to RHS, we should be certain that we don't | ||||||||||
10147 | // need any size extensions for this. So let's decline all cases when the | ||||||||||
10148 | // sizes of types of LHS and RHS do not match. | ||||||||||
10149 | // TODO: Maybe try to get RHS from sext to catch more cases? | ||||||||||
10150 | if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) | ||||||||||
10151 | return false; | ||||||||||
10152 | |||||||||||
10153 | // Should not overflow. | ||||||||||
10154 | if (!LHSAddExpr->hasNoSignedWrap()) | ||||||||||
10155 | return false; | ||||||||||
10156 | |||||||||||
10157 | auto *LL = LHSAddExpr->getOperand(0); | ||||||||||
10158 | auto *LR = LHSAddExpr->getOperand(1); | ||||||||||
10159 | auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); | ||||||||||
10160 | |||||||||||
10161 | // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. | ||||||||||
10162 | auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { | ||||||||||
10163 | return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); | ||||||||||
10164 | }; | ||||||||||
10165 | // Try to prove the following rule: | ||||||||||
10166 | // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). | ||||||||||
10167 | // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). | ||||||||||
10168 | if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) | ||||||||||
10169 | return true; | ||||||||||
10170 | } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { | ||||||||||
10171 | Value *LL, *LR; | ||||||||||
10172 | // FIXME: Once we have SDiv implemented, we can get rid of this matching. | ||||||||||
10173 | |||||||||||
10174 | using namespace llvm::PatternMatch; | ||||||||||
10175 | |||||||||||
10176 | if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { | ||||||||||
10177 | // Rules for division. | ||||||||||
10178 | // We are going to perform some comparisons with Denominator and its | ||||||||||
10179 | // derivative expressions. In general case, creating a SCEV for it may | ||||||||||
10180 | // lead to a complex analysis of the entire graph, and in particular it | ||||||||||
10181 | // can request trip count recalculation for the same loop. This would | ||||||||||
10182 | // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid | ||||||||||
10183 | // this, we only want to create SCEVs that are constants in this section. | ||||||||||
10184 | // So we bail if Denominator is not a constant. | ||||||||||
10185 | if (!isa<ConstantInt>(LR)) | ||||||||||
10186 | return false; | ||||||||||
10187 | |||||||||||
10188 | auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); | ||||||||||
10189 | |||||||||||
10190 | // We want to make sure that LHS = FoundLHS / Denominator. If it is so, | ||||||||||
10191 | // then a SCEV for the numerator already exists and matches with FoundLHS. | ||||||||||
10192 | auto *Numerator = getExistingSCEV(LL); | ||||||||||
10193 | if (!Numerator || Numerator->getType() != FoundLHS->getType()) | ||||||||||
10194 | return false; | ||||||||||
10195 | |||||||||||
10196 | // Make sure that the numerator matches with FoundLHS and the denominator | ||||||||||
10197 | // is positive. | ||||||||||
10198 | if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) | ||||||||||
10199 | return false; | ||||||||||
10200 | |||||||||||
10201 | auto *DTy = Denominator->getType(); | ||||||||||
10202 | auto *FRHSTy = FoundRHS->getType(); | ||||||||||
10203 | if (DTy->isPointerTy() != FRHSTy->isPointerTy()) | ||||||||||
10204 | // One of types is a pointer and another one is not. We cannot extend | ||||||||||
10205 | // them properly to a wider type, so let us just reject this case. | ||||||||||
10206 | // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help | ||||||||||
10207 | // to avoid this check. | ||||||||||
10208 | return false; | ||||||||||
10209 | |||||||||||
10210 | // Given that: | ||||||||||
10211 | // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. | ||||||||||
10212 | auto *WTy = getWiderType(DTy, FRHSTy); | ||||||||||
10213 | auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); | ||||||||||
10214 | auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); | ||||||||||
10215 | |||||||||||
10216 | // Try to prove the following rule: | ||||||||||
10217 | // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). | ||||||||||
10218 | // For example, given that FoundLHS > 2. It means that FoundLHS is at | ||||||||||
10219 | // least 3. If we divide it by Denominator < 4, we will have at least 1. | ||||||||||
10220 | auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); | ||||||||||
10221 | if (isKnownNonPositive(RHS) && | ||||||||||
10222 | IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) | ||||||||||
10223 | return true; | ||||||||||
10224 | |||||||||||
10225 | // Try to prove the following rule: | ||||||||||
10226 | // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). | ||||||||||
10227 | // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. | ||||||||||
10228 | // If we divide it by Denominator > 2, then: | ||||||||||
10229 | // 1. If FoundLHS is negative, then the result is 0. | ||||||||||
10230 | // 2. If FoundLHS is non-negative, then the result is non-negative. | ||||||||||
10231 | // Anyways, the result is non-negative. | ||||||||||
10232 | auto *MinusOne = getNegativeSCEV(getOne(WTy)); | ||||||||||
10233 | auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); | ||||||||||
10234 | if (isKnownNegative(RHS) && | ||||||||||
10235 | IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) | ||||||||||
10236 | return true; | ||||||||||
10237 | } | ||||||||||
10238 | } | ||||||||||
10239 | |||||||||||
10240 | // If our expression contained SCEVUnknown Phis, and we split it down and now | ||||||||||
10241 | // need to prove something for them, try to prove the predicate for every | ||||||||||
10242 | // possible incoming values of those Phis. | ||||||||||
10243 | if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) | ||||||||||
10244 | return true; | ||||||||||
10245 | |||||||||||
10246 | return false; | ||||||||||
10247 | } | ||||||||||
10248 | |||||||||||
10249 | static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, | ||||||||||
10250 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
10251 | // zext x u<= sext x, sext x s<= zext x | ||||||||||
10252 | switch (Pred) { | ||||||||||
10253 | case ICmpInst::ICMP_SGE: | ||||||||||
10254 | std::swap(LHS, RHS); | ||||||||||
10255 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
10256 | case ICmpInst::ICMP_SLE: { | ||||||||||
10257 | // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. | ||||||||||
10258 | const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); | ||||||||||
10259 | const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); | ||||||||||
10260 | if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) | ||||||||||
10261 | return true; | ||||||||||
10262 | break; | ||||||||||
10263 | } | ||||||||||
10264 | case ICmpInst::ICMP_UGE: | ||||||||||
10265 | std::swap(LHS, RHS); | ||||||||||
10266 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
10267 | case ICmpInst::ICMP_ULE: { | ||||||||||
10268 | // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. | ||||||||||
10269 | const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); | ||||||||||
10270 | const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); | ||||||||||
10271 | if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) | ||||||||||
10272 | return true; | ||||||||||
10273 | break; | ||||||||||
10274 | } | ||||||||||
10275 | default: | ||||||||||
10276 | break; | ||||||||||
10277 | }; | ||||||||||
10278 | return false; | ||||||||||
10279 | } | ||||||||||
10280 | |||||||||||
10281 | bool | ||||||||||
10282 | ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, | ||||||||||
10283 | const SCEV *LHS, const SCEV *RHS) { | ||||||||||
10284 | return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || | ||||||||||
10285 | isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || | ||||||||||
10286 | IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || | ||||||||||
10287 | IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || | ||||||||||
10288 | isKnownPredicateViaNoOverflow(Pred, LHS, RHS); | ||||||||||
10289 | } | ||||||||||
10290 | |||||||||||
10291 | bool | ||||||||||
10292 | ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, | ||||||||||
10293 | const SCEV *LHS, const SCEV *RHS, | ||||||||||
10294 | const SCEV *FoundLHS, | ||||||||||
10295 | const SCEV *FoundRHS) { | ||||||||||
10296 | switch (Pred) { | ||||||||||
10297 | default: llvm_unreachable("Unexpected ICmpInst::Predicate value!")::llvm::llvm_unreachable_internal("Unexpected ICmpInst::Predicate value!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10297); | ||||||||||
10298 | case ICmpInst::ICMP_EQ: | ||||||||||
10299 | case ICmpInst::ICMP_NE: | ||||||||||
10300 | if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) | ||||||||||
10301 | return true; | ||||||||||
10302 | break; | ||||||||||
10303 | case ICmpInst::ICMP_SLT: | ||||||||||
10304 | case ICmpInst::ICMP_SLE: | ||||||||||
10305 | if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && | ||||||||||
10306 | isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) | ||||||||||
10307 | return true; | ||||||||||
10308 | break; | ||||||||||
10309 | case ICmpInst::ICMP_SGT: | ||||||||||
10310 | case ICmpInst::ICMP_SGE: | ||||||||||
10311 | if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && | ||||||||||
10312 | isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) | ||||||||||
10313 | return true; | ||||||||||
10314 | break; | ||||||||||
10315 | case ICmpInst::ICMP_ULT: | ||||||||||
10316 | case ICmpInst::ICMP_ULE: | ||||||||||
10317 | if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && | ||||||||||
10318 | isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) | ||||||||||
10319 | return true; | ||||||||||
10320 | break; | ||||||||||
10321 | case ICmpInst::ICMP_UGT: | ||||||||||
10322 | case ICmpInst::ICMP_UGE: | ||||||||||
10323 | if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && | ||||||||||
10324 | isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) | ||||||||||
10325 | return true; | ||||||||||
10326 | break; | ||||||||||
10327 | } | ||||||||||
10328 | |||||||||||
10329 | // Maybe it can be proved via operations? | ||||||||||
10330 | if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) | ||||||||||
10331 | return true; | ||||||||||
10332 | |||||||||||
10333 | return false; | ||||||||||
10334 | } | ||||||||||
10335 | |||||||||||
10336 | bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, | ||||||||||
10337 | const SCEV *LHS, | ||||||||||
10338 | const SCEV *RHS, | ||||||||||
10339 | const SCEV *FoundLHS, | ||||||||||
10340 | const SCEV *FoundRHS) { | ||||||||||
10341 | if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) | ||||||||||
10342 | // The restriction on `FoundRHS` be lifted easily -- it exists only to | ||||||||||
10343 | // reduce the compile time impact of this optimization. | ||||||||||
10344 | return false; | ||||||||||
10345 | |||||||||||
10346 | Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); | ||||||||||
10347 | if (!Addend) | ||||||||||
10348 | return false; | ||||||||||
10349 | |||||||||||
10350 | const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); | ||||||||||
10351 | |||||||||||
10352 | // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the | ||||||||||
10353 | // antecedent "`FoundLHS` `Pred` `FoundRHS`". | ||||||||||
10354 | ConstantRange FoundLHSRange = | ||||||||||
10355 | ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); | ||||||||||
10356 | |||||||||||
10357 | // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: | ||||||||||
10358 | ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); | ||||||||||
10359 | |||||||||||
10360 | // We can also compute the range of values for `LHS` that satisfy the | ||||||||||
10361 | // consequent, "`LHS` `Pred` `RHS`": | ||||||||||
10362 | const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); | ||||||||||
10363 | ConstantRange SatisfyingLHSRange = | ||||||||||
10364 | ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); | ||||||||||
10365 | |||||||||||
10366 | // The antecedent implies the consequent if every value of `LHS` that | ||||||||||
10367 | // satisfies the antecedent also satisfies the consequent. | ||||||||||
10368 | return SatisfyingLHSRange.contains(LHSRange); | ||||||||||
10369 | } | ||||||||||
10370 | |||||||||||
10371 | bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, | ||||||||||
10372 | bool IsSigned, bool NoWrap) { | ||||||||||
10373 | assert(isKnownPositive(Stride) && "Positive stride expected!")((isKnownPositive(Stride) && "Positive stride expected!" ) ? static_cast<void> (0) : __assert_fail ("isKnownPositive(Stride) && \"Positive stride expected!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10373, __PRETTY_FUNCTION__)); | ||||||||||
10374 | |||||||||||
10375 | if (NoWrap) return false; | ||||||||||
10376 | |||||||||||
10377 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); | ||||||||||
10378 | const SCEV *One = getOne(Stride->getType()); | ||||||||||
10379 | |||||||||||
10380 | if (IsSigned) { | ||||||||||
10381 | APInt MaxRHS = getSignedRangeMax(RHS); | ||||||||||
10382 | APInt MaxValue = APInt::getSignedMaxValue(BitWidth); | ||||||||||
10383 | APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); | ||||||||||
10384 | |||||||||||
10385 | // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! | ||||||||||
10386 | return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); | ||||||||||
10387 | } | ||||||||||
10388 | |||||||||||
10389 | APInt MaxRHS = getUnsignedRangeMax(RHS); | ||||||||||
10390 | APInt MaxValue = APInt::getMaxValue(BitWidth); | ||||||||||
10391 | APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); | ||||||||||
10392 | |||||||||||
10393 | // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! | ||||||||||
10394 | return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); | ||||||||||
10395 | } | ||||||||||
10396 | |||||||||||
10397 | bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, | ||||||||||
10398 | bool IsSigned, bool NoWrap) { | ||||||||||
10399 | if (NoWrap) return false; | ||||||||||
10400 | |||||||||||
10401 | unsigned BitWidth = getTypeSizeInBits(RHS->getType()); | ||||||||||
10402 | const SCEV *One = getOne(Stride->getType()); | ||||||||||
10403 | |||||||||||
10404 | if (IsSigned) { | ||||||||||
10405 | APInt MinRHS = getSignedRangeMin(RHS); | ||||||||||
10406 | APInt MinValue = APInt::getSignedMinValue(BitWidth); | ||||||||||
10407 | APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); | ||||||||||
10408 | |||||||||||
10409 | // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! | ||||||||||
10410 | return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); | ||||||||||
10411 | } | ||||||||||
10412 | |||||||||||
10413 | APInt MinRHS = getUnsignedRangeMin(RHS); | ||||||||||
10414 | APInt MinValue = APInt::getMinValue(BitWidth); | ||||||||||
10415 | APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); | ||||||||||
10416 | |||||||||||
10417 | // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! | ||||||||||
10418 | return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); | ||||||||||
10419 | } | ||||||||||
10420 | |||||||||||
10421 | const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, | ||||||||||
10422 | bool Equality) { | ||||||||||
10423 | const SCEV *One = getOne(Step->getType()); | ||||||||||
10424 | Delta = Equality ? getAddExpr(Delta, Step) | ||||||||||
10425 | : getAddExpr(Delta, getMinusSCEV(Step, One)); | ||||||||||
10426 | return getUDivExpr(Delta, Step); | ||||||||||
10427 | } | ||||||||||
10428 | |||||||||||
10429 | const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, | ||||||||||
10430 | const SCEV *Stride, | ||||||||||
10431 | const SCEV *End, | ||||||||||
10432 | unsigned BitWidth, | ||||||||||
10433 | bool IsSigned) { | ||||||||||
10434 | |||||||||||
10435 | assert(!isKnownNonPositive(Stride) &&((!isKnownNonPositive(Stride) && "Stride is expected strictly positive!" ) ? static_cast<void> (0) : __assert_fail ("!isKnownNonPositive(Stride) && \"Stride is expected strictly positive!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10436, __PRETTY_FUNCTION__)) | ||||||||||
10436 | "Stride is expected strictly positive!")((!isKnownNonPositive(Stride) && "Stride is expected strictly positive!" ) ? static_cast<void> (0) : __assert_fail ("!isKnownNonPositive(Stride) && \"Stride is expected strictly positive!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10436, __PRETTY_FUNCTION__)); | ||||||||||
10437 | // Calculate the maximum backedge count based on the range of values | ||||||||||
10438 | // permitted by Start, End, and Stride. | ||||||||||
10439 | const SCEV *MaxBECount; | ||||||||||
10440 | APInt MinStart = | ||||||||||
10441 | IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); | ||||||||||
10442 | |||||||||||
10443 | APInt StrideForMaxBECount = | ||||||||||
10444 | IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); | ||||||||||
10445 | |||||||||||
10446 | // We already know that the stride is positive, so we paper over conservatism | ||||||||||
10447 | // in our range computation by forcing StrideForMaxBECount to be at least one. | ||||||||||
10448 | // In theory this is unnecessary, but we expect MaxBECount to be a | ||||||||||
10449 | // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there | ||||||||||
10450 | // is nothing to constant fold it to). | ||||||||||
10451 | APInt One(BitWidth, 1, IsSigned); | ||||||||||
10452 | StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); | ||||||||||
10453 | |||||||||||
10454 | APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) | ||||||||||
10455 | : APInt::getMaxValue(BitWidth); | ||||||||||
10456 | APInt Limit = MaxValue - (StrideForMaxBECount - 1); | ||||||||||
10457 | |||||||||||
10458 | // Although End can be a MAX expression we estimate MaxEnd considering only | ||||||||||
10459 | // the case End = RHS of the loop termination condition. This is safe because | ||||||||||
10460 | // in the other case (End - Start) is zero, leading to a zero maximum backedge | ||||||||||
10461 | // taken count. | ||||||||||
10462 | APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) | ||||||||||
10463 | : APIntOps::umin(getUnsignedRangeMax(End), Limit); | ||||||||||
10464 | |||||||||||
10465 | MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, | ||||||||||
10466 | getConstant(StrideForMaxBECount) /* Step */, | ||||||||||
10467 | false /* Equality */); | ||||||||||
10468 | |||||||||||
10469 | return MaxBECount; | ||||||||||
10470 | } | ||||||||||
10471 | |||||||||||
10472 | ScalarEvolution::ExitLimit | ||||||||||
10473 | ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, | ||||||||||
10474 | const Loop *L, bool IsSigned, | ||||||||||
10475 | bool ControlsExit, bool AllowPredicates) { | ||||||||||
10476 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; | ||||||||||
10477 | |||||||||||
10478 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); | ||||||||||
10479 | bool PredicatedIV = false; | ||||||||||
10480 | |||||||||||
10481 | if (!IV && AllowPredicates) { | ||||||||||
10482 | // Try to make this an AddRec using runtime tests, in the first X | ||||||||||
10483 | // iterations of this loop, where X is the SCEV expression found by the | ||||||||||
10484 | // algorithm below. | ||||||||||
10485 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); | ||||||||||
10486 | PredicatedIV = true; | ||||||||||
10487 | } | ||||||||||
10488 | |||||||||||
10489 | // Avoid weird loops | ||||||||||
10490 | if (!IV || IV->getLoop() != L || !IV->isAffine()) | ||||||||||
10491 | return getCouldNotCompute(); | ||||||||||
10492 | |||||||||||
10493 | bool NoWrap = ControlsExit && | ||||||||||
10494 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); | ||||||||||
10495 | |||||||||||
10496 | const SCEV *Stride = IV->getStepRecurrence(*this); | ||||||||||
10497 | |||||||||||
10498 | bool PositiveStride = isKnownPositive(Stride); | ||||||||||
10499 | |||||||||||
10500 | // Avoid negative or zero stride values. | ||||||||||
10501 | if (!PositiveStride) { | ||||||||||
10502 | // We can compute the correct backedge taken count for loops with unknown | ||||||||||
10503 | // strides if we can prove that the loop is not an infinite loop with side | ||||||||||
10504 | // effects. Here's the loop structure we are trying to handle - | ||||||||||
10505 | // | ||||||||||
10506 | // i = start | ||||||||||
10507 | // do { | ||||||||||
10508 | // A[i] = i; | ||||||||||
10509 | // i += s; | ||||||||||
10510 | // } while (i < end); | ||||||||||
10511 | // | ||||||||||
10512 | // The backedge taken count for such loops is evaluated as - | ||||||||||
10513 | // (max(end, start + stride) - start - 1) /u stride | ||||||||||
10514 | // | ||||||||||
10515 | // The additional preconditions that we need to check to prove correctness | ||||||||||
10516 | // of the above formula is as follows - | ||||||||||
10517 | // | ||||||||||
10518 | // a) IV is either nuw or nsw depending upon signedness (indicated by the | ||||||||||
10519 | // NoWrap flag). | ||||||||||
10520 | // b) loop is single exit with no side effects. | ||||||||||
10521 | // | ||||||||||
10522 | // | ||||||||||
10523 | // Precondition a) implies that if the stride is negative, this is a single | ||||||||||
10524 | // trip loop. The backedge taken count formula reduces to zero in this case. | ||||||||||
10525 | // | ||||||||||
10526 | // Precondition b) implies that the unknown stride cannot be zero otherwise | ||||||||||
10527 | // we have UB. | ||||||||||
10528 | // | ||||||||||
10529 | // The positive stride case is the same as isKnownPositive(Stride) returning | ||||||||||
10530 | // true (original behavior of the function). | ||||||||||
10531 | // | ||||||||||
10532 | // We want to make sure that the stride is truly unknown as there are edge | ||||||||||
10533 | // cases where ScalarEvolution propagates no wrap flags to the | ||||||||||
10534 | // post-increment/decrement IV even though the increment/decrement operation | ||||||||||
10535 | // itself is wrapping. The computed backedge taken count may be wrong in | ||||||||||
10536 | // such cases. This is prevented by checking that the stride is not known to | ||||||||||
10537 | // be either positive or non-positive. For example, no wrap flags are | ||||||||||
10538 | // propagated to the post-increment IV of this loop with a trip count of 2 - | ||||||||||
10539 | // | ||||||||||
10540 | // unsigned char i; | ||||||||||
10541 | // for(i=127; i<128; i+=129) | ||||||||||
10542 | // A[i] = i; | ||||||||||
10543 | // | ||||||||||
10544 | if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || | ||||||||||
10545 | !loopHasNoSideEffects(L)) | ||||||||||
10546 | return getCouldNotCompute(); | ||||||||||
10547 | } else if (!Stride->isOne() && | ||||||||||
10548 | doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) | ||||||||||
10549 | // Avoid proven overflow cases: this will ensure that the backedge taken | ||||||||||
10550 | // count will not generate any unsigned overflow. Relaxed no-overflow | ||||||||||
10551 | // conditions exploit NoWrapFlags, allowing to optimize in presence of | ||||||||||
10552 | // undefined behaviors like the case of C language. | ||||||||||
10553 | return getCouldNotCompute(); | ||||||||||
10554 | |||||||||||
10555 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT | ||||||||||
10556 | : ICmpInst::ICMP_ULT; | ||||||||||
10557 | const SCEV *Start = IV->getStart(); | ||||||||||
10558 | const SCEV *End = RHS; | ||||||||||
10559 | // When the RHS is not invariant, we do not know the end bound of the loop and | ||||||||||
10560 | // cannot calculate the ExactBECount needed by ExitLimit. However, we can | ||||||||||
10561 | // calculate the MaxBECount, given the start, stride and max value for the end | ||||||||||
10562 | // bound of the loop (RHS), and the fact that IV does not overflow (which is | ||||||||||
10563 | // checked above). | ||||||||||
10564 | if (!isLoopInvariant(RHS, L)) { | ||||||||||
10565 | const SCEV *MaxBECount = computeMaxBECountForLT( | ||||||||||
10566 | Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); | ||||||||||
10567 | return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, | ||||||||||
10568 | false /*MaxOrZero*/, Predicates); | ||||||||||
10569 | } | ||||||||||
10570 | // If the backedge is taken at least once, then it will be taken | ||||||||||
10571 | // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start | ||||||||||
10572 | // is the LHS value of the less-than comparison the first time it is evaluated | ||||||||||
10573 | // and End is the RHS. | ||||||||||
10574 | const SCEV *BECountIfBackedgeTaken = | ||||||||||
10575 | computeBECount(getMinusSCEV(End, Start), Stride, false); | ||||||||||
10576 | // If the loop entry is guarded by the result of the backedge test of the | ||||||||||
10577 | // first loop iteration, then we know the backedge will be taken at least | ||||||||||
10578 | // once and so the backedge taken count is as above. If not then we use the | ||||||||||
10579 | // expression (max(End,Start)-Start)/Stride to describe the backedge count, | ||||||||||
10580 | // as if the backedge is taken at least once max(End,Start) is End and so the | ||||||||||
10581 | // result is as above, and if not max(End,Start) is Start so we get a backedge | ||||||||||
10582 | // count of zero. | ||||||||||
10583 | const SCEV *BECount; | ||||||||||
10584 | if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) | ||||||||||
10585 | BECount = BECountIfBackedgeTaken; | ||||||||||
10586 | else { | ||||||||||
10587 | // If we know that RHS >= Start in the context of loop, then we know that | ||||||||||
10588 | // max(RHS, Start) = RHS at this point. | ||||||||||
10589 | if (isLoopEntryGuardedByCond( | ||||||||||
10590 | L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) | ||||||||||
10591 | End = RHS; | ||||||||||
10592 | else | ||||||||||
10593 | End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); | ||||||||||
10594 | BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); | ||||||||||
10595 | } | ||||||||||
10596 | |||||||||||
10597 | const SCEV *MaxBECount; | ||||||||||
10598 | bool MaxOrZero = false; | ||||||||||
10599 | if (isa<SCEVConstant>(BECount)) | ||||||||||
10600 | MaxBECount = BECount; | ||||||||||
10601 | else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { | ||||||||||
10602 | // If we know exactly how many times the backedge will be taken if it's | ||||||||||
10603 | // taken at least once, then the backedge count will either be that or | ||||||||||
10604 | // zero. | ||||||||||
10605 | MaxBECount = BECountIfBackedgeTaken; | ||||||||||
10606 | MaxOrZero = true; | ||||||||||
10607 | } else { | ||||||||||
10608 | MaxBECount = computeMaxBECountForLT( | ||||||||||
10609 | Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); | ||||||||||
10610 | } | ||||||||||
10611 | |||||||||||
10612 | if (isa<SCEVCouldNotCompute>(MaxBECount) && | ||||||||||
10613 | !isa<SCEVCouldNotCompute>(BECount)) | ||||||||||
10614 | MaxBECount = getConstant(getUnsignedRangeMax(BECount)); | ||||||||||
10615 | |||||||||||
10616 | return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); | ||||||||||
10617 | } | ||||||||||
10618 | |||||||||||
10619 | ScalarEvolution::ExitLimit | ||||||||||
10620 | ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, | ||||||||||
10621 | const Loop *L, bool IsSigned, | ||||||||||
10622 | bool ControlsExit, bool AllowPredicates) { | ||||||||||
10623 | SmallPtrSet<const SCEVPredicate *, 4> Predicates; | ||||||||||
10624 | // We handle only IV > Invariant | ||||||||||
10625 | if (!isLoopInvariant(RHS, L)) | ||||||||||
10626 | return getCouldNotCompute(); | ||||||||||
10627 | |||||||||||
10628 | const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); | ||||||||||
10629 | if (!IV && AllowPredicates) | ||||||||||
10630 | // Try to make this an AddRec using runtime tests, in the first X | ||||||||||
10631 | // iterations of this loop, where X is the SCEV expression found by the | ||||||||||
10632 | // algorithm below. | ||||||||||
10633 | IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); | ||||||||||
10634 | |||||||||||
10635 | // Avoid weird loops | ||||||||||
10636 | if (!IV || IV->getLoop() != L || !IV->isAffine()) | ||||||||||
10637 | return getCouldNotCompute(); | ||||||||||
10638 | |||||||||||
10639 | bool NoWrap = ControlsExit && | ||||||||||
10640 | IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); | ||||||||||
10641 | |||||||||||
10642 | const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); | ||||||||||
10643 | |||||||||||
10644 | // Avoid negative or zero stride values | ||||||||||
10645 | if (!isKnownPositive(Stride)) | ||||||||||
10646 | return getCouldNotCompute(); | ||||||||||
10647 | |||||||||||
10648 | // Avoid proven overflow cases: this will ensure that the backedge taken count | ||||||||||
10649 | // will not generate any unsigned overflow. Relaxed no-overflow conditions | ||||||||||
10650 | // exploit NoWrapFlags, allowing to optimize in presence of undefined | ||||||||||
10651 | // behaviors like the case of C language. | ||||||||||
10652 | if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) | ||||||||||
10653 | return getCouldNotCompute(); | ||||||||||
10654 | |||||||||||
10655 | ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT | ||||||||||
10656 | : ICmpInst::ICMP_UGT; | ||||||||||
10657 | |||||||||||
10658 | const SCEV *Start = IV->getStart(); | ||||||||||
10659 | const SCEV *End = RHS; | ||||||||||
10660 | if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { | ||||||||||
10661 | // If we know that Start >= RHS in the context of loop, then we know that | ||||||||||
10662 | // min(RHS, Start) = RHS at this point. | ||||||||||
10663 | if (isLoopEntryGuardedByCond( | ||||||||||
10664 | L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) | ||||||||||
10665 | End = RHS; | ||||||||||
10666 | else | ||||||||||
10667 | End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); | ||||||||||
10668 | } | ||||||||||
10669 | |||||||||||
10670 | const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); | ||||||||||
10671 | |||||||||||
10672 | APInt MaxStart = IsSigned ? getSignedRangeMax(Start) | ||||||||||
10673 | : getUnsignedRangeMax(Start); | ||||||||||
10674 | |||||||||||
10675 | APInt MinStride = IsSigned ? getSignedRangeMin(Stride) | ||||||||||
10676 | : getUnsignedRangeMin(Stride); | ||||||||||
10677 | |||||||||||
10678 | unsigned BitWidth = getTypeSizeInBits(LHS->getType()); | ||||||||||
10679 | APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) | ||||||||||
10680 | : APInt::getMinValue(BitWidth) + (MinStride - 1); | ||||||||||
10681 | |||||||||||
10682 | // Although End can be a MIN expression we estimate MinEnd considering only | ||||||||||
10683 | // the case End = RHS. This is safe because in the other case (Start - End) | ||||||||||
10684 | // is zero, leading to a zero maximum backedge taken count. | ||||||||||
10685 | APInt MinEnd = | ||||||||||
10686 | IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) | ||||||||||
10687 | : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); | ||||||||||
10688 | |||||||||||
10689 | const SCEV *MaxBECount = isa<SCEVConstant>(BECount) | ||||||||||
10690 | ? BECount | ||||||||||
10691 | : computeBECount(getConstant(MaxStart - MinEnd), | ||||||||||
10692 | getConstant(MinStride), false); | ||||||||||
10693 | |||||||||||
10694 | if (isa<SCEVCouldNotCompute>(MaxBECount)) | ||||||||||
10695 | MaxBECount = BECount; | ||||||||||
10696 | |||||||||||
10697 | return ExitLimit(BECount, MaxBECount, false, Predicates); | ||||||||||
10698 | } | ||||||||||
10699 | |||||||||||
10700 | const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, | ||||||||||
10701 | ScalarEvolution &SE) const { | ||||||||||
10702 | if (Range.isFullSet()) // Infinite loop. | ||||||||||
10703 | return SE.getCouldNotCompute(); | ||||||||||
10704 | |||||||||||
10705 | // If the start is a non-zero constant, shift the range to simplify things. | ||||||||||
10706 | if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) | ||||||||||
10707 | if (!SC->getValue()->isZero()) { | ||||||||||
10708 | SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); | ||||||||||
10709 | Operands[0] = SE.getZero(SC->getType()); | ||||||||||
10710 | const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), | ||||||||||
10711 | getNoWrapFlags(FlagNW)); | ||||||||||
10712 | if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) | ||||||||||
10713 | return ShiftedAddRec->getNumIterationsInRange( | ||||||||||
10714 | Range.subtract(SC->getAPInt()), SE); | ||||||||||
10715 | // This is strange and shouldn't happen. | ||||||||||
10716 | return SE.getCouldNotCompute(); | ||||||||||
10717 | } | ||||||||||
10718 | |||||||||||
10719 | // The only time we can solve this is when we have all constant indices. | ||||||||||
10720 | // Otherwise, we cannot determine the overflow conditions. | ||||||||||
10721 | if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) | ||||||||||
10722 | return SE.getCouldNotCompute(); | ||||||||||
10723 | |||||||||||
10724 | // Okay at this point we know that all elements of the chrec are constants and | ||||||||||
10725 | // that the start element is zero. | ||||||||||
10726 | |||||||||||
10727 | // First check to see if the range contains zero. If not, the first | ||||||||||
10728 | // iteration exits. | ||||||||||
10729 | unsigned BitWidth = SE.getTypeSizeInBits(getType()); | ||||||||||
10730 | if (!Range.contains(APInt(BitWidth, 0))) | ||||||||||
10731 | return SE.getZero(getType()); | ||||||||||
10732 | |||||||||||
10733 | if (isAffine()) { | ||||||||||
10734 | // If this is an affine expression then we have this situation: | ||||||||||
10735 | // Solve {0,+,A} in Range === Ax in Range | ||||||||||
10736 | |||||||||||
10737 | // We know that zero is in the range. If A is positive then we know that | ||||||||||
10738 | // the upper value of the range must be the first possible exit value. | ||||||||||
10739 | // If A is negative then the lower of the range is the last possible loop | ||||||||||
10740 | // value. Also note that we already checked for a full range. | ||||||||||
10741 | APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); | ||||||||||
10742 | APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); | ||||||||||
10743 | |||||||||||
10744 | // The exit value should be (End+A)/A. | ||||||||||
10745 | APInt ExitVal = (End + A).udiv(A); | ||||||||||
10746 | ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); | ||||||||||
10747 | |||||||||||
10748 | // Evaluate at the exit value. If we really did fall out of the valid | ||||||||||
10749 | // range, then we computed our trip count, otherwise wrap around or other | ||||||||||
10750 | // things must have happened. | ||||||||||
10751 | ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); | ||||||||||
10752 | if (Range.contains(Val->getValue())) | ||||||||||
10753 | return SE.getCouldNotCompute(); // Something strange happened | ||||||||||
10754 | |||||||||||
10755 | // Ensure that the previous value is in the range. This is a sanity check. | ||||||||||
10756 | assert(Range.contains(((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt ::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && "Linear scev computation is off in a bad way!") ? static_cast <void> (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10759, __PRETTY_FUNCTION__)) | ||||||||||
10757 | EvaluateConstantChrecAtConstant(this,((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt ::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && "Linear scev computation is off in a bad way!") ? static_cast <void> (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10759, __PRETTY_FUNCTION__)) | ||||||||||
10758 | ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt ::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && "Linear scev computation is off in a bad way!") ? static_cast <void> (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10759, __PRETTY_FUNCTION__)) | ||||||||||
10759 | "Linear scev computation is off in a bad way!")((Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt ::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && "Linear scev computation is off in a bad way!") ? static_cast <void> (0) : __assert_fail ("Range.contains( EvaluateConstantChrecAtConstant(this, ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && \"Linear scev computation is off in a bad way!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10759, __PRETTY_FUNCTION__)); | ||||||||||
10760 | return SE.getConstant(ExitValue); | ||||||||||
10761 | } | ||||||||||
10762 | |||||||||||
10763 | if (isQuadratic()) { | ||||||||||
10764 | if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) | ||||||||||
10765 | return SE.getConstant(S.getValue()); | ||||||||||
10766 | } | ||||||||||
10767 | |||||||||||
10768 | return SE.getCouldNotCompute(); | ||||||||||
10769 | } | ||||||||||
10770 | |||||||||||
10771 | const SCEVAddRecExpr * | ||||||||||
10772 | SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { | ||||||||||
10773 | assert(getNumOperands() > 1 && "AddRec with zero step?")((getNumOperands() > 1 && "AddRec with zero step?" ) ? static_cast<void> (0) : __assert_fail ("getNumOperands() > 1 && \"AddRec with zero step?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10773, __PRETTY_FUNCTION__)); | ||||||||||
10774 | // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), | ||||||||||
10775 | // but in this case we cannot guarantee that the value returned will be an | ||||||||||
10776 | // AddRec because SCEV does not have a fixed point where it stops | ||||||||||
10777 | // simplification: it is legal to return ({rec1} + {rec2}). For example, it | ||||||||||
10778 | // may happen if we reach arithmetic depth limit while simplifying. So we | ||||||||||
10779 | // construct the returned value explicitly. | ||||||||||
10780 | SmallVector<const SCEV *, 3> Ops; | ||||||||||
10781 | // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and | ||||||||||
10782 | // (this + Step) is {A+B,+,B+C,+...,+,N}. | ||||||||||
10783 | for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) | ||||||||||
10784 | Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); | ||||||||||
10785 | // We know that the last operand is not a constant zero (otherwise it would | ||||||||||
10786 | // have been popped out earlier). This guarantees us that if the result has | ||||||||||
10787 | // the same last operand, then it will also not be popped out, meaning that | ||||||||||
10788 | // the returned value will be an AddRec. | ||||||||||
10789 | const SCEV *Last = getOperand(getNumOperands() - 1); | ||||||||||
10790 | assert(!Last->isZero() && "Recurrency with zero step?")((!Last->isZero() && "Recurrency with zero step?") ? static_cast<void> (0) : __assert_fail ("!Last->isZero() && \"Recurrency with zero step?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 10790, __PRETTY_FUNCTION__)); | ||||||||||
10791 | Ops.push_back(Last); | ||||||||||
10792 | return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), | ||||||||||
10793 | SCEV::FlagAnyWrap)); | ||||||||||
10794 | } | ||||||||||
10795 | |||||||||||
10796 | // Return true when S contains at least an undef value. | ||||||||||
10797 | static inline bool containsUndefs(const SCEV *S) { | ||||||||||
10798 | return SCEVExprContains(S, [](const SCEV *S) { | ||||||||||
10799 | if (const auto *SU = dyn_cast<SCEVUnknown>(S)) | ||||||||||
10800 | return isa<UndefValue>(SU->getValue()); | ||||||||||
10801 | return false; | ||||||||||
10802 | }); | ||||||||||
10803 | } | ||||||||||
10804 | |||||||||||
10805 | namespace { | ||||||||||
10806 | |||||||||||
10807 | // Collect all steps of SCEV expressions. | ||||||||||
10808 | struct SCEVCollectStrides { | ||||||||||
10809 | ScalarEvolution &SE; | ||||||||||
10810 | SmallVectorImpl<const SCEV *> &Strides; | ||||||||||
10811 | |||||||||||
10812 | SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) | ||||||||||
10813 | : SE(SE), Strides(S) {} | ||||||||||
10814 | |||||||||||
10815 | bool follow(const SCEV *S) { | ||||||||||
10816 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) | ||||||||||
10817 | Strides.push_back(AR->getStepRecurrence(SE)); | ||||||||||
10818 | return true; | ||||||||||
10819 | } | ||||||||||
10820 | |||||||||||
10821 | bool isDone() const { return false; } | ||||||||||
10822 | }; | ||||||||||
10823 | |||||||||||
10824 | // Collect all SCEVUnknown and SCEVMulExpr expressions. | ||||||||||
10825 | struct SCEVCollectTerms { | ||||||||||
10826 | SmallVectorImpl<const SCEV *> &Terms; | ||||||||||
10827 | |||||||||||
10828 | SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} | ||||||||||
10829 | |||||||||||
10830 | bool follow(const SCEV *S) { | ||||||||||
10831 | if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || | ||||||||||
10832 | isa<SCEVSignExtendExpr>(S)) { | ||||||||||
10833 | if (!containsUndefs(S)) | ||||||||||
10834 | Terms.push_back(S); | ||||||||||
10835 | |||||||||||
10836 | // Stop recursion: once we collected a term, do not walk its operands. | ||||||||||
10837 | return false; | ||||||||||
10838 | } | ||||||||||
10839 | |||||||||||
10840 | // Keep looking. | ||||||||||
10841 | return true; | ||||||||||
10842 | } | ||||||||||
10843 | |||||||||||
10844 | bool isDone() const { return false; } | ||||||||||
10845 | }; | ||||||||||
10846 | |||||||||||
10847 | // Check if a SCEV contains an AddRecExpr. | ||||||||||
10848 | struct SCEVHasAddRec { | ||||||||||
10849 | bool &ContainsAddRec; | ||||||||||
10850 | |||||||||||
10851 | SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { | ||||||||||
10852 | ContainsAddRec = false; | ||||||||||
10853 | } | ||||||||||
10854 | |||||||||||
10855 | bool follow(const SCEV *S) { | ||||||||||
10856 | if (isa<SCEVAddRecExpr>(S)) { | ||||||||||
10857 | ContainsAddRec = true; | ||||||||||
10858 | |||||||||||
10859 | // Stop recursion: once we collected a term, do not walk its operands. | ||||||||||
10860 | return false; | ||||||||||
10861 | } | ||||||||||
10862 | |||||||||||
10863 | // Keep looking. | ||||||||||
10864 | return true; | ||||||||||
10865 | } | ||||||||||
10866 | |||||||||||
10867 | bool isDone() const { return false; } | ||||||||||
10868 | }; | ||||||||||
10869 | |||||||||||
10870 | // Find factors that are multiplied with an expression that (possibly as a | ||||||||||
10871 | // subexpression) contains an AddRecExpr. In the expression: | ||||||||||
10872 | // | ||||||||||
10873 | // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) | ||||||||||
10874 | // | ||||||||||
10875 | // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" | ||||||||||
10876 | // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size | ||||||||||
10877 | // parameters as they form a product with an induction variable. | ||||||||||
10878 | // | ||||||||||
10879 | // This collector expects all array size parameters to be in the same MulExpr. | ||||||||||
10880 | // It might be necessary to later add support for collecting parameters that are | ||||||||||
10881 | // spread over different nested MulExpr. | ||||||||||
10882 | struct SCEVCollectAddRecMultiplies { | ||||||||||
10883 | SmallVectorImpl<const SCEV *> &Terms; | ||||||||||
10884 | ScalarEvolution &SE; | ||||||||||
10885 | |||||||||||
10886 | SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) | ||||||||||
10887 | : Terms(T), SE(SE) {} | ||||||||||
10888 | |||||||||||
10889 | bool follow(const SCEV *S) { | ||||||||||
10890 | if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { | ||||||||||
10891 | bool HasAddRec = false; | ||||||||||
10892 | SmallVector<const SCEV *, 0> Operands; | ||||||||||
10893 | for (auto Op : Mul->operands()) { | ||||||||||
10894 | const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); | ||||||||||
10895 | if (Unknown && !isa<CallInst>(Unknown->getValue())) { | ||||||||||
10896 | Operands.push_back(Op); | ||||||||||
10897 | } else if (Unknown) { | ||||||||||
10898 | HasAddRec = true; | ||||||||||
10899 | } else { | ||||||||||
10900 | bool ContainsAddRec = false; | ||||||||||
10901 | SCEVHasAddRec ContiansAddRec(ContainsAddRec); | ||||||||||
10902 | visitAll(Op, ContiansAddRec); | ||||||||||
10903 | HasAddRec |= ContainsAddRec; | ||||||||||
10904 | } | ||||||||||
10905 | } | ||||||||||
10906 | if (Operands.size() == 0) | ||||||||||
10907 | return true; | ||||||||||
10908 | |||||||||||
10909 | if (!HasAddRec) | ||||||||||
10910 | return false; | ||||||||||
10911 | |||||||||||
10912 | Terms.push_back(SE.getMulExpr(Operands)); | ||||||||||
10913 | // Stop recursion: once we collected a term, do not walk its operands. | ||||||||||
10914 | return false; | ||||||||||
10915 | } | ||||||||||
10916 | |||||||||||
10917 | // Keep looking. | ||||||||||
10918 | return true; | ||||||||||
10919 | } | ||||||||||
10920 | |||||||||||
10921 | bool isDone() const { return false; } | ||||||||||
10922 | }; | ||||||||||
10923 | |||||||||||
10924 | } // end anonymous namespace | ||||||||||
10925 | |||||||||||
10926 | /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in | ||||||||||
10927 | /// two places: | ||||||||||
10928 | /// 1) The strides of AddRec expressions. | ||||||||||
10929 | /// 2) Unknowns that are multiplied with AddRec expressions. | ||||||||||
10930 | void ScalarEvolution::collectParametricTerms(const SCEV *Expr, | ||||||||||
10931 | SmallVectorImpl<const SCEV *> &Terms) { | ||||||||||
10932 | SmallVector<const SCEV *, 4> Strides; | ||||||||||
10933 | SCEVCollectStrides StrideCollector(*this, Strides); | ||||||||||
10934 | visitAll(Expr, StrideCollector); | ||||||||||
10935 | |||||||||||
10936 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Strides:\n"; for ( const SCEV *S : Strides) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
10937 | dbgs() << "Strides:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Strides:\n"; for ( const SCEV *S : Strides) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
10938 | for (const SCEV *S : Strides)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Strides:\n"; for ( const SCEV *S : Strides) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
10939 | dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Strides:\n"; for ( const SCEV *S : Strides) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
10940 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Strides:\n"; for ( const SCEV *S : Strides) dbgs() << *S << "\n"; }; } } while (false); | ||||||||||
10941 | |||||||||||
10942 | for (const SCEV *S : Strides) { | ||||||||||
10943 | SCEVCollectTerms TermCollector(Terms); | ||||||||||
10944 | visitAll(S, TermCollector); | ||||||||||
10945 | } | ||||||||||
10946 | |||||||||||
10947 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
10948 | dbgs() << "Terms:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
10949 | for (const SCEV *T : Terms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
10950 | dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
10951 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false); | ||||||||||
10952 | |||||||||||
10953 | SCEVCollectAddRecMultiplies MulCollector(Terms, *this); | ||||||||||
10954 | visitAll(Expr, MulCollector); | ||||||||||
10955 | } | ||||||||||
10956 | |||||||||||
10957 | static bool findArrayDimensionsRec(ScalarEvolution &SE, | ||||||||||
10958 | SmallVectorImpl<const SCEV *> &Terms, | ||||||||||
10959 | SmallVectorImpl<const SCEV *> &Sizes) { | ||||||||||
10960 | int Last = Terms.size() - 1; | ||||||||||
10961 | const SCEV *Step = Terms[Last]; | ||||||||||
10962 | |||||||||||
10963 | // End of recursion. | ||||||||||
10964 | if (Last == 0) { | ||||||||||
10965 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { | ||||||||||
10966 | SmallVector<const SCEV *, 2> Qs; | ||||||||||
10967 | for (const SCEV *Op : M->operands()) | ||||||||||
10968 | if (!isa<SCEVConstant>(Op)) | ||||||||||
10969 | Qs.push_back(Op); | ||||||||||
10970 | |||||||||||
10971 | Step = SE.getMulExpr(Qs); | ||||||||||
10972 | } | ||||||||||
10973 | |||||||||||
10974 | Sizes.push_back(Step); | ||||||||||
10975 | return true; | ||||||||||
10976 | } | ||||||||||
10977 | |||||||||||
10978 | for (const SCEV *&Term : Terms) { | ||||||||||
10979 | // Normalize the terms before the next call to findArrayDimensionsRec. | ||||||||||
10980 | const SCEV *Q, *R; | ||||||||||
10981 | SCEVDivision::divide(SE, Term, Step, &Q, &R); | ||||||||||
10982 | |||||||||||
10983 | // Bail out when GCD does not evenly divide one of the terms. | ||||||||||
10984 | if (!R->isZero()) | ||||||||||
10985 | return false; | ||||||||||
10986 | |||||||||||
10987 | Term = Q; | ||||||||||
10988 | } | ||||||||||
10989 | |||||||||||
10990 | // Remove all SCEVConstants. | ||||||||||
10991 | Terms.erase( | ||||||||||
10992 | remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), | ||||||||||
10993 | Terms.end()); | ||||||||||
10994 | |||||||||||
10995 | if (Terms.size() > 0) | ||||||||||
10996 | if (!findArrayDimensionsRec(SE, Terms, Sizes)) | ||||||||||
10997 | return false; | ||||||||||
10998 | |||||||||||
10999 | Sizes.push_back(Step); | ||||||||||
11000 | return true; | ||||||||||
11001 | } | ||||||||||
11002 | |||||||||||
11003 | // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. | ||||||||||
11004 | static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { | ||||||||||
11005 | for (const SCEV *T : Terms) | ||||||||||
11006 | if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) | ||||||||||
11007 | return true; | ||||||||||
11008 | |||||||||||
11009 | return false; | ||||||||||
11010 | } | ||||||||||
11011 | |||||||||||
11012 | // Return the number of product terms in S. | ||||||||||
11013 | static inline int numberOfTerms(const SCEV *S) { | ||||||||||
11014 | if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) | ||||||||||
11015 | return Expr->getNumOperands(); | ||||||||||
11016 | return 1; | ||||||||||
11017 | } | ||||||||||
11018 | |||||||||||
11019 | static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { | ||||||||||
11020 | if (isa<SCEVConstant>(T)) | ||||||||||
11021 | return nullptr; | ||||||||||
11022 | |||||||||||
11023 | if (isa<SCEVUnknown>(T)) | ||||||||||
11024 | return T; | ||||||||||
11025 | |||||||||||
11026 | if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { | ||||||||||
11027 | SmallVector<const SCEV *, 2> Factors; | ||||||||||
11028 | for (const SCEV *Op : M->operands()) | ||||||||||
11029 | if (!isa<SCEVConstant>(Op)) | ||||||||||
11030 | Factors.push_back(Op); | ||||||||||
11031 | |||||||||||
11032 | return SE.getMulExpr(Factors); | ||||||||||
11033 | } | ||||||||||
11034 | |||||||||||
11035 | return T; | ||||||||||
11036 | } | ||||||||||
11037 | |||||||||||
11038 | /// Return the size of an element read or written by Inst. | ||||||||||
11039 | const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { | ||||||||||
11040 | Type *Ty; | ||||||||||
11041 | if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) | ||||||||||
11042 | Ty = Store->getValueOperand()->getType(); | ||||||||||
11043 | else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) | ||||||||||
11044 | Ty = Load->getType(); | ||||||||||
11045 | else | ||||||||||
11046 | return nullptr; | ||||||||||
11047 | |||||||||||
11048 | Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); | ||||||||||
11049 | return getSizeOfExpr(ETy, Ty); | ||||||||||
11050 | } | ||||||||||
11051 | |||||||||||
11052 | void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, | ||||||||||
11053 | SmallVectorImpl<const SCEV *> &Sizes, | ||||||||||
11054 | const SCEV *ElementSize) { | ||||||||||
11055 | if (Terms.size() < 1 || !ElementSize) | ||||||||||
11056 | return; | ||||||||||
11057 | |||||||||||
11058 | // Early return when Terms do not contain parameters: we do not delinearize | ||||||||||
11059 | // non parametric SCEVs. | ||||||||||
11060 | if (!containsParameters(Terms)) | ||||||||||
11061 | return; | ||||||||||
11062 | |||||||||||
11063 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
11064 | dbgs() << "Terms:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
11065 | for (const SCEV *T : Terms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
11066 | dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false) | ||||||||||
11067 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms:\n"; for (const SCEV *T : Terms) dbgs() << *T << "\n"; }; } } while (false); | ||||||||||
11068 | |||||||||||
11069 | // Remove duplicates. | ||||||||||
11070 | array_pod_sort(Terms.begin(), Terms.end()); | ||||||||||
11071 | Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); | ||||||||||
11072 | |||||||||||
11073 | // Put larger terms first. | ||||||||||
11074 | llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { | ||||||||||
11075 | return numberOfTerms(LHS) > numberOfTerms(RHS); | ||||||||||
11076 | }); | ||||||||||
11077 | |||||||||||
11078 | // Try to divide all terms by the element size. If term is not divisible by | ||||||||||
11079 | // element size, proceed with the original term. | ||||||||||
11080 | for (const SCEV *&Term : Terms) { | ||||||||||
11081 | const SCEV *Q, *R; | ||||||||||
11082 | SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); | ||||||||||
11083 | if (!Q->isZero()) | ||||||||||
11084 | Term = Q; | ||||||||||
11085 | } | ||||||||||
11086 | |||||||||||
11087 | SmallVector<const SCEV *, 4> NewTerms; | ||||||||||
11088 | |||||||||||
11089 | // Remove constant factors. | ||||||||||
11090 | for (const SCEV *T : Terms) | ||||||||||
11091 | if (const SCEV *NewT = removeConstantFactors(*this, T)) | ||||||||||
11092 | NewTerms.push_back(NewT); | ||||||||||
11093 | |||||||||||
11094 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms after sorting:\n" ; for (const SCEV *T : NewTerms) dbgs() << *T << "\n" ; }; } } while (false) | ||||||||||
11095 | dbgs() << "Terms after sorting:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms after sorting:\n" ; for (const SCEV *T : NewTerms) dbgs() << *T << "\n" ; }; } } while (false) | ||||||||||
11096 | for (const SCEV *T : NewTerms)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms after sorting:\n" ; for (const SCEV *T : NewTerms) dbgs() << *T << "\n" ; }; } } while (false) | ||||||||||
11097 | dbgs() << *T << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms after sorting:\n" ; for (const SCEV *T : NewTerms) dbgs() << *T << "\n" ; }; } } while (false) | ||||||||||
11098 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Terms after sorting:\n" ; for (const SCEV *T : NewTerms) dbgs() << *T << "\n" ; }; } } while (false); | ||||||||||
11099 | |||||||||||
11100 | if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { | ||||||||||
11101 | Sizes.clear(); | ||||||||||
11102 | return; | ||||||||||
11103 | } | ||||||||||
11104 | |||||||||||
11105 | // The last element to be pushed into Sizes is the size of an element. | ||||||||||
11106 | Sizes.push_back(ElementSize); | ||||||||||
11107 | |||||||||||
11108 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
11109 | dbgs() << "Sizes:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
11110 | for (const SCEV *S : Sizes)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
11111 | dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while (false) | ||||||||||
11112 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Sizes:\n"; for (const SCEV *S : Sizes) dbgs() << *S << "\n"; }; } } while (false); | ||||||||||
11113 | } | ||||||||||
11114 | |||||||||||
11115 | void ScalarEvolution::computeAccessFunctions( | ||||||||||
11116 | const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, | ||||||||||
11117 | SmallVectorImpl<const SCEV *> &Sizes) { | ||||||||||
11118 | // Early exit in case this SCEV is not an affine multivariate function. | ||||||||||
11119 | if (Sizes.empty()) | ||||||||||
11120 | return; | ||||||||||
11121 | |||||||||||
11122 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) | ||||||||||
11123 | if (!AR->isAffine()) | ||||||||||
11124 | return; | ||||||||||
11125 | |||||||||||
11126 | const SCEV *Res = Expr; | ||||||||||
11127 | int Last = Sizes.size() - 1; | ||||||||||
11128 | for (int i = Last; i >= 0; i--) { | ||||||||||
11129 | const SCEV *Q, *R; | ||||||||||
11130 | SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); | ||||||||||
11131 | |||||||||||
11132 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11133 | dbgs() << "Res: " << *Res << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11134 | dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11135 | dbgs() << "Res divided by Sizes[i]:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11136 | dbgs() << "Quotient: " << *Q << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11137 | dbgs() << "Remainder: " << *R << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false) | ||||||||||
11138 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Res: " << *Res << "\n"; dbgs() << "Sizes[i]: " << *Sizes[ i] << "\n"; dbgs() << "Res divided by Sizes[i]:\n" ; dbgs() << "Quotient: " << *Q << "\n"; dbgs () << "Remainder: " << *R << "\n"; }; } } while (false); | ||||||||||
11139 | |||||||||||
11140 | Res = Q; | ||||||||||
11141 | |||||||||||
11142 | // Do not record the last subscript corresponding to the size of elements in | ||||||||||
11143 | // the array. | ||||||||||
11144 | if (i == Last) { | ||||||||||
11145 | |||||||||||
11146 | // Bail out if the remainder is too complex. | ||||||||||
11147 | if (isa<SCEVAddRecExpr>(R)) { | ||||||||||
11148 | Subscripts.clear(); | ||||||||||
11149 | Sizes.clear(); | ||||||||||
11150 | return; | ||||||||||
11151 | } | ||||||||||
11152 | |||||||||||
11153 | continue; | ||||||||||
11154 | } | ||||||||||
11155 | |||||||||||
11156 | // Record the access function for the current subscript. | ||||||||||
11157 | Subscripts.push_back(R); | ||||||||||
11158 | } | ||||||||||
11159 | |||||||||||
11160 | // Also push in last position the remainder of the last division: it will be | ||||||||||
11161 | // the access function of the innermost dimension. | ||||||||||
11162 | Subscripts.push_back(Res); | ||||||||||
11163 | |||||||||||
11164 | std::reverse(Subscripts.begin(), Subscripts.end()); | ||||||||||
11165 | |||||||||||
11166 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for (const SCEV *S : Subscripts) dbgs() << *S << "\n" ; }; } } while (false) | ||||||||||
11167 | dbgs() << "Subscripts:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for (const SCEV *S : Subscripts) dbgs() << *S << "\n" ; }; } } while (false) | ||||||||||
11168 | for (const SCEV *S : Subscripts)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for (const SCEV *S : Subscripts) dbgs() << *S << "\n" ; }; } } while (false) | ||||||||||
11169 | dbgs() << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for (const SCEV *S : Subscripts) dbgs() << *S << "\n" ; }; } } while (false) | ||||||||||
11170 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "Subscripts:\n"; for (const SCEV *S : Subscripts) dbgs() << *S << "\n" ; }; } } while (false); | ||||||||||
11171 | } | ||||||||||
11172 | |||||||||||
11173 | /// Splits the SCEV into two vectors of SCEVs representing the subscripts and | ||||||||||
11174 | /// sizes of an array access. Returns the remainder of the delinearization that | ||||||||||
11175 | /// is the offset start of the array. The SCEV->delinearize algorithm computes | ||||||||||
11176 | /// the multiples of SCEV coefficients: that is a pattern matching of sub | ||||||||||
11177 | /// expressions in the stride and base of a SCEV corresponding to the | ||||||||||
11178 | /// computation of a GCD (greatest common divisor) of base and stride. When | ||||||||||
11179 | /// SCEV->delinearize fails, it returns the SCEV unchanged. | ||||||||||
11180 | /// | ||||||||||
11181 | /// For example: when analyzing the memory access A[i][j][k] in this loop nest | ||||||||||
11182 | /// | ||||||||||
11183 | /// void foo(long n, long m, long o, double A[n][m][o]) { | ||||||||||
11184 | /// | ||||||||||
11185 | /// for (long i = 0; i < n; i++) | ||||||||||
11186 | /// for (long j = 0; j < m; j++) | ||||||||||
11187 | /// for (long k = 0; k < o; k++) | ||||||||||
11188 | /// A[i][j][k] = 1.0; | ||||||||||
11189 | /// } | ||||||||||
11190 | /// | ||||||||||
11191 | /// the delinearization input is the following AddRec SCEV: | ||||||||||
11192 | /// | ||||||||||
11193 | /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> | ||||||||||
11194 | /// | ||||||||||
11195 | /// From this SCEV, we are able to say that the base offset of the access is %A | ||||||||||
11196 | /// because it appears as an offset that does not divide any of the strides in | ||||||||||
11197 | /// the loops: | ||||||||||
11198 | /// | ||||||||||
11199 | /// CHECK: Base offset: %A | ||||||||||
11200 | /// | ||||||||||
11201 | /// and then SCEV->delinearize determines the size of some of the dimensions of | ||||||||||
11202 | /// the array as these are the multiples by which the strides are happening: | ||||||||||
11203 | /// | ||||||||||
11204 | /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. | ||||||||||
11205 | /// | ||||||||||
11206 | /// Note that the outermost dimension remains of UnknownSize because there are | ||||||||||
11207 | /// no strides that would help identifying the size of the last dimension: when | ||||||||||
11208 | /// the array has been statically allocated, one could compute the size of that | ||||||||||
11209 | /// dimension by dividing the overall size of the array by the size of the known | ||||||||||
11210 | /// dimensions: %m * %o * 8. | ||||||||||
11211 | /// | ||||||||||
11212 | /// Finally delinearize provides the access functions for the array reference | ||||||||||
11213 | /// that does correspond to A[i][j][k] of the above C testcase: | ||||||||||
11214 | /// | ||||||||||
11215 | /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] | ||||||||||
11216 | /// | ||||||||||
11217 | /// The testcases are checking the output of a function pass: | ||||||||||
11218 | /// DelinearizationPass that walks through all loads and stores of a function | ||||||||||
11219 | /// asking for the SCEV of the memory access with respect to all enclosing | ||||||||||
11220 | /// loops, calling SCEV->delinearize on that and printing the results. | ||||||||||
11221 | void ScalarEvolution::delinearize(const SCEV *Expr, | ||||||||||
11222 | SmallVectorImpl<const SCEV *> &Subscripts, | ||||||||||
11223 | SmallVectorImpl<const SCEV *> &Sizes, | ||||||||||
11224 | const SCEV *ElementSize) { | ||||||||||
11225 | // First step: collect parametric terms. | ||||||||||
11226 | SmallVector<const SCEV *, 4> Terms; | ||||||||||
11227 | collectParametricTerms(Expr, Terms); | ||||||||||
11228 | |||||||||||
11229 | if (Terms.empty()) | ||||||||||
11230 | return; | ||||||||||
11231 | |||||||||||
11232 | // Second step: find subscript sizes. | ||||||||||
11233 | findArrayDimensions(Terms, Sizes, ElementSize); | ||||||||||
11234 | |||||||||||
11235 | if (Sizes.empty()) | ||||||||||
11236 | return; | ||||||||||
11237 | |||||||||||
11238 | // Third step: compute the access functions for each subscript. | ||||||||||
11239 | computeAccessFunctions(Expr, Subscripts, Sizes); | ||||||||||
11240 | |||||||||||
11241 | if (Subscripts.empty()) | ||||||||||
11242 | return; | ||||||||||
11243 | |||||||||||
11244 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11245 | dbgs() << "succeeded to delinearize " << *Expr << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11246 | dbgs() << "ArrayDecl[UnknownSize]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11247 | for (const SCEV *S : Sizes)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11248 | dbgs() << "[" << *S << "]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11249 | |||||||||||
11250 | dbgs() << "\nArrayRef";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11251 | for (const SCEV *S : Subscripts)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11252 | dbgs() << "[" << *S << "]";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11253 | dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false) | ||||||||||
11254 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("scalar-evolution")) { { dbgs() << "succeeded to delinearize " << *Expr << "\n"; dbgs() << "ArrayDecl[UnknownSize]" ; for (const SCEV *S : Sizes) dbgs() << "[" << *S << "]"; dbgs() << "\nArrayRef"; for (const SCEV * S : Subscripts) dbgs() << "[" << *S << "]"; dbgs() << "\n"; }; } } while (false); | ||||||||||
11255 | } | ||||||||||
11256 | |||||||||||
11257 | bool ScalarEvolution::getIndexExpressionsFromGEP( | ||||||||||
11258 | const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, | ||||||||||
11259 | SmallVectorImpl<int> &Sizes) { | ||||||||||
11260 | assert(Subscripts.empty() && Sizes.empty() &&((Subscripts.empty() && Sizes.empty() && "Expected output lists to be empty on entry to this function." ) ? static_cast<void> (0) : __assert_fail ("Subscripts.empty() && Sizes.empty() && \"Expected output lists to be empty on entry to this function.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11261, __PRETTY_FUNCTION__)) | ||||||||||
11261 | "Expected output lists to be empty on entry to this function.")((Subscripts.empty() && Sizes.empty() && "Expected output lists to be empty on entry to this function." ) ? static_cast<void> (0) : __assert_fail ("Subscripts.empty() && Sizes.empty() && \"Expected output lists to be empty on entry to this function.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11261, __PRETTY_FUNCTION__)); | ||||||||||
11262 | assert(GEP && "getIndexExpressionsFromGEP called with a null GEP")((GEP && "getIndexExpressionsFromGEP called with a null GEP" ) ? static_cast<void> (0) : __assert_fail ("GEP && \"getIndexExpressionsFromGEP called with a null GEP\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11262, __PRETTY_FUNCTION__)); | ||||||||||
11263 | Type *Ty = GEP->getPointerOperandType(); | ||||||||||
11264 | bool DroppedFirstDim = false; | ||||||||||
11265 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { | ||||||||||
11266 | const SCEV *Expr = getSCEV(GEP->getOperand(i)); | ||||||||||
11267 | if (i == 1) { | ||||||||||
11268 | if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { | ||||||||||
11269 | Ty = PtrTy->getElementType(); | ||||||||||
11270 | } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { | ||||||||||
11271 | Ty = ArrayTy->getElementType(); | ||||||||||
11272 | } else { | ||||||||||
11273 | Subscripts.clear(); | ||||||||||
11274 | Sizes.clear(); | ||||||||||
11275 | return false; | ||||||||||
11276 | } | ||||||||||
11277 | if (auto *Const = dyn_cast<SCEVConstant>(Expr)) | ||||||||||
11278 | if (Const->getValue()->isZero()) { | ||||||||||
11279 | DroppedFirstDim = true; | ||||||||||
11280 | continue; | ||||||||||
11281 | } | ||||||||||
11282 | Subscripts.push_back(Expr); | ||||||||||
11283 | continue; | ||||||||||
11284 | } | ||||||||||
11285 | |||||||||||
11286 | auto *ArrayTy = dyn_cast<ArrayType>(Ty); | ||||||||||
11287 | if (!ArrayTy) { | ||||||||||
11288 | Subscripts.clear(); | ||||||||||
11289 | Sizes.clear(); | ||||||||||
11290 | return false; | ||||||||||
11291 | } | ||||||||||
11292 | |||||||||||
11293 | Subscripts.push_back(Expr); | ||||||||||
11294 | if (!(DroppedFirstDim && i == 2)) | ||||||||||
11295 | Sizes.push_back(ArrayTy->getNumElements()); | ||||||||||
11296 | |||||||||||
11297 | Ty = ArrayTy->getElementType(); | ||||||||||
11298 | } | ||||||||||
11299 | return !Subscripts.empty(); | ||||||||||
11300 | } | ||||||||||
11301 | |||||||||||
11302 | //===----------------------------------------------------------------------===// | ||||||||||
11303 | // SCEVCallbackVH Class Implementation | ||||||||||
11304 | //===----------------------------------------------------------------------===// | ||||||||||
11305 | |||||||||||
11306 | void ScalarEvolution::SCEVCallbackVH::deleted() { | ||||||||||
11307 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")((SE && "SCEVCallbackVH called with a null ScalarEvolution!" ) ? static_cast<void> (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11307, __PRETTY_FUNCTION__)); | ||||||||||
11308 | if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) | ||||||||||
11309 | SE->ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
11310 | SE->eraseValueFromMap(getValPtr()); | ||||||||||
11311 | // this now dangles! | ||||||||||
11312 | } | ||||||||||
11313 | |||||||||||
11314 | void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { | ||||||||||
11315 | assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!")((SE && "SCEVCallbackVH called with a null ScalarEvolution!" ) ? static_cast<void> (0) : __assert_fail ("SE && \"SCEVCallbackVH called with a null ScalarEvolution!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11315, __PRETTY_FUNCTION__)); | ||||||||||
11316 | |||||||||||
11317 | // Forget all the expressions associated with users of the old value, | ||||||||||
11318 | // so that future queries will recompute the expressions using the new | ||||||||||
11319 | // value. | ||||||||||
11320 | Value *Old = getValPtr(); | ||||||||||
11321 | SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); | ||||||||||
11322 | SmallPtrSet<User *, 8> Visited; | ||||||||||
11323 | while (!Worklist.empty()) { | ||||||||||
11324 | User *U = Worklist.pop_back_val(); | ||||||||||
11325 | // Deleting the Old value will cause this to dangle. Postpone | ||||||||||
11326 | // that until everything else is done. | ||||||||||
11327 | if (U == Old) | ||||||||||
11328 | continue; | ||||||||||
11329 | if (!Visited.insert(U).second) | ||||||||||
11330 | continue; | ||||||||||
11331 | if (PHINode *PN = dyn_cast<PHINode>(U)) | ||||||||||
11332 | SE->ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
11333 | SE->eraseValueFromMap(U); | ||||||||||
11334 | Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); | ||||||||||
11335 | } | ||||||||||
11336 | // Delete the Old value. | ||||||||||
11337 | if (PHINode *PN = dyn_cast<PHINode>(Old)) | ||||||||||
11338 | SE->ConstantEvolutionLoopExitValue.erase(PN); | ||||||||||
11339 | SE->eraseValueFromMap(Old); | ||||||||||
11340 | // this now dangles! | ||||||||||
11341 | } | ||||||||||
11342 | |||||||||||
11343 | ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) | ||||||||||
11344 | : CallbackVH(V), SE(se) {} | ||||||||||
11345 | |||||||||||
11346 | //===----------------------------------------------------------------------===// | ||||||||||
11347 | // ScalarEvolution Class Implementation | ||||||||||
11348 | //===----------------------------------------------------------------------===// | ||||||||||
11349 | |||||||||||
11350 | ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, | ||||||||||
11351 | AssumptionCache &AC, DominatorTree &DT, | ||||||||||
11352 | LoopInfo &LI) | ||||||||||
11353 | : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), | ||||||||||
11354 | CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), | ||||||||||
11355 | LoopDispositions(64), BlockDispositions(64) { | ||||||||||
11356 | // To use guards for proving predicates, we need to scan every instruction in | ||||||||||
11357 | // relevant basic blocks, and not just terminators. Doing this is a waste of | ||||||||||
11358 | // time if the IR does not actually contain any calls to | ||||||||||
11359 | // @llvm.experimental.guard, so do a quick check and remember this beforehand. | ||||||||||
11360 | // | ||||||||||
11361 | // This pessimizes the case where a pass that preserves ScalarEvolution wants | ||||||||||
11362 | // to _add_ guards to the module when there weren't any before, and wants | ||||||||||
11363 | // ScalarEvolution to optimize based on those guards. For now we prefer to be | ||||||||||
11364 | // efficient in lieu of being smart in that rather obscure case. | ||||||||||
11365 | |||||||||||
11366 | auto *GuardDecl = F.getParent()->getFunction( | ||||||||||
11367 | Intrinsic::getName(Intrinsic::experimental_guard)); | ||||||||||
11368 | HasGuards = GuardDecl && !GuardDecl->use_empty(); | ||||||||||
11369 | } | ||||||||||
11370 | |||||||||||
11371 | ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) | ||||||||||
11372 | : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), | ||||||||||
11373 | LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), | ||||||||||
11374 | ValueExprMap(std::move(Arg.ValueExprMap)), | ||||||||||
11375 | PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), | ||||||||||
11376 | PendingPhiRanges(std::move(Arg.PendingPhiRanges)), | ||||||||||
11377 | PendingMerges(std::move(Arg.PendingMerges)), | ||||||||||
11378 | MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), | ||||||||||
11379 | BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), | ||||||||||
11380 | PredicatedBackedgeTakenCounts( | ||||||||||
11381 | std::move(Arg.PredicatedBackedgeTakenCounts)), | ||||||||||
11382 | ConstantEvolutionLoopExitValue( | ||||||||||
11383 | std::move(Arg.ConstantEvolutionLoopExitValue)), | ||||||||||
11384 | ValuesAtScopes(std::move(Arg.ValuesAtScopes)), | ||||||||||
11385 | LoopDispositions(std::move(Arg.LoopDispositions)), | ||||||||||
11386 | LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), | ||||||||||
11387 | BlockDispositions(std::move(Arg.BlockDispositions)), | ||||||||||
11388 | UnsignedRanges(std::move(Arg.UnsignedRanges)), | ||||||||||
11389 | SignedRanges(std::move(Arg.SignedRanges)), | ||||||||||
11390 | UniqueSCEVs(std::move(Arg.UniqueSCEVs)), | ||||||||||
11391 | UniquePreds(std::move(Arg.UniquePreds)), | ||||||||||
11392 | SCEVAllocator(std::move(Arg.SCEVAllocator)), | ||||||||||
11393 | LoopUsers(std::move(Arg.LoopUsers)), | ||||||||||
11394 | PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), | ||||||||||
11395 | FirstUnknown(Arg.FirstUnknown) { | ||||||||||
11396 | Arg.FirstUnknown = nullptr; | ||||||||||
11397 | } | ||||||||||
11398 | |||||||||||
11399 | ScalarEvolution::~ScalarEvolution() { | ||||||||||
11400 | // Iterate through all the SCEVUnknown instances and call their | ||||||||||
11401 | // destructors, so that they release their references to their values. | ||||||||||
11402 | for (SCEVUnknown *U = FirstUnknown; U;) { | ||||||||||
11403 | SCEVUnknown *Tmp = U; | ||||||||||
11404 | U = U->Next; | ||||||||||
11405 | Tmp->~SCEVUnknown(); | ||||||||||
11406 | } | ||||||||||
11407 | FirstUnknown = nullptr; | ||||||||||
11408 | |||||||||||
11409 | ExprValueMap.clear(); | ||||||||||
11410 | ValueExprMap.clear(); | ||||||||||
11411 | HasRecMap.clear(); | ||||||||||
11412 | |||||||||||
11413 | // Free any extra memory created for ExitNotTakenInfo in the unlikely event | ||||||||||
11414 | // that a loop had multiple computable exits. | ||||||||||
11415 | for (auto &BTCI : BackedgeTakenCounts) | ||||||||||
11416 | BTCI.second.clear(); | ||||||||||
11417 | for (auto &BTCI : PredicatedBackedgeTakenCounts) | ||||||||||
11418 | BTCI.second.clear(); | ||||||||||
11419 | |||||||||||
11420 | assert(PendingLoopPredicates.empty() && "isImpliedCond garbage")((PendingLoopPredicates.empty() && "isImpliedCond garbage" ) ? static_cast<void> (0) : __assert_fail ("PendingLoopPredicates.empty() && \"isImpliedCond garbage\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11420, __PRETTY_FUNCTION__)); | ||||||||||
11421 | assert(PendingPhiRanges.empty() && "getRangeRef garbage")((PendingPhiRanges.empty() && "getRangeRef garbage") ? static_cast<void> (0) : __assert_fail ("PendingPhiRanges.empty() && \"getRangeRef garbage\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11421, __PRETTY_FUNCTION__)); | ||||||||||
11422 | assert(PendingMerges.empty() && "isImpliedViaMerge garbage")((PendingMerges.empty() && "isImpliedViaMerge garbage" ) ? static_cast<void> (0) : __assert_fail ("PendingMerges.empty() && \"isImpliedViaMerge garbage\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11422, __PRETTY_FUNCTION__)); | ||||||||||
11423 | assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!")((!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!" ) ? static_cast<void> (0) : __assert_fail ("!WalkingBEDominatingConds && \"isLoopBackedgeGuardedByCond garbage!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11423, __PRETTY_FUNCTION__)); | ||||||||||
11424 | assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!")((!ProvingSplitPredicate && "ProvingSplitPredicate garbage!" ) ? static_cast<void> (0) : __assert_fail ("!ProvingSplitPredicate && \"ProvingSplitPredicate garbage!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11424, __PRETTY_FUNCTION__)); | ||||||||||
11425 | } | ||||||||||
11426 | |||||||||||
11427 | bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { | ||||||||||
11428 | return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); | ||||||||||
11429 | } | ||||||||||
11430 | |||||||||||
11431 | static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, | ||||||||||
11432 | const Loop *L) { | ||||||||||
11433 | // Print all inner loops first | ||||||||||
11434 | for (Loop *I : *L) | ||||||||||
11435 | PrintLoopInfo(OS, SE, I); | ||||||||||
11436 | |||||||||||
11437 | OS << "Loop "; | ||||||||||
11438 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11439 | OS << ": "; | ||||||||||
11440 | |||||||||||
11441 | SmallVector<BasicBlock *, 8> ExitingBlocks; | ||||||||||
11442 | L->getExitingBlocks(ExitingBlocks); | ||||||||||
11443 | if (ExitingBlocks.size() != 1) | ||||||||||
11444 | OS << "<multiple exits> "; | ||||||||||
11445 | |||||||||||
11446 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) | ||||||||||
11447 | OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; | ||||||||||
11448 | else | ||||||||||
11449 | OS << "Unpredictable backedge-taken count.\n"; | ||||||||||
11450 | |||||||||||
11451 | if (ExitingBlocks.size() > 1) | ||||||||||
11452 | for (BasicBlock *ExitingBlock : ExitingBlocks) { | ||||||||||
11453 | OS << " exit count for " << ExitingBlock->getName() << ": " | ||||||||||
11454 | << *SE->getExitCount(L, ExitingBlock) << "\n"; | ||||||||||
11455 | } | ||||||||||
11456 | |||||||||||
11457 | OS << "Loop "; | ||||||||||
11458 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11459 | OS << ": "; | ||||||||||
11460 | |||||||||||
11461 | if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { | ||||||||||
11462 | OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); | ||||||||||
11463 | if (SE->isBackedgeTakenCountMaxOrZero(L)) | ||||||||||
11464 | OS << ", actual taken count either this or zero."; | ||||||||||
11465 | } else { | ||||||||||
11466 | OS << "Unpredictable max backedge-taken count. "; | ||||||||||
11467 | } | ||||||||||
11468 | |||||||||||
11469 | OS << "\n" | ||||||||||
11470 | "Loop "; | ||||||||||
11471 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11472 | OS << ": "; | ||||||||||
11473 | |||||||||||
11474 | SCEVUnionPredicate Pred; | ||||||||||
11475 | auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); | ||||||||||
11476 | if (!isa<SCEVCouldNotCompute>(PBT)) { | ||||||||||
11477 | OS << "Predicated backedge-taken count is " << *PBT << "\n"; | ||||||||||
11478 | OS << " Predicates:\n"; | ||||||||||
11479 | Pred.print(OS, 4); | ||||||||||
11480 | } else { | ||||||||||
11481 | OS << "Unpredictable predicated backedge-taken count. "; | ||||||||||
11482 | } | ||||||||||
11483 | OS << "\n"; | ||||||||||
11484 | |||||||||||
11485 | if (SE->hasLoopInvariantBackedgeTakenCount(L)) { | ||||||||||
11486 | OS << "Loop "; | ||||||||||
11487 | L->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11488 | OS << ": "; | ||||||||||
11489 | OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; | ||||||||||
11490 | } | ||||||||||
11491 | } | ||||||||||
11492 | |||||||||||
11493 | static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { | ||||||||||
11494 | switch (LD) { | ||||||||||
11495 | case ScalarEvolution::LoopVariant: | ||||||||||
11496 | return "Variant"; | ||||||||||
11497 | case ScalarEvolution::LoopInvariant: | ||||||||||
11498 | return "Invariant"; | ||||||||||
11499 | case ScalarEvolution::LoopComputable: | ||||||||||
11500 | return "Computable"; | ||||||||||
11501 | } | ||||||||||
11502 | llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!")::llvm::llvm_unreachable_internal("Unknown ScalarEvolution::LoopDisposition kind!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11502); | ||||||||||
11503 | } | ||||||||||
11504 | |||||||||||
11505 | void ScalarEvolution::print(raw_ostream &OS) const { | ||||||||||
11506 | // ScalarEvolution's implementation of the print method is to print | ||||||||||
11507 | // out SCEV values of all instructions that are interesting. Doing | ||||||||||
11508 | // this potentially causes it to create new SCEV objects though, | ||||||||||
11509 | // which technically conflicts with the const qualifier. This isn't | ||||||||||
11510 | // observable from outside the class though, so casting away the | ||||||||||
11511 | // const isn't dangerous. | ||||||||||
11512 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); | ||||||||||
11513 | |||||||||||
11514 | if (ClassifyExpressions) { | ||||||||||
11515 | OS << "Classifying expressions for: "; | ||||||||||
11516 | F.printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11517 | OS << "\n"; | ||||||||||
11518 | for (Instruction &I : instructions(F)) | ||||||||||
11519 | if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { | ||||||||||
11520 | OS << I << '\n'; | ||||||||||
11521 | OS << " --> "; | ||||||||||
11522 | const SCEV *SV = SE.getSCEV(&I); | ||||||||||
11523 | SV->print(OS); | ||||||||||
11524 | if (!isa<SCEVCouldNotCompute>(SV)) { | ||||||||||
11525 | OS << " U: "; | ||||||||||
11526 | SE.getUnsignedRange(SV).print(OS); | ||||||||||
11527 | OS << " S: "; | ||||||||||
11528 | SE.getSignedRange(SV).print(OS); | ||||||||||
11529 | } | ||||||||||
11530 | |||||||||||
11531 | const Loop *L = LI.getLoopFor(I.getParent()); | ||||||||||
11532 | |||||||||||
11533 | const SCEV *AtUse = SE.getSCEVAtScope(SV, L); | ||||||||||
11534 | if (AtUse != SV) { | ||||||||||
11535 | OS << " --> "; | ||||||||||
11536 | AtUse->print(OS); | ||||||||||
11537 | if (!isa<SCEVCouldNotCompute>(AtUse)) { | ||||||||||
11538 | OS << " U: "; | ||||||||||
11539 | SE.getUnsignedRange(AtUse).print(OS); | ||||||||||
11540 | OS << " S: "; | ||||||||||
11541 | SE.getSignedRange(AtUse).print(OS); | ||||||||||
11542 | } | ||||||||||
11543 | } | ||||||||||
11544 | |||||||||||
11545 | if (L) { | ||||||||||
11546 | OS << "\t\t" "Exits: "; | ||||||||||
11547 | const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); | ||||||||||
11548 | if (!SE.isLoopInvariant(ExitValue, L)) { | ||||||||||
11549 | OS << "<<Unknown>>"; | ||||||||||
11550 | } else { | ||||||||||
11551 | OS << *ExitValue; | ||||||||||
11552 | } | ||||||||||
11553 | |||||||||||
11554 | bool First = true; | ||||||||||
11555 | for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { | ||||||||||
11556 | if (First) { | ||||||||||
11557 | OS << "\t\t" "LoopDispositions: { "; | ||||||||||
11558 | First = false; | ||||||||||
11559 | } else { | ||||||||||
11560 | OS << ", "; | ||||||||||
11561 | } | ||||||||||
11562 | |||||||||||
11563 | Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11564 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); | ||||||||||
11565 | } | ||||||||||
11566 | |||||||||||
11567 | for (auto *InnerL : depth_first(L)) { | ||||||||||
11568 | if (InnerL == L) | ||||||||||
11569 | continue; | ||||||||||
11570 | if (First) { | ||||||||||
11571 | OS << "\t\t" "LoopDispositions: { "; | ||||||||||
11572 | First = false; | ||||||||||
11573 | } else { | ||||||||||
11574 | OS << ", "; | ||||||||||
11575 | } | ||||||||||
11576 | |||||||||||
11577 | InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11578 | OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); | ||||||||||
11579 | } | ||||||||||
11580 | |||||||||||
11581 | OS << " }"; | ||||||||||
11582 | } | ||||||||||
11583 | |||||||||||
11584 | OS << "\n"; | ||||||||||
11585 | } | ||||||||||
11586 | } | ||||||||||
11587 | |||||||||||
11588 | OS << "Determining loop execution counts for: "; | ||||||||||
11589 | F.printAsOperand(OS, /*PrintType=*/false); | ||||||||||
11590 | OS << "\n"; | ||||||||||
11591 | for (Loop *I : LI) | ||||||||||
11592 | PrintLoopInfo(OS, &SE, I); | ||||||||||
11593 | } | ||||||||||
11594 | |||||||||||
11595 | ScalarEvolution::LoopDisposition | ||||||||||
11596 | ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { | ||||||||||
11597 | auto &Values = LoopDispositions[S]; | ||||||||||
11598 | for (auto &V : Values) { | ||||||||||
11599 | if (V.getPointer() == L) | ||||||||||
11600 | return V.getInt(); | ||||||||||
11601 | } | ||||||||||
11602 | Values.emplace_back(L, LoopVariant); | ||||||||||
11603 | LoopDisposition D = computeLoopDisposition(S, L); | ||||||||||
11604 | auto &Values2 = LoopDispositions[S]; | ||||||||||
11605 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { | ||||||||||
11606 | if (V.getPointer() == L) { | ||||||||||
11607 | V.setInt(D); | ||||||||||
11608 | break; | ||||||||||
11609 | } | ||||||||||
11610 | } | ||||||||||
11611 | return D; | ||||||||||
11612 | } | ||||||||||
11613 | |||||||||||
11614 | ScalarEvolution::LoopDisposition | ||||||||||
11615 | ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { | ||||||||||
11616 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { | ||||||||||
11617 | case scConstant: | ||||||||||
11618 | return LoopInvariant; | ||||||||||
11619 | case scTruncate: | ||||||||||
11620 | case scZeroExtend: | ||||||||||
11621 | case scSignExtend: | ||||||||||
11622 | return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); | ||||||||||
11623 | case scAddRecExpr: { | ||||||||||
11624 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); | ||||||||||
11625 | |||||||||||
11626 | // If L is the addrec's loop, it's computable. | ||||||||||
11627 | if (AR->getLoop() == L) | ||||||||||
11628 | return LoopComputable; | ||||||||||
11629 | |||||||||||
11630 | // Add recurrences are never invariant in the function-body (null loop). | ||||||||||
11631 | if (!L) | ||||||||||
11632 | return LoopVariant; | ||||||||||
11633 | |||||||||||
11634 | // Everything that is not defined at loop entry is variant. | ||||||||||
11635 | if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) | ||||||||||
11636 | return LoopVariant; | ||||||||||
11637 | assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"((!L->contains(AR->getLoop()) && "Containing loop's header does not" " dominate the contained loop's header?") ? static_cast<void > (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11638, __PRETTY_FUNCTION__)) | ||||||||||
11638 | " dominate the contained loop's header?")((!L->contains(AR->getLoop()) && "Containing loop's header does not" " dominate the contained loop's header?") ? static_cast<void > (0) : __assert_fail ("!L->contains(AR->getLoop()) && \"Containing loop's header does not\" \" dominate the contained loop's header?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11638, __PRETTY_FUNCTION__)); | ||||||||||
11639 | |||||||||||
11640 | // This recurrence is invariant w.r.t. L if AR's loop contains L. | ||||||||||
11641 | if (AR->getLoop()->contains(L)) | ||||||||||
11642 | return LoopInvariant; | ||||||||||
11643 | |||||||||||
11644 | // This recurrence is variant w.r.t. L if any of its operands | ||||||||||
11645 | // are variant. | ||||||||||
11646 | for (auto *Op : AR->operands()) | ||||||||||
11647 | if (!isLoopInvariant(Op, L)) | ||||||||||
11648 | return LoopVariant; | ||||||||||
11649 | |||||||||||
11650 | // Otherwise it's loop-invariant. | ||||||||||
11651 | return LoopInvariant; | ||||||||||
11652 | } | ||||||||||
11653 | case scAddExpr: | ||||||||||
11654 | case scMulExpr: | ||||||||||
11655 | case scUMaxExpr: | ||||||||||
11656 | case scSMaxExpr: | ||||||||||
11657 | case scUMinExpr: | ||||||||||
11658 | case scSMinExpr: { | ||||||||||
11659 | bool HasVarying = false; | ||||||||||
11660 | for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { | ||||||||||
11661 | LoopDisposition D = getLoopDisposition(Op, L); | ||||||||||
11662 | if (D == LoopVariant) | ||||||||||
11663 | return LoopVariant; | ||||||||||
11664 | if (D == LoopComputable) | ||||||||||
11665 | HasVarying = true; | ||||||||||
11666 | } | ||||||||||
11667 | return HasVarying ? LoopComputable : LoopInvariant; | ||||||||||
11668 | } | ||||||||||
11669 | case scUDivExpr: { | ||||||||||
11670 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); | ||||||||||
11671 | LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); | ||||||||||
11672 | if (LD == LoopVariant) | ||||||||||
11673 | return LoopVariant; | ||||||||||
11674 | LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); | ||||||||||
11675 | if (RD == LoopVariant) | ||||||||||
11676 | return LoopVariant; | ||||||||||
11677 | return (LD == LoopInvariant && RD == LoopInvariant) ? | ||||||||||
11678 | LoopInvariant : LoopComputable; | ||||||||||
11679 | } | ||||||||||
11680 | case scUnknown: | ||||||||||
11681 | // All non-instruction values are loop invariant. All instructions are loop | ||||||||||
11682 | // invariant if they are not contained in the specified loop. | ||||||||||
11683 | // Instructions are never considered invariant in the function body | ||||||||||
11684 | // (null loop) because they are defined within the "loop". | ||||||||||
11685 | if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) | ||||||||||
11686 | return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; | ||||||||||
11687 | return LoopInvariant; | ||||||||||
11688 | case scCouldNotCompute: | ||||||||||
11689 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11689); | ||||||||||
11690 | } | ||||||||||
11691 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11691); | ||||||||||
11692 | } | ||||||||||
11693 | |||||||||||
11694 | bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { | ||||||||||
11695 | return getLoopDisposition(S, L) == LoopInvariant; | ||||||||||
11696 | } | ||||||||||
11697 | |||||||||||
11698 | bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { | ||||||||||
11699 | return getLoopDisposition(S, L) == LoopComputable; | ||||||||||
11700 | } | ||||||||||
11701 | |||||||||||
11702 | ScalarEvolution::BlockDisposition | ||||||||||
11703 | ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { | ||||||||||
11704 | auto &Values = BlockDispositions[S]; | ||||||||||
11705 | for (auto &V : Values) { | ||||||||||
11706 | if (V.getPointer() == BB) | ||||||||||
11707 | return V.getInt(); | ||||||||||
11708 | } | ||||||||||
11709 | Values.emplace_back(BB, DoesNotDominateBlock); | ||||||||||
11710 | BlockDisposition D = computeBlockDisposition(S, BB); | ||||||||||
11711 | auto &Values2 = BlockDispositions[S]; | ||||||||||
11712 | for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { | ||||||||||
11713 | if (V.getPointer() == BB) { | ||||||||||
11714 | V.setInt(D); | ||||||||||
11715 | break; | ||||||||||
11716 | } | ||||||||||
11717 | } | ||||||||||
11718 | return D; | ||||||||||
11719 | } | ||||||||||
11720 | |||||||||||
11721 | ScalarEvolution::BlockDisposition | ||||||||||
11722 | ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { | ||||||||||
11723 | switch (static_cast<SCEVTypes>(S->getSCEVType())) { | ||||||||||
11724 | case scConstant: | ||||||||||
11725 | return ProperlyDominatesBlock; | ||||||||||
11726 | case scTruncate: | ||||||||||
11727 | case scZeroExtend: | ||||||||||
11728 | case scSignExtend: | ||||||||||
11729 | return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); | ||||||||||
11730 | case scAddRecExpr: { | ||||||||||
11731 | // This uses a "dominates" query instead of "properly dominates" query | ||||||||||
11732 | // to test for proper dominance too, because the instruction which | ||||||||||
11733 | // produces the addrec's value is a PHI, and a PHI effectively properly | ||||||||||
11734 | // dominates its entire containing block. | ||||||||||
11735 | const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); | ||||||||||
11736 | if (!DT.dominates(AR->getLoop()->getHeader(), BB)) | ||||||||||
11737 | return DoesNotDominateBlock; | ||||||||||
11738 | |||||||||||
11739 | // Fall through into SCEVNAryExpr handling. | ||||||||||
11740 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||
11741 | } | ||||||||||
11742 | case scAddExpr: | ||||||||||
11743 | case scMulExpr: | ||||||||||
11744 | case scUMaxExpr: | ||||||||||
11745 | case scSMaxExpr: | ||||||||||
11746 | case scUMinExpr: | ||||||||||
11747 | case scSMinExpr: { | ||||||||||
11748 | const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); | ||||||||||
11749 | bool Proper = true; | ||||||||||
11750 | for (const SCEV *NAryOp : NAry->operands()) { | ||||||||||
11751 | BlockDisposition D = getBlockDisposition(NAryOp, BB); | ||||||||||
11752 | if (D == DoesNotDominateBlock) | ||||||||||
11753 | return DoesNotDominateBlock; | ||||||||||
11754 | if (D == DominatesBlock) | ||||||||||
11755 | Proper = false; | ||||||||||
11756 | } | ||||||||||
11757 | return Proper ? ProperlyDominatesBlock : DominatesBlock; | ||||||||||
11758 | } | ||||||||||
11759 | case scUDivExpr: { | ||||||||||
11760 | const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); | ||||||||||
11761 | const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); | ||||||||||
11762 | BlockDisposition LD = getBlockDisposition(LHS, BB); | ||||||||||
11763 | if (LD == DoesNotDominateBlock) | ||||||||||
11764 | return DoesNotDominateBlock; | ||||||||||
11765 | BlockDisposition RD = getBlockDisposition(RHS, BB); | ||||||||||
11766 | if (RD == DoesNotDominateBlock) | ||||||||||
11767 | return DoesNotDominateBlock; | ||||||||||
11768 | return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? | ||||||||||
11769 | ProperlyDominatesBlock : DominatesBlock; | ||||||||||
11770 | } | ||||||||||
11771 | case scUnknown: | ||||||||||
11772 | if (Instruction *I = | ||||||||||
11773 | dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { | ||||||||||
11774 | if (I->getParent() == BB) | ||||||||||
11775 | return DominatesBlock; | ||||||||||
11776 | if (DT.properlyDominates(I->getParent(), BB)) | ||||||||||
11777 | return ProperlyDominatesBlock; | ||||||||||
11778 | return DoesNotDominateBlock; | ||||||||||
11779 | } | ||||||||||
11780 | return ProperlyDominatesBlock; | ||||||||||
11781 | case scCouldNotCompute: | ||||||||||
11782 | llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!")::llvm::llvm_unreachable_internal("Attempt to use a SCEVCouldNotCompute object!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11782); | ||||||||||
11783 | } | ||||||||||
11784 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 11784); | ||||||||||
11785 | } | ||||||||||
11786 | |||||||||||
11787 | bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { | ||||||||||
11788 | return getBlockDisposition(S, BB) >= DominatesBlock; | ||||||||||
11789 | } | ||||||||||
11790 | |||||||||||
11791 | bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { | ||||||||||
11792 | return getBlockDisposition(S, BB) == ProperlyDominatesBlock; | ||||||||||
11793 | } | ||||||||||
11794 | |||||||||||
11795 | bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { | ||||||||||
11796 | return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); | ||||||||||
11797 | } | ||||||||||
11798 | |||||||||||
11799 | bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { | ||||||||||
11800 | auto IsS = [&](const SCEV *X) { return S == X; }; | ||||||||||
11801 | auto ContainsS = [&](const SCEV *X) { | ||||||||||
11802 | return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); | ||||||||||
11803 | }; | ||||||||||
11804 | return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); | ||||||||||
11805 | } | ||||||||||
11806 | |||||||||||
11807 | void | ||||||||||
11808 | ScalarEvolution::forgetMemoizedResults(const SCEV *S) { | ||||||||||
11809 | ValuesAtScopes.erase(S); | ||||||||||
11810 | LoopDispositions.erase(S); | ||||||||||
11811 | BlockDispositions.erase(S); | ||||||||||
11812 | UnsignedRanges.erase(S); | ||||||||||
11813 | SignedRanges.erase(S); | ||||||||||
11814 | ExprValueMap.erase(S); | ||||||||||
11815 | HasRecMap.erase(S); | ||||||||||
11816 | MinTrailingZerosCache.erase(S); | ||||||||||
11817 | |||||||||||
11818 | for (auto I = PredicatedSCEVRewrites.begin(); | ||||||||||
11819 | I != PredicatedSCEVRewrites.end();) { | ||||||||||
11820 | std::pair<const SCEV *, const Loop *> Entry = I->first; | ||||||||||
11821 | if (Entry.first == S) | ||||||||||
11822 | PredicatedSCEVRewrites.erase(I++); | ||||||||||
11823 | else | ||||||||||
11824 | ++I; | ||||||||||
11825 | } | ||||||||||
11826 | |||||||||||
11827 | auto RemoveSCEVFromBackedgeMap = | ||||||||||
11828 | [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { | ||||||||||
11829 | for (auto I = Map.begin(), E = Map.end(); I != E;) { | ||||||||||
11830 | BackedgeTakenInfo &BEInfo = I->second; | ||||||||||
11831 | if (BEInfo.hasOperand(S, this)) { | ||||||||||
11832 | BEInfo.clear(); | ||||||||||
11833 | Map.erase(I++); | ||||||||||
11834 | } else | ||||||||||
11835 | ++I; | ||||||||||
11836 | } | ||||||||||
11837 | }; | ||||||||||
11838 | |||||||||||
11839 | RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); | ||||||||||
11840 | RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); | ||||||||||
11841 | } | ||||||||||
11842 | |||||||||||
11843 | void | ||||||||||
11844 | ScalarEvolution::getUsedLoops(const SCEV *S, | ||||||||||
11845 | SmallPtrSetImpl<const Loop *> &LoopsUsed) { | ||||||||||
11846 | struct FindUsedLoops { | ||||||||||
11847 | FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) | ||||||||||
11848 | : LoopsUsed(LoopsUsed) {} | ||||||||||
11849 | SmallPtrSetImpl<const Loop *> &LoopsUsed; | ||||||||||
11850 | bool follow(const SCEV *S) { | ||||||||||
11851 | if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) | ||||||||||
11852 | LoopsUsed.insert(AR->getLoop()); | ||||||||||
11853 | return true; | ||||||||||
11854 | } | ||||||||||
11855 | |||||||||||
11856 | bool isDone() const { return false; } | ||||||||||
11857 | }; | ||||||||||
11858 | |||||||||||
11859 | FindUsedLoops F(LoopsUsed); | ||||||||||
11860 | SCEVTraversal<FindUsedLoops>(F).visitAll(S); | ||||||||||
11861 | } | ||||||||||
11862 | |||||||||||
11863 | void ScalarEvolution::addToLoopUseLists(const SCEV *S) { | ||||||||||
11864 | SmallPtrSet<const Loop *, 8> LoopsUsed; | ||||||||||
11865 | getUsedLoops(S, LoopsUsed); | ||||||||||
11866 | for (auto *L : LoopsUsed) | ||||||||||
11867 | LoopUsers[L].push_back(S); | ||||||||||
11868 | } | ||||||||||
11869 | |||||||||||
11870 | void ScalarEvolution::verify() const { | ||||||||||
11871 | ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); | ||||||||||
11872 | ScalarEvolution SE2(F, TLI, AC, DT, LI); | ||||||||||
11873 | |||||||||||
11874 | SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); | ||||||||||
11875 | |||||||||||
11876 | // Map's SCEV expressions from one ScalarEvolution "universe" to another. | ||||||||||
11877 | struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { | ||||||||||
11878 | SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} | ||||||||||
11879 | |||||||||||
11880 | const SCEV *visitConstant(const SCEVConstant *Constant) { | ||||||||||
11881 | return SE.getConstant(Constant->getAPInt()); | ||||||||||
11882 | } | ||||||||||
11883 | |||||||||||
11884 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
11885 | return SE.getUnknown(Expr->getValue()); | ||||||||||
11886 | } | ||||||||||
11887 | |||||||||||
11888 | const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { | ||||||||||
11889 | return SE.getCouldNotCompute(); | ||||||||||
11890 | } | ||||||||||
11891 | }; | ||||||||||
11892 | |||||||||||
11893 | SCEVMapper SCM(SE2); | ||||||||||
11894 | |||||||||||
11895 | while (!LoopStack.empty()) { | ||||||||||
11896 | auto *L = LoopStack.pop_back_val(); | ||||||||||
11897 | LoopStack.insert(LoopStack.end(), L->begin(), L->end()); | ||||||||||
11898 | |||||||||||
11899 | auto *CurBECount = SCM.visit( | ||||||||||
11900 | const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); | ||||||||||
11901 | auto *NewBECount = SE2.getBackedgeTakenCount(L); | ||||||||||
11902 | |||||||||||
11903 | if (CurBECount == SE2.getCouldNotCompute() || | ||||||||||
11904 | NewBECount == SE2.getCouldNotCompute()) { | ||||||||||
11905 | // NB! This situation is legal, but is very suspicious -- whatever pass | ||||||||||
11906 | // change the loop to make a trip count go from could not compute to | ||||||||||
11907 | // computable or vice-versa *should have* invalidated SCEV. However, we | ||||||||||
11908 | // choose not to assert here (for now) since we don't want false | ||||||||||
11909 | // positives. | ||||||||||
11910 | continue; | ||||||||||
11911 | } | ||||||||||
11912 | |||||||||||
11913 | if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { | ||||||||||
11914 | // SCEV treats "undef" as an unknown but consistent value (i.e. it does | ||||||||||
11915 | // not propagate undef aggressively). This means we can (and do) fail | ||||||||||
11916 | // verification in cases where a transform makes the trip count of a loop | ||||||||||
11917 | // go from "undef" to "undef+1" (say). The transform is fine, since in | ||||||||||
11918 | // both cases the loop iterates "undef" times, but SCEV thinks we | ||||||||||
11919 | // increased the trip count of the loop by 1 incorrectly. | ||||||||||
11920 | continue; | ||||||||||
11921 | } | ||||||||||
11922 | |||||||||||
11923 | if (SE.getTypeSizeInBits(CurBECount->getType()) > | ||||||||||
11924 | SE.getTypeSizeInBits(NewBECount->getType())) | ||||||||||
11925 | NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); | ||||||||||
11926 | else if (SE.getTypeSizeInBits(CurBECount->getType()) < | ||||||||||
11927 | SE.getTypeSizeInBits(NewBECount->getType())) | ||||||||||
11928 | CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); | ||||||||||
11929 | |||||||||||
11930 | const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); | ||||||||||
11931 | |||||||||||
11932 | // Unless VerifySCEVStrict is set, we only compare constant deltas. | ||||||||||
11933 | if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { | ||||||||||
11934 | dbgs() << "Trip Count for " << *L << " Changed!\n"; | ||||||||||
11935 | dbgs() << "Old: " << *CurBECount << "\n"; | ||||||||||
11936 | dbgs() << "New: " << *NewBECount << "\n"; | ||||||||||
11937 | dbgs() << "Delta: " << *Delta << "\n"; | ||||||||||
11938 | std::abort(); | ||||||||||
11939 | } | ||||||||||
11940 | } | ||||||||||
11941 | } | ||||||||||
11942 | |||||||||||
11943 | bool ScalarEvolution::invalidate( | ||||||||||
11944 | Function &F, const PreservedAnalyses &PA, | ||||||||||
11945 | FunctionAnalysisManager::Invalidator &Inv) { | ||||||||||
11946 | // Invalidate the ScalarEvolution object whenever it isn't preserved or one | ||||||||||
11947 | // of its dependencies is invalidated. | ||||||||||
11948 | auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); | ||||||||||
11949 | return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || | ||||||||||
11950 | Inv.invalidate<AssumptionAnalysis>(F, PA) || | ||||||||||
11951 | Inv.invalidate<DominatorTreeAnalysis>(F, PA) || | ||||||||||
11952 | Inv.invalidate<LoopAnalysis>(F, PA); | ||||||||||
11953 | } | ||||||||||
11954 | |||||||||||
11955 | AnalysisKey ScalarEvolutionAnalysis::Key; | ||||||||||
11956 | |||||||||||
11957 | ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, | ||||||||||
11958 | FunctionAnalysisManager &AM) { | ||||||||||
11959 | return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), | ||||||||||
11960 | AM.getResult<AssumptionAnalysis>(F), | ||||||||||
11961 | AM.getResult<DominatorTreeAnalysis>(F), | ||||||||||
11962 | AM.getResult<LoopAnalysis>(F)); | ||||||||||
11963 | } | ||||||||||
11964 | |||||||||||
11965 | PreservedAnalyses | ||||||||||
11966 | ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { | ||||||||||
11967 | AM.getResult<ScalarEvolutionAnalysis>(F).verify(); | ||||||||||
11968 | return PreservedAnalyses::all(); | ||||||||||
11969 | } | ||||||||||
11970 | |||||||||||
11971 | PreservedAnalyses | ||||||||||
11972 | ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { | ||||||||||
11973 | // For compatibility with opt's -analyze feature under legacy pass manager | ||||||||||
11974 | // which was not ported to NPM. This keeps tests using | ||||||||||
11975 | // update_analyze_test_checks.py working. | ||||||||||
11976 | OS << "Printing analysis 'Scalar Evolution Analysis' for function '" | ||||||||||
11977 | << F.getName() << "':\n"; | ||||||||||
11978 | AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); | ||||||||||
11979 | return PreservedAnalyses::all(); | ||||||||||
11980 | } | ||||||||||
11981 | |||||||||||
11982 | INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry &Registry) { | ||||||||||
11983 | "Scalar Evolution Analysis", false, true)static void *initializeScalarEvolutionWrapperPassPassOnce(PassRegistry &Registry) { | ||||||||||
11984 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | ||||||||||
11985 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry); | ||||||||||
11986 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry); | ||||||||||
11987 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry); | ||||||||||
11988 | INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",PassInfo *PI = new PassInfo( "Scalar Evolution Analysis", "scalar-evolution" , &ScalarEvolutionWrapperPass::ID, PassInfo::NormalCtor_t (callDefaultCtor<ScalarEvolutionWrapperPass>), false, true ); Registry.registerPass(*PI, true); return PI; } static llvm ::once_flag InitializeScalarEvolutionWrapperPassPassFlag; void llvm::initializeScalarEvolutionWrapperPassPass(PassRegistry & Registry) { llvm::call_once(InitializeScalarEvolutionWrapperPassPassFlag , initializeScalarEvolutionWrapperPassPassOnce, std::ref(Registry )); } | ||||||||||
11989 | "Scalar Evolution Analysis", false, true)PassInfo *PI = new PassInfo( "Scalar Evolution Analysis", "scalar-evolution" , &ScalarEvolutionWrapperPass::ID, PassInfo::NormalCtor_t (callDefaultCtor<ScalarEvolutionWrapperPass>), false, true ); Registry.registerPass(*PI, true); return PI; } static llvm ::once_flag InitializeScalarEvolutionWrapperPassPassFlag; void llvm::initializeScalarEvolutionWrapperPassPass(PassRegistry & Registry) { llvm::call_once(InitializeScalarEvolutionWrapperPassPassFlag , initializeScalarEvolutionWrapperPassPassOnce, std::ref(Registry )); } | ||||||||||
11990 | |||||||||||
11991 | char ScalarEvolutionWrapperPass::ID = 0; | ||||||||||
11992 | |||||||||||
11993 | ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { | ||||||||||
11994 | initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); | ||||||||||
11995 | } | ||||||||||
11996 | |||||||||||
11997 | bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { | ||||||||||
11998 | SE.reset(new ScalarEvolution( | ||||||||||
11999 | F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), | ||||||||||
12000 | getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), | ||||||||||
12001 | getAnalysis<DominatorTreeWrapperPass>().getDomTree(), | ||||||||||
12002 | getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); | ||||||||||
12003 | return false; | ||||||||||
12004 | } | ||||||||||
12005 | |||||||||||
12006 | void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } | ||||||||||
12007 | |||||||||||
12008 | void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { | ||||||||||
12009 | SE->print(OS); | ||||||||||
12010 | } | ||||||||||
12011 | |||||||||||
12012 | void ScalarEvolutionWrapperPass::verifyAnalysis() const { | ||||||||||
12013 | if (!VerifySCEV) | ||||||||||
12014 | return; | ||||||||||
12015 | |||||||||||
12016 | SE->verify(); | ||||||||||
12017 | } | ||||||||||
12018 | |||||||||||
12019 | void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { | ||||||||||
12020 | AU.setPreservesAll(); | ||||||||||
12021 | AU.addRequiredTransitive<AssumptionCacheTracker>(); | ||||||||||
12022 | AU.addRequiredTransitive<LoopInfoWrapperPass>(); | ||||||||||
12023 | AU.addRequiredTransitive<DominatorTreeWrapperPass>(); | ||||||||||
12024 | AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); | ||||||||||
12025 | } | ||||||||||
12026 | |||||||||||
12027 | const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, | ||||||||||
12028 | const SCEV *RHS) { | ||||||||||
12029 | FoldingSetNodeID ID; | ||||||||||
12030 | assert(LHS->getType() == RHS->getType() &&((LHS->getType() == RHS->getType() && "Type mismatch between LHS and RHS" ) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12031, __PRETTY_FUNCTION__)) | ||||||||||
12031 | "Type mismatch between LHS and RHS")((LHS->getType() == RHS->getType() && "Type mismatch between LHS and RHS" ) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Type mismatch between LHS and RHS\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12031, __PRETTY_FUNCTION__)); | ||||||||||
12032 | // Unique this node based on the arguments | ||||||||||
12033 | ID.AddInteger(SCEVPredicate::P_Equal); | ||||||||||
12034 | ID.AddPointer(LHS); | ||||||||||
12035 | ID.AddPointer(RHS); | ||||||||||
12036 | void *IP = nullptr; | ||||||||||
12037 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) | ||||||||||
12038 | return S; | ||||||||||
12039 | SCEVEqualPredicate *Eq = new (SCEVAllocator) | ||||||||||
12040 | SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); | ||||||||||
12041 | UniquePreds.InsertNode(Eq, IP); | ||||||||||
12042 | return Eq; | ||||||||||
12043 | } | ||||||||||
12044 | |||||||||||
12045 | const SCEVPredicate *ScalarEvolution::getWrapPredicate( | ||||||||||
12046 | const SCEVAddRecExpr *AR, | ||||||||||
12047 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { | ||||||||||
12048 | FoldingSetNodeID ID; | ||||||||||
12049 | // Unique this node based on the arguments | ||||||||||
12050 | ID.AddInteger(SCEVPredicate::P_Wrap); | ||||||||||
12051 | ID.AddPointer(AR); | ||||||||||
12052 | ID.AddInteger(AddedFlags); | ||||||||||
12053 | void *IP = nullptr; | ||||||||||
12054 | if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) | ||||||||||
12055 | return S; | ||||||||||
12056 | auto *OF = new (SCEVAllocator) | ||||||||||
12057 | SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); | ||||||||||
12058 | UniquePreds.InsertNode(OF, IP); | ||||||||||
12059 | return OF; | ||||||||||
12060 | } | ||||||||||
12061 | |||||||||||
12062 | namespace { | ||||||||||
12063 | |||||||||||
12064 | class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { | ||||||||||
12065 | public: | ||||||||||
12066 | |||||||||||
12067 | /// Rewrites \p S in the context of a loop L and the SCEV predication | ||||||||||
12068 | /// infrastructure. | ||||||||||
12069 | /// | ||||||||||
12070 | /// If \p Pred is non-null, the SCEV expression is rewritten to respect the | ||||||||||
12071 | /// equivalences present in \p Pred. | ||||||||||
12072 | /// | ||||||||||
12073 | /// If \p NewPreds is non-null, rewrite is free to add further predicates to | ||||||||||
12074 | /// \p NewPreds such that the result will be an AddRecExpr. | ||||||||||
12075 | static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, | ||||||||||
12076 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, | ||||||||||
12077 | SCEVUnionPredicate *Pred) { | ||||||||||
12078 | SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); | ||||||||||
12079 | return Rewriter.visit(S); | ||||||||||
12080 | } | ||||||||||
12081 | |||||||||||
12082 | const SCEV *visitUnknown(const SCEVUnknown *Expr) { | ||||||||||
12083 | if (Pred) { | ||||||||||
12084 | auto ExprPreds = Pred->getPredicatesForExpr(Expr); | ||||||||||
12085 | for (auto *Pred : ExprPreds) | ||||||||||
12086 | if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) | ||||||||||
12087 | if (IPred->getLHS() == Expr) | ||||||||||
12088 | return IPred->getRHS(); | ||||||||||
12089 | } | ||||||||||
12090 | return convertToAddRecWithPreds(Expr); | ||||||||||
12091 | } | ||||||||||
12092 | |||||||||||
12093 | const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { | ||||||||||
12094 | const SCEV *Operand = visit(Expr->getOperand()); | ||||||||||
12095 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); | ||||||||||
12096 | if (AR && AR->getLoop() == L && AR->isAffine()) { | ||||||||||
12097 | // This couldn't be folded because the operand didn't have the nuw | ||||||||||
12098 | // flag. Add the nusw flag as an assumption that we could make. | ||||||||||
12099 | const SCEV *Step = AR->getStepRecurrence(SE); | ||||||||||
12100 | Type *Ty = Expr->getType(); | ||||||||||
12101 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) | ||||||||||
12102 | return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), | ||||||||||
12103 | SE.getSignExtendExpr(Step, Ty), L, | ||||||||||
12104 | AR->getNoWrapFlags()); | ||||||||||
12105 | } | ||||||||||
12106 | return SE.getZeroExtendExpr(Operand, Expr->getType()); | ||||||||||
12107 | } | ||||||||||
12108 | |||||||||||
12109 | const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { | ||||||||||
12110 | const SCEV *Operand = visit(Expr->getOperand()); | ||||||||||
12111 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); | ||||||||||
12112 | if (AR && AR->getLoop() == L && AR->isAffine()) { | ||||||||||
12113 | // This couldn't be folded because the operand didn't have the nsw | ||||||||||
12114 | // flag. Add the nssw flag as an assumption that we could make. | ||||||||||
12115 | const SCEV *Step = AR->getStepRecurrence(SE); | ||||||||||
12116 | Type *Ty = Expr->getType(); | ||||||||||
12117 | if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) | ||||||||||
12118 | return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), | ||||||||||
12119 | SE.getSignExtendExpr(Step, Ty), L, | ||||||||||
12120 | AR->getNoWrapFlags()); | ||||||||||
12121 | } | ||||||||||
12122 | return SE.getSignExtendExpr(Operand, Expr->getType()); | ||||||||||
12123 | } | ||||||||||
12124 | |||||||||||
12125 | private: | ||||||||||
12126 | explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, | ||||||||||
12127 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, | ||||||||||
12128 | SCEVUnionPredicate *Pred) | ||||||||||
12129 | : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} | ||||||||||
12130 | |||||||||||
12131 | bool addOverflowAssumption(const SCEVPredicate *P) { | ||||||||||
12132 | if (!NewPreds) { | ||||||||||
12133 | // Check if we've already made this assumption. | ||||||||||
12134 | return Pred && Pred->implies(P); | ||||||||||
12135 | } | ||||||||||
12136 | NewPreds->insert(P); | ||||||||||
12137 | return true; | ||||||||||
12138 | } | ||||||||||
12139 | |||||||||||
12140 | bool addOverflowAssumption(const SCEVAddRecExpr *AR, | ||||||||||
12141 | SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { | ||||||||||
12142 | auto *A = SE.getWrapPredicate(AR, AddedFlags); | ||||||||||
12143 | return addOverflowAssumption(A); | ||||||||||
12144 | } | ||||||||||
12145 | |||||||||||
12146 | // If \p Expr represents a PHINode, we try to see if it can be represented | ||||||||||
12147 | // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible | ||||||||||
12148 | // to add this predicate as a runtime overflow check, we return the AddRec. | ||||||||||
12149 | // If \p Expr does not meet these conditions (is not a PHI node, or we | ||||||||||
12150 | // couldn't create an AddRec for it, or couldn't add the predicate), we just | ||||||||||
12151 | // return \p Expr. | ||||||||||
12152 | const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { | ||||||||||
12153 | if (!isa<PHINode>(Expr->getValue())) | ||||||||||
12154 | return Expr; | ||||||||||
12155 | Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> | ||||||||||
12156 | PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); | ||||||||||
12157 | if (!PredicatedRewrite) | ||||||||||
12158 | return Expr; | ||||||||||
12159 | for (auto *P : PredicatedRewrite->second){ | ||||||||||
12160 | // Wrap predicates from outer loops are not supported. | ||||||||||
12161 | if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { | ||||||||||
12162 | auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); | ||||||||||
12163 | if (L != AR->getLoop()) | ||||||||||
12164 | return Expr; | ||||||||||
12165 | } | ||||||||||
12166 | if (!addOverflowAssumption(P)) | ||||||||||
12167 | return Expr; | ||||||||||
12168 | } | ||||||||||
12169 | return PredicatedRewrite->first; | ||||||||||
12170 | } | ||||||||||
12171 | |||||||||||
12172 | SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; | ||||||||||
12173 | SCEVUnionPredicate *Pred; | ||||||||||
12174 | const Loop *L; | ||||||||||
12175 | }; | ||||||||||
12176 | |||||||||||
12177 | } // end anonymous namespace | ||||||||||
12178 | |||||||||||
12179 | const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, | ||||||||||
12180 | SCEVUnionPredicate &Preds) { | ||||||||||
12181 | return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); | ||||||||||
12182 | } | ||||||||||
12183 | |||||||||||
12184 | const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( | ||||||||||
12185 | const SCEV *S, const Loop *L, | ||||||||||
12186 | SmallPtrSetImpl<const SCEVPredicate *> &Preds) { | ||||||||||
12187 | SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; | ||||||||||
12188 | S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); | ||||||||||
12189 | auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); | ||||||||||
12190 | |||||||||||
12191 | if (!AddRec) | ||||||||||
12192 | return nullptr; | ||||||||||
12193 | |||||||||||
12194 | // Since the transformation was successful, we can now transfer the SCEV | ||||||||||
12195 | // predicates. | ||||||||||
12196 | for (auto *P : TransformPreds) | ||||||||||
12197 | Preds.insert(P); | ||||||||||
12198 | |||||||||||
12199 | return AddRec; | ||||||||||
12200 | } | ||||||||||
12201 | |||||||||||
12202 | /// SCEV predicates | ||||||||||
12203 | SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, | ||||||||||
12204 | SCEVPredicateKind Kind) | ||||||||||
12205 | : FastID(ID), Kind(Kind) {} | ||||||||||
12206 | |||||||||||
12207 | SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, | ||||||||||
12208 | const SCEV *LHS, const SCEV *RHS) | ||||||||||
12209 | : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { | ||||||||||
12210 | assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match")((LHS->getType() == RHS->getType() && "LHS and RHS types don't match" ) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS types don't match\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12210, __PRETTY_FUNCTION__)); | ||||||||||
12211 | assert(LHS != RHS && "LHS and RHS are the same SCEV")((LHS != RHS && "LHS and RHS are the same SCEV") ? static_cast <void> (0) : __assert_fail ("LHS != RHS && \"LHS and RHS are the same SCEV\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12211, __PRETTY_FUNCTION__)); | ||||||||||
12212 | } | ||||||||||
12213 | |||||||||||
12214 | bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { | ||||||||||
12215 | const auto *Op = dyn_cast<SCEVEqualPredicate>(N); | ||||||||||
12216 | |||||||||||
12217 | if (!Op) | ||||||||||
12218 | return false; | ||||||||||
12219 | |||||||||||
12220 | return Op->LHS == LHS && Op->RHS == RHS; | ||||||||||
12221 | } | ||||||||||
12222 | |||||||||||
12223 | bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } | ||||||||||
12224 | |||||||||||
12225 | const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } | ||||||||||
12226 | |||||||||||
12227 | void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { | ||||||||||
12228 | OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; | ||||||||||
12229 | } | ||||||||||
12230 | |||||||||||
12231 | SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, | ||||||||||
12232 | const SCEVAddRecExpr *AR, | ||||||||||
12233 | IncrementWrapFlags Flags) | ||||||||||
12234 | : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} | ||||||||||
12235 | |||||||||||
12236 | const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } | ||||||||||
12237 | |||||||||||
12238 | bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { | ||||||||||
12239 | const auto *Op = dyn_cast<SCEVWrapPredicate>(N); | ||||||||||
12240 | |||||||||||
12241 | return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; | ||||||||||
12242 | } | ||||||||||
12243 | |||||||||||
12244 | bool SCEVWrapPredicate::isAlwaysTrue() const { | ||||||||||
12245 | SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); | ||||||||||
12246 | IncrementWrapFlags IFlags = Flags; | ||||||||||
12247 | |||||||||||
12248 | if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) | ||||||||||
12249 | IFlags = clearFlags(IFlags, IncrementNSSW); | ||||||||||
12250 | |||||||||||
12251 | return IFlags == IncrementAnyWrap; | ||||||||||
12252 | } | ||||||||||
12253 | |||||||||||
12254 | void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { | ||||||||||
12255 | OS.indent(Depth) << *getExpr() << " Added Flags: "; | ||||||||||
12256 | if (SCEVWrapPredicate::IncrementNUSW & getFlags()) | ||||||||||
12257 | OS << "<nusw>"; | ||||||||||
12258 | if (SCEVWrapPredicate::IncrementNSSW & getFlags()) | ||||||||||
12259 | OS << "<nssw>"; | ||||||||||
12260 | OS << "\n"; | ||||||||||
12261 | } | ||||||||||
12262 | |||||||||||
12263 | SCEVWrapPredicate::IncrementWrapFlags | ||||||||||
12264 | SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, | ||||||||||
12265 | ScalarEvolution &SE) { | ||||||||||
12266 | IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; | ||||||||||
12267 | SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); | ||||||||||
12268 | |||||||||||
12269 | // We can safely transfer the NSW flag as NSSW. | ||||||||||
12270 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) | ||||||||||
12271 | ImpliedFlags = IncrementNSSW; | ||||||||||
12272 | |||||||||||
12273 | if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { | ||||||||||
12274 | // If the increment is positive, the SCEV NUW flag will also imply the | ||||||||||
12275 | // WrapPredicate NUSW flag. | ||||||||||
12276 | if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) | ||||||||||
12277 | if (Step->getValue()->getValue().isNonNegative()) | ||||||||||
12278 | ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); | ||||||||||
12279 | } | ||||||||||
12280 | |||||||||||
12281 | return ImpliedFlags; | ||||||||||
12282 | } | ||||||||||
12283 | |||||||||||
12284 | /// Union predicates don't get cached so create a dummy set ID for it. | ||||||||||
12285 | SCEVUnionPredicate::SCEVUnionPredicate() | ||||||||||
12286 | : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} | ||||||||||
12287 | |||||||||||
12288 | bool SCEVUnionPredicate::isAlwaysTrue() const { | ||||||||||
12289 | return all_of(Preds, | ||||||||||
12290 | [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); | ||||||||||
12291 | } | ||||||||||
12292 | |||||||||||
12293 | ArrayRef<const SCEVPredicate *> | ||||||||||
12294 | SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { | ||||||||||
12295 | auto I = SCEVToPreds.find(Expr); | ||||||||||
12296 | if (I == SCEVToPreds.end()) | ||||||||||
12297 | return ArrayRef<const SCEVPredicate *>(); | ||||||||||
12298 | return I->second; | ||||||||||
12299 | } | ||||||||||
12300 | |||||||||||
12301 | bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { | ||||||||||
12302 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) | ||||||||||
12303 | return all_of(Set->Preds, | ||||||||||
12304 | [this](const SCEVPredicate *I) { return this->implies(I); }); | ||||||||||
12305 | |||||||||||
12306 | auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); | ||||||||||
12307 | if (ScevPredsIt == SCEVToPreds.end()) | ||||||||||
12308 | return false; | ||||||||||
12309 | auto &SCEVPreds = ScevPredsIt->second; | ||||||||||
12310 | |||||||||||
12311 | return any_of(SCEVPreds, | ||||||||||
12312 | [N](const SCEVPredicate *I) { return I->implies(N); }); | ||||||||||
12313 | } | ||||||||||
12314 | |||||||||||
12315 | const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } | ||||||||||
12316 | |||||||||||
12317 | void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { | ||||||||||
12318 | for (auto Pred : Preds) | ||||||||||
12319 | Pred->print(OS, Depth); | ||||||||||
12320 | } | ||||||||||
12321 | |||||||||||
12322 | void SCEVUnionPredicate::add(const SCEVPredicate *N) { | ||||||||||
12323 | if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { | ||||||||||
12324 | for (auto Pred : Set->Preds) | ||||||||||
12325 | add(Pred); | ||||||||||
12326 | return; | ||||||||||
12327 | } | ||||||||||
12328 | |||||||||||
12329 | if (implies(N)) | ||||||||||
12330 | return; | ||||||||||
12331 | |||||||||||
12332 | const SCEV *Key = N->getExpr(); | ||||||||||
12333 | assert(Key && "Only SCEVUnionPredicate doesn't have an "((Key && "Only SCEVUnionPredicate doesn't have an " " associated expression!" ) ? static_cast<void> (0) : __assert_fail ("Key && \"Only SCEVUnionPredicate doesn't have an \" \" associated expression!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12334, __PRETTY_FUNCTION__)) | ||||||||||
12334 | " associated expression!")((Key && "Only SCEVUnionPredicate doesn't have an " " associated expression!" ) ? static_cast<void> (0) : __assert_fail ("Key && \"Only SCEVUnionPredicate doesn't have an \" \" associated expression!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12334, __PRETTY_FUNCTION__)); | ||||||||||
12335 | |||||||||||
12336 | SCEVToPreds[Key].push_back(N); | ||||||||||
12337 | Preds.push_back(N); | ||||||||||
12338 | } | ||||||||||
12339 | |||||||||||
12340 | PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, | ||||||||||
12341 | Loop &L) | ||||||||||
12342 | : SE(SE), L(L) {} | ||||||||||
12343 | |||||||||||
12344 | const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { | ||||||||||
12345 | const SCEV *Expr = SE.getSCEV(V); | ||||||||||
12346 | RewriteEntry &Entry = RewriteMap[Expr]; | ||||||||||
12347 | |||||||||||
12348 | // If we already have an entry and the version matches, return it. | ||||||||||
12349 | if (Entry.second && Generation == Entry.first) | ||||||||||
12350 | return Entry.second; | ||||||||||
12351 | |||||||||||
12352 | // We found an entry but it's stale. Rewrite the stale entry | ||||||||||
12353 | // according to the current predicate. | ||||||||||
12354 | if (Entry.second) | ||||||||||
12355 | Expr = Entry.second; | ||||||||||
12356 | |||||||||||
12357 | const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); | ||||||||||
12358 | Entry = {Generation, NewSCEV}; | ||||||||||
12359 | |||||||||||
12360 | return NewSCEV; | ||||||||||
12361 | } | ||||||||||
12362 | |||||||||||
12363 | const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { | ||||||||||
12364 | if (!BackedgeCount) { | ||||||||||
12365 | SCEVUnionPredicate BackedgePred; | ||||||||||
12366 | BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); | ||||||||||
12367 | addPredicate(BackedgePred); | ||||||||||
12368 | } | ||||||||||
12369 | return BackedgeCount; | ||||||||||
12370 | } | ||||||||||
12371 | |||||||||||
12372 | void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { | ||||||||||
12373 | if (Preds.implies(&Pred)) | ||||||||||
12374 | return; | ||||||||||
12375 | Preds.add(&Pred); | ||||||||||
12376 | updateGeneration(); | ||||||||||
12377 | } | ||||||||||
12378 | |||||||||||
12379 | const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { | ||||||||||
12380 | return Preds; | ||||||||||
12381 | } | ||||||||||
12382 | |||||||||||
12383 | void PredicatedScalarEvolution::updateGeneration() { | ||||||||||
12384 | // If the generation number wrapped recompute everything. | ||||||||||
12385 | if (++Generation == 0) { | ||||||||||
12386 | for (auto &II : RewriteMap) { | ||||||||||
12387 | const SCEV *Rewritten = II.second.second; | ||||||||||
12388 | II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; | ||||||||||
12389 | } | ||||||||||
12390 | } | ||||||||||
12391 | } | ||||||||||
12392 | |||||||||||
12393 | void PredicatedScalarEvolution::setNoOverflow( | ||||||||||
12394 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { | ||||||||||
12395 | const SCEV *Expr = getSCEV(V); | ||||||||||
12396 | const auto *AR = cast<SCEVAddRecExpr>(Expr); | ||||||||||
12397 | |||||||||||
12398 | auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); | ||||||||||
12399 | |||||||||||
12400 | // Clear the statically implied flags. | ||||||||||
12401 | Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); | ||||||||||
12402 | addPredicate(*SE.getWrapPredicate(AR, Flags)); | ||||||||||
12403 | |||||||||||
12404 | auto II = FlagsMap.insert({V, Flags}); | ||||||||||
12405 | if (!II.second) | ||||||||||
12406 | II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); | ||||||||||
12407 | } | ||||||||||
12408 | |||||||||||
12409 | bool PredicatedScalarEvolution::hasNoOverflow( | ||||||||||
12410 | Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { | ||||||||||
12411 | const SCEV *Expr = getSCEV(V); | ||||||||||
12412 | const auto *AR = cast<SCEVAddRecExpr>(Expr); | ||||||||||
12413 | |||||||||||
12414 | Flags = SCEVWrapPredicate::clearFlags( | ||||||||||
12415 | Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); | ||||||||||
12416 | |||||||||||
12417 | auto II = FlagsMap.find(V); | ||||||||||
12418 | |||||||||||
12419 | if (II != FlagsMap.end()) | ||||||||||
12420 | Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); | ||||||||||
12421 | |||||||||||
12422 | return Flags == SCEVWrapPredicate::IncrementAnyWrap; | ||||||||||
12423 | } | ||||||||||
12424 | |||||||||||
12425 | const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { | ||||||||||
12426 | const SCEV *Expr = this->getSCEV(V); | ||||||||||
12427 | SmallPtrSet<const SCEVPredicate *, 4> NewPreds; | ||||||||||
12428 | auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); | ||||||||||
12429 | |||||||||||
12430 | if (!New) | ||||||||||
12431 | return nullptr; | ||||||||||
12432 | |||||||||||
12433 | for (auto *P : NewPreds) | ||||||||||
12434 | Preds.add(P); | ||||||||||
12435 | |||||||||||
12436 | updateGeneration(); | ||||||||||
12437 | RewriteMap[SE.getSCEV(V)] = {Generation, New}; | ||||||||||
12438 | return New; | ||||||||||
12439 | } | ||||||||||
12440 | |||||||||||
12441 | PredicatedScalarEvolution::PredicatedScalarEvolution( | ||||||||||
12442 | const PredicatedScalarEvolution &Init) | ||||||||||
12443 | : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), | ||||||||||
12444 | Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { | ||||||||||
12445 | for (auto I : Init.FlagsMap) | ||||||||||
12446 | FlagsMap.insert(I); | ||||||||||
12447 | } | ||||||||||
12448 | |||||||||||
12449 | void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { | ||||||||||
12450 | // For each block. | ||||||||||
12451 | for (auto *BB : L.getBlocks()) | ||||||||||
12452 | for (auto &I : *BB) { | ||||||||||
12453 | if (!SE.isSCEVable(I.getType())) | ||||||||||
12454 | continue; | ||||||||||
12455 | |||||||||||
12456 | auto *Expr = SE.getSCEV(&I); | ||||||||||
12457 | auto II = RewriteMap.find(Expr); | ||||||||||
12458 | |||||||||||
12459 | if (II == RewriteMap.end()) | ||||||||||
12460 | continue; | ||||||||||
12461 | |||||||||||
12462 | // Don't print things that are not interesting. | ||||||||||
12463 | if (II->second.second == Expr) | ||||||||||
12464 | continue; | ||||||||||
12465 | |||||||||||
12466 | OS.indent(Depth) << "[PSE]" << I << ":\n"; | ||||||||||
12467 | OS.indent(Depth + 2) << *Expr << "\n"; | ||||||||||
12468 | OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; | ||||||||||
12469 | } | ||||||||||
12470 | } | ||||||||||
12471 | |||||||||||
12472 | // Match the mathematical pattern A - (A / B) * B, where A and B can be | ||||||||||
12473 | // arbitrary expressions. | ||||||||||
12474 | // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is | ||||||||||
12475 | // 4, A / B becomes X / 8). | ||||||||||
12476 | bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, | ||||||||||
12477 | const SCEV *&RHS) { | ||||||||||
12478 | const auto *Add = dyn_cast<SCEVAddExpr>(Expr); | ||||||||||
12479 | if (Add == nullptr || Add->getNumOperands() != 2) | ||||||||||
12480 | return false; | ||||||||||
12481 | |||||||||||
12482 | const SCEV *A = Add->getOperand(1); | ||||||||||
12483 | const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); | ||||||||||
12484 | |||||||||||
12485 | if (Mul == nullptr) | ||||||||||
12486 | return false; | ||||||||||
12487 | |||||||||||
12488 | const auto MatchURemWithDivisor = [&](const SCEV *B) { | ||||||||||
12489 | // (SomeExpr + (-(SomeExpr / B) * B)). | ||||||||||
12490 | if (Expr == getURemExpr(A, B)) { | ||||||||||
12491 | LHS = A; | ||||||||||
12492 | RHS = B; | ||||||||||
12493 | return true; | ||||||||||
12494 | } | ||||||||||
12495 | return false; | ||||||||||
12496 | }; | ||||||||||
12497 | |||||||||||
12498 | // (SomeExpr + (-1 * (SomeExpr / B) * B)). | ||||||||||
12499 | if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) | ||||||||||
12500 | return MatchURemWithDivisor(Mul->getOperand(1)) || | ||||||||||
12501 | MatchURemWithDivisor(Mul->getOperand(2)); | ||||||||||
12502 | |||||||||||
12503 | // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). | ||||||||||
12504 | if (Mul->getNumOperands() == 2) | ||||||||||
12505 | return MatchURemWithDivisor(Mul->getOperand(1)) || | ||||||||||
12506 | MatchURemWithDivisor(Mul->getOperand(0)) || | ||||||||||
12507 | MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || | ||||||||||
12508 | MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); | ||||||||||
12509 | return false; | ||||||||||
12510 | } | ||||||||||
12511 | |||||||||||
12512 | const SCEV* ScalarEvolution::computeMaxBackedgeTakenCount(const Loop *L) { | ||||||||||
12513 | SmallVector<BasicBlock*, 16> ExitingBlocks; | ||||||||||
12514 | L->getExitingBlocks(ExitingBlocks); | ||||||||||
12515 | |||||||||||
12516 | // Form an expression for the maximum exit count possible for this loop. We | ||||||||||
12517 | // merge the max and exact information to approximate a version of | ||||||||||
12518 | // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. | ||||||||||
12519 | SmallVector<const SCEV*, 4> ExitCounts; | ||||||||||
12520 | for (BasicBlock *ExitingBB : ExitingBlocks) { | ||||||||||
12521 | const SCEV *ExitCount = getExitCount(L, ExitingBB); | ||||||||||
12522 | if (isa<SCEVCouldNotCompute>(ExitCount)) | ||||||||||
12523 | ExitCount = getExitCount(L, ExitingBB, | ||||||||||
12524 | ScalarEvolution::ConstantMaximum); | ||||||||||
12525 | if (!isa<SCEVCouldNotCompute>(ExitCount)) { | ||||||||||
12526 | assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that " "dominate latch!") ? static_cast<void> (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12528, __PRETTY_FUNCTION__)) | ||||||||||
12527 | "We should only have known counts for exiting blocks that "((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that " "dominate latch!") ? static_cast<void> (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12528, __PRETTY_FUNCTION__)) | ||||||||||
12528 | "dominate latch!")((DT.dominates(ExitingBB, L->getLoopLatch()) && "We should only have known counts for exiting blocks that " "dominate latch!") ? static_cast<void> (0) : __assert_fail ("DT.dominates(ExitingBB, L->getLoopLatch()) && \"We should only have known counts for exiting blocks that \" \"dominate latch!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ScalarEvolution.cpp" , 12528, __PRETTY_FUNCTION__)); | ||||||||||
12529 | ExitCounts.push_back(ExitCount); | ||||||||||
12530 | } | ||||||||||
12531 | } | ||||||||||
12532 | if (ExitCounts.empty()) | ||||||||||
12533 | return getCouldNotCompute(); | ||||||||||
12534 | return getUMinFromMismatchedTypes(ExitCounts); | ||||||||||
12535 | } |
1 | //===- llvm/Type.h - Classes for handling data types ------------*- C++ -*-===// |
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 declaration of the Type class. For more "Type" |
10 | // stuff, look in DerivedTypes.h. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_IR_TYPE_H |
15 | #define LLVM_IR_TYPE_H |
16 | |
17 | #include "llvm/ADT/APFloat.h" |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/SmallPtrSet.h" |
20 | #include "llvm/Support/CBindingWrapping.h" |
21 | #include "llvm/Support/Casting.h" |
22 | #include "llvm/Support/Compiler.h" |
23 | #include "llvm/Support/ErrorHandling.h" |
24 | #include "llvm/Support/TypeSize.h" |
25 | #include <cassert> |
26 | #include <cstdint> |
27 | #include <iterator> |
28 | |
29 | namespace llvm { |
30 | |
31 | template<class GraphType> struct GraphTraits; |
32 | class IntegerType; |
33 | class LLVMContext; |
34 | class PointerType; |
35 | class raw_ostream; |
36 | class StringRef; |
37 | |
38 | /// The instances of the Type class are immutable: once they are created, |
39 | /// they are never changed. Also note that only one instance of a particular |
40 | /// type is ever created. Thus seeing if two types are equal is a matter of |
41 | /// doing a trivial pointer comparison. To enforce that no two equal instances |
42 | /// are created, Type instances can only be created via static factory methods |
43 | /// in class Type and in derived classes. Once allocated, Types are never |
44 | /// free'd. |
45 | /// |
46 | class Type { |
47 | public: |
48 | //===--------------------------------------------------------------------===// |
49 | /// Definitions of all of the base types for the Type system. Based on this |
50 | /// value, you can cast to a class defined in DerivedTypes.h. |
51 | /// Note: If you add an element to this, you need to add an element to the |
52 | /// Type::getPrimitiveType function, or else things will break! |
53 | /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding. |
54 | /// |
55 | enum TypeID { |
56 | // PrimitiveTypes |
57 | HalfTyID = 0, ///< 16-bit floating point type |
58 | BFloatTyID, ///< 16-bit floating point type (7-bit significand) |
59 | FloatTyID, ///< 32-bit floating point type |
60 | DoubleTyID, ///< 64-bit floating point type |
61 | X86_FP80TyID, ///< 80-bit floating point type (X87) |
62 | FP128TyID, ///< 128-bit floating point type (112-bit significand) |
63 | PPC_FP128TyID, ///< 128-bit floating point type (two 64-bits, PowerPC) |
64 | VoidTyID, ///< type with no size |
65 | LabelTyID, ///< Labels |
66 | MetadataTyID, ///< Metadata |
67 | X86_MMXTyID, ///< MMX vectors (64 bits, X86 specific) |
68 | TokenTyID, ///< Tokens |
69 | |
70 | // Derived types... see DerivedTypes.h file. |
71 | IntegerTyID, ///< Arbitrary bit width integers |
72 | FunctionTyID, ///< Functions |
73 | PointerTyID, ///< Pointers |
74 | StructTyID, ///< Structures |
75 | ArrayTyID, ///< Arrays |
76 | FixedVectorTyID, ///< Fixed width SIMD vector type |
77 | ScalableVectorTyID ///< Scalable SIMD vector type |
78 | }; |
79 | |
80 | private: |
81 | /// This refers to the LLVMContext in which this type was uniqued. |
82 | LLVMContext &Context; |
83 | |
84 | TypeID ID : 8; // The current base type of this type. |
85 | unsigned SubclassData : 24; // Space for subclasses to store data. |
86 | // Note that this should be synchronized with |
87 | // MAX_INT_BITS value in IntegerType class. |
88 | |
89 | protected: |
90 | friend class LLVMContextImpl; |
91 | |
92 | explicit Type(LLVMContext &C, TypeID tid) |
93 | : Context(C), ID(tid), SubclassData(0) {} |
94 | ~Type() = default; |
95 | |
96 | unsigned getSubclassData() const { return SubclassData; } |
97 | |
98 | void setSubclassData(unsigned val) { |
99 | SubclassData = val; |
100 | // Ensure we don't have any accidental truncation. |
101 | assert(getSubclassData() == val && "Subclass data too large for field")((getSubclassData() == val && "Subclass data too large for field" ) ? static_cast<void> (0) : __assert_fail ("getSubclassData() == val && \"Subclass data too large for field\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 101, __PRETTY_FUNCTION__)); |
102 | } |
103 | |
104 | /// Keeps track of how many Type*'s there are in the ContainedTys list. |
105 | unsigned NumContainedTys = 0; |
106 | |
107 | /// A pointer to the array of Types contained by this Type. For example, this |
108 | /// includes the arguments of a function type, the elements of a structure, |
109 | /// the pointee of a pointer, the element type of an array, etc. This pointer |
110 | /// may be 0 for types that don't contain other types (Integer, Double, |
111 | /// Float). |
112 | Type * const *ContainedTys = nullptr; |
113 | |
114 | public: |
115 | /// Print the current type. |
116 | /// Omit the type details if \p NoDetails == true. |
117 | /// E.g., let %st = type { i32, i16 } |
118 | /// When \p NoDetails is true, we only print %st. |
119 | /// Put differently, \p NoDetails prints the type as if |
120 | /// inlined with the operands when printing an instruction. |
121 | void print(raw_ostream &O, bool IsForDebug = false, |
122 | bool NoDetails = false) const; |
123 | |
124 | void dump() const; |
125 | |
126 | /// Return the LLVMContext in which this type was uniqued. |
127 | LLVMContext &getContext() const { return Context; } |
128 | |
129 | //===--------------------------------------------------------------------===// |
130 | // Accessors for working with types. |
131 | // |
132 | |
133 | /// Return the type id for the type. This will return one of the TypeID enum |
134 | /// elements defined above. |
135 | TypeID getTypeID() const { return ID; } |
136 | |
137 | /// Return true if this is 'void'. |
138 | bool isVoidTy() const { return getTypeID() == VoidTyID; } |
139 | |
140 | /// Return true if this is 'half', a 16-bit IEEE fp type. |
141 | bool isHalfTy() const { return getTypeID() == HalfTyID; } |
142 | |
143 | /// Return true if this is 'bfloat', a 16-bit bfloat type. |
144 | bool isBFloatTy() const { return getTypeID() == BFloatTyID; } |
145 | |
146 | /// Return true if this is 'float', a 32-bit IEEE fp type. |
147 | bool isFloatTy() const { return getTypeID() == FloatTyID; } |
148 | |
149 | /// Return true if this is 'double', a 64-bit IEEE fp type. |
150 | bool isDoubleTy() const { return getTypeID() == DoubleTyID; } |
151 | |
152 | /// Return true if this is x86 long double. |
153 | bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; } |
154 | |
155 | /// Return true if this is 'fp128'. |
156 | bool isFP128Ty() const { return getTypeID() == FP128TyID; } |
157 | |
158 | /// Return true if this is powerpc long double. |
159 | bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; } |
160 | |
161 | /// Return true if this is one of the six floating-point types |
162 | bool isFloatingPointTy() const { |
163 | return getTypeID() == HalfTyID || getTypeID() == BFloatTyID || |
164 | getTypeID() == FloatTyID || getTypeID() == DoubleTyID || |
165 | getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID || |
166 | getTypeID() == PPC_FP128TyID; |
167 | } |
168 | |
169 | const fltSemantics &getFltSemantics() const { |
170 | switch (getTypeID()) { |
171 | case HalfTyID: return APFloat::IEEEhalf(); |
172 | case BFloatTyID: return APFloat::BFloat(); |
173 | case FloatTyID: return APFloat::IEEEsingle(); |
174 | case DoubleTyID: return APFloat::IEEEdouble(); |
175 | case X86_FP80TyID: return APFloat::x87DoubleExtended(); |
176 | case FP128TyID: return APFloat::IEEEquad(); |
177 | case PPC_FP128TyID: return APFloat::PPCDoubleDouble(); |
178 | default: llvm_unreachable("Invalid floating type")::llvm::llvm_unreachable_internal("Invalid floating type", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 178); |
179 | } |
180 | } |
181 | |
182 | /// Return true if this is X86 MMX. |
183 | bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; } |
184 | |
185 | /// Return true if this is a FP type or a vector of FP. |
186 | bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); } |
187 | |
188 | /// Return true if this is 'label'. |
189 | bool isLabelTy() const { return getTypeID() == LabelTyID; } |
190 | |
191 | /// Return true if this is 'metadata'. |
192 | bool isMetadataTy() const { return getTypeID() == MetadataTyID; } |
193 | |
194 | /// Return true if this is 'token'. |
195 | bool isTokenTy() const { return getTypeID() == TokenTyID; } |
196 | |
197 | /// True if this is an instance of IntegerType. |
198 | bool isIntegerTy() const { return getTypeID() == IntegerTyID; } |
199 | |
200 | /// Return true if this is an IntegerType of the given width. |
201 | bool isIntegerTy(unsigned Bitwidth) const; |
202 | |
203 | /// Return true if this is an integer type or a vector of integer types. |
204 | bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); } |
205 | |
206 | /// Return true if this is an integer type or a vector of integer types of |
207 | /// the given width. |
208 | bool isIntOrIntVectorTy(unsigned BitWidth) const { |
209 | return getScalarType()->isIntegerTy(BitWidth); |
210 | } |
211 | |
212 | /// Return true if this is an integer type or a pointer type. |
213 | bool isIntOrPtrTy() const { return isIntegerTy() || isPointerTy(); } |
214 | |
215 | /// True if this is an instance of FunctionType. |
216 | bool isFunctionTy() const { return getTypeID() == FunctionTyID; } |
217 | |
218 | /// True if this is an instance of StructType. |
219 | bool isStructTy() const { return getTypeID() == StructTyID; } |
220 | |
221 | /// True if this is an instance of ArrayType. |
222 | bool isArrayTy() const { return getTypeID() == ArrayTyID; } |
223 | |
224 | /// True if this is an instance of PointerType. |
225 | bool isPointerTy() const { return getTypeID() == PointerTyID; } |
226 | |
227 | /// Return true if this is a pointer type or a vector of pointer types. |
228 | bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); } |
229 | |
230 | /// True if this is an instance of VectorType. |
231 | inline bool isVectorTy() const { |
232 | return getTypeID() == ScalableVectorTyID || getTypeID() == FixedVectorTyID; |
233 | } |
234 | |
235 | /// Return true if this type could be converted with a lossless BitCast to |
236 | /// type 'Ty'. For example, i8* to i32*. BitCasts are valid for types of the |
237 | /// same size only where no re-interpretation of the bits is done. |
238 | /// Determine if this type could be losslessly bitcast to Ty |
239 | bool canLosslesslyBitCastTo(Type *Ty) const; |
240 | |
241 | /// Return true if this type is empty, that is, it has no elements or all of |
242 | /// its elements are empty. |
243 | bool isEmptyTy() const; |
244 | |
245 | /// Return true if the type is "first class", meaning it is a valid type for a |
246 | /// Value. |
247 | bool isFirstClassType() const { |
248 | return getTypeID() != FunctionTyID && getTypeID() != VoidTyID; |
249 | } |
250 | |
251 | /// Return true if the type is a valid type for a register in codegen. This |
252 | /// includes all first-class types except struct and array types. |
253 | bool isSingleValueType() const { |
254 | return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() || |
255 | isPointerTy() || isVectorTy(); |
256 | } |
257 | |
258 | /// Return true if the type is an aggregate type. This means it is valid as |
259 | /// the first operand of an insertvalue or extractvalue instruction. This |
260 | /// includes struct and array types, but does not include vector types. |
261 | bool isAggregateType() const { |
262 | return getTypeID() == StructTyID || getTypeID() == ArrayTyID; |
263 | } |
264 | |
265 | /// Return true if it makes sense to take the size of this type. To get the |
266 | /// actual size for a particular target, it is reasonable to use the |
267 | /// DataLayout subsystem to do this. |
268 | bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const { |
269 | // If it's a primitive, it is always sized. |
270 | if (getTypeID() == IntegerTyID || isFloatingPointTy() || |
271 | getTypeID() == PointerTyID || |
272 | getTypeID() == X86_MMXTyID) |
273 | return true; |
274 | // If it is not something that can have a size (e.g. a function or label), |
275 | // it doesn't have a size. |
276 | if (getTypeID() != StructTyID && getTypeID() != ArrayTyID && !isVectorTy()) |
277 | return false; |
278 | // Otherwise we have to try harder to decide. |
279 | return isSizedDerivedType(Visited); |
280 | } |
281 | |
282 | /// Return the basic size of this type if it is a primitive type. These are |
283 | /// fixed by LLVM and are not target-dependent. |
284 | /// This will return zero if the type does not have a size or is not a |
285 | /// primitive type. |
286 | /// |
287 | /// If this is a scalable vector type, the scalable property will be set and |
288 | /// the runtime size will be a positive integer multiple of the base size. |
289 | /// |
290 | /// Note that this may not reflect the size of memory allocated for an |
291 | /// instance of the type or the number of bytes that are written when an |
292 | /// instance of the type is stored to memory. The DataLayout class provides |
293 | /// additional query functions to provide this information. |
294 | /// |
295 | TypeSize getPrimitiveSizeInBits() const LLVM_READONLY__attribute__((__pure__)); |
296 | |
297 | /// If this is a vector type, return the getPrimitiveSizeInBits value for the |
298 | /// element type. Otherwise return the getPrimitiveSizeInBits value for this |
299 | /// type. |
300 | unsigned getScalarSizeInBits() const LLVM_READONLY__attribute__((__pure__)); |
301 | |
302 | /// Return the width of the mantissa of this type. This is only valid on |
303 | /// floating-point types. If the FP type does not have a stable mantissa (e.g. |
304 | /// ppc long double), this method returns -1. |
305 | int getFPMantissaWidth() const; |
306 | |
307 | /// If this is a vector type, return the element type, otherwise return |
308 | /// 'this'. |
309 | inline Type *getScalarType() const { |
310 | if (isVectorTy()) |
311 | return getContainedType(0); |
312 | return const_cast<Type *>(this); |
313 | } |
314 | |
315 | //===--------------------------------------------------------------------===// |
316 | // Type Iteration support. |
317 | // |
318 | using subtype_iterator = Type * const *; |
319 | |
320 | subtype_iterator subtype_begin() const { return ContainedTys; } |
321 | subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];} |
322 | ArrayRef<Type*> subtypes() const { |
323 | return makeArrayRef(subtype_begin(), subtype_end()); |
324 | } |
325 | |
326 | using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>; |
327 | |
328 | subtype_reverse_iterator subtype_rbegin() const { |
329 | return subtype_reverse_iterator(subtype_end()); |
330 | } |
331 | subtype_reverse_iterator subtype_rend() const { |
332 | return subtype_reverse_iterator(subtype_begin()); |
333 | } |
334 | |
335 | /// This method is used to implement the type iterator (defined at the end of |
336 | /// the file). For derived types, this returns the types 'contained' in the |
337 | /// derived type. |
338 | Type *getContainedType(unsigned i) const { |
339 | assert(i < NumContainedTys && "Index out of range!")((i < NumContainedTys && "Index out of range!") ? static_cast <void> (0) : __assert_fail ("i < NumContainedTys && \"Index out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 339, __PRETTY_FUNCTION__)); |
340 | return ContainedTys[i]; |
341 | } |
342 | |
343 | /// Return the number of types in the derived type. |
344 | unsigned getNumContainedTypes() const { return NumContainedTys; } |
345 | |
346 | //===--------------------------------------------------------------------===// |
347 | // Helper methods corresponding to subclass methods. This forces a cast to |
348 | // the specified subclass and calls its accessor. "getArrayNumElements" (for |
349 | // example) is shorthand for cast<ArrayType>(Ty)->getNumElements(). This is |
350 | // only intended to cover the core methods that are frequently used, helper |
351 | // methods should not be added here. |
352 | |
353 | inline unsigned getIntegerBitWidth() const; |
354 | |
355 | inline Type *getFunctionParamType(unsigned i) const; |
356 | inline unsigned getFunctionNumParams() const; |
357 | inline bool isFunctionVarArg() const; |
358 | |
359 | inline StringRef getStructName() const; |
360 | inline unsigned getStructNumElements() const; |
361 | inline Type *getStructElementType(unsigned N) const; |
362 | |
363 | inline uint64_t getArrayNumElements() const; |
364 | |
365 | Type *getArrayElementType() const { |
366 | assert(getTypeID() == ArrayTyID)((getTypeID() == ArrayTyID) ? static_cast<void> (0) : __assert_fail ("getTypeID() == ArrayTyID", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 366, __PRETTY_FUNCTION__)); |
367 | return ContainedTys[0]; |
368 | } |
369 | |
370 | Type *getPointerElementType() const { |
371 | assert(getTypeID() == PointerTyID)((getTypeID() == PointerTyID) ? static_cast<void> (0) : __assert_fail ("getTypeID() == PointerTyID", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 371, __PRETTY_FUNCTION__)); |
372 | return ContainedTys[0]; |
373 | } |
374 | |
375 | /// Given an integer or vector type, change the lane bitwidth to NewBitwidth, |
376 | /// whilst keeping the old number of lanes. |
377 | inline Type *getWithNewBitWidth(unsigned NewBitWidth) const; |
378 | |
379 | /// Given scalar/vector integer type, returns a type with elements twice as |
380 | /// wide as in the original type. For vectors, preserves element count. |
381 | inline Type *getExtendedType() const; |
382 | |
383 | /// Get the address space of this pointer or pointer vector type. |
384 | inline unsigned getPointerAddressSpace() const; |
385 | |
386 | //===--------------------------------------------------------------------===// |
387 | // Static members exported by the Type class itself. Useful for getting |
388 | // instances of Type. |
389 | // |
390 | |
391 | /// Return a type based on an identifier. |
392 | static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber); |
393 | |
394 | //===--------------------------------------------------------------------===// |
395 | // These are the builtin types that are always available. |
396 | // |
397 | static Type *getVoidTy(LLVMContext &C); |
398 | static Type *getLabelTy(LLVMContext &C); |
399 | static Type *getHalfTy(LLVMContext &C); |
400 | static Type *getBFloatTy(LLVMContext &C); |
401 | static Type *getFloatTy(LLVMContext &C); |
402 | static Type *getDoubleTy(LLVMContext &C); |
403 | static Type *getMetadataTy(LLVMContext &C); |
404 | static Type *getX86_FP80Ty(LLVMContext &C); |
405 | static Type *getFP128Ty(LLVMContext &C); |
406 | static Type *getPPC_FP128Ty(LLVMContext &C); |
407 | static Type *getX86_MMXTy(LLVMContext &C); |
408 | static Type *getTokenTy(LLVMContext &C); |
409 | static IntegerType *getIntNTy(LLVMContext &C, unsigned N); |
410 | static IntegerType *getInt1Ty(LLVMContext &C); |
411 | static IntegerType *getInt8Ty(LLVMContext &C); |
412 | static IntegerType *getInt16Ty(LLVMContext &C); |
413 | static IntegerType *getInt32Ty(LLVMContext &C); |
414 | static IntegerType *getInt64Ty(LLVMContext &C); |
415 | static IntegerType *getInt128Ty(LLVMContext &C); |
416 | template <typename ScalarTy> static Type *getScalarTy(LLVMContext &C) { |
417 | int noOfBits = sizeof(ScalarTy) * CHAR_BIT8; |
418 | if (std::is_integral<ScalarTy>::value) { |
419 | return (Type*) Type::getIntNTy(C, noOfBits); |
420 | } else if (std::is_floating_point<ScalarTy>::value) { |
421 | switch (noOfBits) { |
422 | case 32: |
423 | return Type::getFloatTy(C); |
424 | case 64: |
425 | return Type::getDoubleTy(C); |
426 | } |
427 | } |
428 | llvm_unreachable("Unsupported type in Type::getScalarTy")::llvm::llvm_unreachable_internal("Unsupported type in Type::getScalarTy" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 428); |
429 | } |
430 | |
431 | //===--------------------------------------------------------------------===// |
432 | // Convenience methods for getting pointer types with one of the above builtin |
433 | // types as pointee. |
434 | // |
435 | static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0); |
436 | static PointerType *getBFloatPtrTy(LLVMContext &C, unsigned AS = 0); |
437 | static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0); |
438 | static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0); |
439 | static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0); |
440 | static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0); |
441 | static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0); |
442 | static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0); |
443 | static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0); |
444 | static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0); |
445 | static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0); |
446 | static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0); |
447 | static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0); |
448 | static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0); |
449 | |
450 | /// Return a pointer to the current type. This is equivalent to |
451 | /// PointerType::get(Foo, AddrSpace). |
452 | PointerType *getPointerTo(unsigned AddrSpace = 0) const; |
453 | |
454 | private: |
455 | /// Derived types like structures and arrays are sized iff all of the members |
456 | /// of the type are sized as well. Since asking for their size is relatively |
457 | /// uncommon, move this operation out-of-line. |
458 | bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const; |
459 | }; |
460 | |
461 | // Printing of types. |
462 | inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) { |
463 | T.print(OS); |
464 | return OS; |
465 | } |
466 | |
467 | // allow isa<PointerType>(x) to work without DerivedTypes.h included. |
468 | template <> struct isa_impl<PointerType, Type> { |
469 | static inline bool doit(const Type &Ty) { |
470 | return Ty.getTypeID() == Type::PointerTyID; |
471 | } |
472 | }; |
473 | |
474 | // Create wrappers for C Binding types (see CBindingWrapping.h). |
475 | DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)inline Type *unwrap(LLVMTypeRef P) { return reinterpret_cast< Type*>(P); } inline LLVMTypeRef wrap(const Type *P) { return reinterpret_cast<LLVMTypeRef>(const_cast<Type*>( P)); } template<typename T> inline T *unwrap(LLVMTypeRef P) { return cast<T>(unwrap(P)); } |
476 | |
477 | /* Specialized opaque type conversions. |
478 | */ |
479 | inline Type **unwrap(LLVMTypeRef* Tys) { |
480 | return reinterpret_cast<Type**>(Tys); |
481 | } |
482 | |
483 | inline LLVMTypeRef *wrap(Type **Tys) { |
484 | return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys)); |
485 | } |
486 | |
487 | } // end namespace llvm |
488 | |
489 | #endif // LLVM_IR_TYPE_H |
1 | //===- Optional.h - Simple variant for passing optional values --*- C++ -*-===// |
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 provides Optional, a template class modeled in the spirit of |
10 | // OCaml's 'opt' variant. The idea is to strongly type whether or not |
11 | // a value can be optional. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_ADT_OPTIONAL_H |
16 | #define LLVM_ADT_OPTIONAL_H |
17 | |
18 | #include "llvm/ADT/None.h" |
19 | #include "llvm/Support/Compiler.h" |
20 | #include "llvm/Support/type_traits.h" |
21 | #include <cassert> |
22 | #include <memory> |
23 | #include <new> |
24 | #include <utility> |
25 | |
26 | namespace llvm { |
27 | |
28 | class raw_ostream; |
29 | |
30 | namespace optional_detail { |
31 | |
32 | struct in_place_t {}; |
33 | |
34 | /// Storage for any type. |
35 | template <typename T, bool = is_trivially_copyable<T>::value> |
36 | class OptionalStorage { |
37 | union { |
38 | char empty; |
39 | T value; |
40 | }; |
41 | bool hasVal; |
42 | |
43 | public: |
44 | ~OptionalStorage() { reset(); } |
45 | |
46 | constexpr OptionalStorage() noexcept : empty(), hasVal(false) {} |
47 | |
48 | constexpr OptionalStorage(OptionalStorage const &other) : OptionalStorage() { |
49 | if (other.hasValue()) { |
50 | emplace(other.value); |
51 | } |
52 | } |
53 | constexpr OptionalStorage(OptionalStorage &&other) : OptionalStorage() { |
54 | if (other.hasValue()) { |
55 | emplace(std::move(other.value)); |
56 | } |
57 | } |
58 | |
59 | template <class... Args> |
60 | constexpr explicit OptionalStorage(in_place_t, Args &&... args) |
61 | : value(std::forward<Args>(args)...), hasVal(true) {} |
62 | |
63 | void reset() noexcept { |
64 | if (hasVal) { |
65 | value.~T(); |
66 | hasVal = false; |
67 | } |
68 | } |
69 | |
70 | constexpr bool hasValue() const noexcept { return hasVal; } |
71 | |
72 | T &getValue() LLVM_LVALUE_FUNCTION& noexcept { |
73 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 73, __PRETTY_FUNCTION__)); |
74 | return value; |
75 | } |
76 | constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept { |
77 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 77, __PRETTY_FUNCTION__)); |
78 | return value; |
79 | } |
80 | #if LLVM_HAS_RVALUE_REFERENCE_THIS1 |
81 | T &&getValue() && noexcept { |
82 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 82, __PRETTY_FUNCTION__)); |
83 | return std::move(value); |
84 | } |
85 | #endif |
86 | |
87 | template <class... Args> void emplace(Args &&... args) { |
88 | reset(); |
89 | ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...); |
90 | hasVal = true; |
91 | } |
92 | |
93 | OptionalStorage &operator=(T const &y) { |
94 | if (hasValue()) { |
95 | value = y; |
96 | } else { |
97 | ::new ((void *)std::addressof(value)) T(y); |
98 | hasVal = true; |
99 | } |
100 | return *this; |
101 | } |
102 | OptionalStorage &operator=(T &&y) { |
103 | if (hasValue()) { |
104 | value = std::move(y); |
105 | } else { |
106 | ::new ((void *)std::addressof(value)) T(std::move(y)); |
107 | hasVal = true; |
108 | } |
109 | return *this; |
110 | } |
111 | |
112 | OptionalStorage &operator=(OptionalStorage const &other) { |
113 | if (other.hasValue()) { |
114 | if (hasValue()) { |
115 | value = other.value; |
116 | } else { |
117 | ::new ((void *)std::addressof(value)) T(other.value); |
118 | hasVal = true; |
119 | } |
120 | } else { |
121 | reset(); |
122 | } |
123 | return *this; |
124 | } |
125 | |
126 | OptionalStorage &operator=(OptionalStorage &&other) { |
127 | if (other.hasValue()) { |
128 | if (hasValue()) { |
129 | value = std::move(other.value); |
130 | } else { |
131 | ::new ((void *)std::addressof(value)) T(std::move(other.value)); |
132 | hasVal = true; |
133 | } |
134 | } else { |
135 | reset(); |
136 | } |
137 | return *this; |
138 | } |
139 | }; |
140 | |
141 | template <typename T> class OptionalStorage<T, true> { |
142 | union { |
143 | char empty; |
144 | T value; |
145 | }; |
146 | bool hasVal = false; |
147 | |
148 | public: |
149 | ~OptionalStorage() = default; |
150 | |
151 | constexpr OptionalStorage() noexcept : empty{} {} |
152 | |
153 | constexpr OptionalStorage(OptionalStorage const &other) = default; |
154 | constexpr OptionalStorage(OptionalStorage &&other) = default; |
155 | |
156 | OptionalStorage &operator=(OptionalStorage const &other) = default; |
157 | OptionalStorage &operator=(OptionalStorage &&other) = default; |
158 | |
159 | template <class... Args> |
160 | constexpr explicit OptionalStorage(in_place_t, Args &&... args) |
161 | : value(std::forward<Args>(args)...), hasVal(true) {} |
162 | |
163 | void reset() noexcept { |
164 | if (hasVal) { |
165 | value.~T(); |
166 | hasVal = false; |
167 | } |
168 | } |
169 | |
170 | constexpr bool hasValue() const noexcept { return hasVal; } |
171 | |
172 | T &getValue() LLVM_LVALUE_FUNCTION& noexcept { |
173 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 173, __PRETTY_FUNCTION__)); |
174 | return value; |
175 | } |
176 | constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept { |
177 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 177, __PRETTY_FUNCTION__)); |
178 | return value; |
179 | } |
180 | #if LLVM_HAS_RVALUE_REFERENCE_THIS1 |
181 | T &&getValue() && noexcept { |
182 | assert(hasVal)((hasVal) ? static_cast<void> (0) : __assert_fail ("hasVal" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/Optional.h" , 182, __PRETTY_FUNCTION__)); |
183 | return std::move(value); |
184 | } |
185 | #endif |
186 | |
187 | template <class... Args> void emplace(Args &&... args) { |
188 | reset(); |
189 | ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...); |
190 | hasVal = true; |
191 | } |
192 | |
193 | OptionalStorage &operator=(T const &y) { |
194 | if (hasValue()) { |
195 | value = y; |
196 | } else { |
197 | ::new ((void *)std::addressof(value)) T(y); |
198 | hasVal = true; |
199 | } |
200 | return *this; |
201 | } |
202 | OptionalStorage &operator=(T &&y) { |
203 | if (hasValue()) { |
204 | value = std::move(y); |
205 | } else { |
206 | ::new ((void *)std::addressof(value)) T(std::move(y)); |
207 | hasVal = true; |
208 | } |
209 | return *this; |
210 | } |
211 | }; |
212 | |
213 | } // namespace optional_detail |
214 | |
215 | template <typename T> class Optional { |
216 | optional_detail::OptionalStorage<T> Storage; |
217 | |
218 | public: |
219 | using value_type = T; |
220 | |
221 | constexpr Optional() {} |
222 | constexpr Optional(NoneType) {} |
223 | |
224 | constexpr Optional(const T &y) : Storage(optional_detail::in_place_t{}, y) {} |
225 | constexpr Optional(const Optional &O) = default; |
226 | |
227 | constexpr Optional(T &&y) |
228 | : Storage(optional_detail::in_place_t{}, std::move(y)) {} |
229 | constexpr Optional(Optional &&O) = default; |
230 | |
231 | Optional &operator=(T &&y) { |
232 | Storage = std::move(y); |
233 | return *this; |
234 | } |
235 | Optional &operator=(Optional &&O) = default; |
236 | |
237 | /// Create a new object by constructing it in place with the given arguments. |
238 | template <typename... ArgTypes> void emplace(ArgTypes &&... Args) { |
239 | Storage.emplace(std::forward<ArgTypes>(Args)...); |
240 | } |
241 | |
242 | static constexpr Optional create(const T *y) { |
243 | return y ? Optional(*y) : Optional(); |
244 | } |
245 | |
246 | Optional &operator=(const T &y) { |
247 | Storage = y; |
248 | return *this; |
249 | } |
250 | Optional &operator=(const Optional &O) = default; |
251 | |
252 | void reset() { Storage.reset(); } |
253 | |
254 | constexpr const T *getPointer() const { return &Storage.getValue(); } |
255 | T *getPointer() { return &Storage.getValue(); } |
256 | constexpr const T &getValue() const LLVM_LVALUE_FUNCTION& { |
257 | return Storage.getValue(); |
258 | } |
259 | T &getValue() LLVM_LVALUE_FUNCTION& { return Storage.getValue(); } |
260 | |
261 | constexpr explicit operator bool() const { return hasValue(); } |
262 | constexpr bool hasValue() const { return Storage.hasValue(); } |
263 | constexpr const T *operator->() const { return getPointer(); } |
264 | T *operator->() { return getPointer(); } |
265 | constexpr const T &operator*() const LLVM_LVALUE_FUNCTION& { |
266 | return getValue(); |
267 | } |
268 | T &operator*() LLVM_LVALUE_FUNCTION& { return getValue(); } |
269 | |
270 | template <typename U> |
271 | constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION& { |
272 | return hasValue() ? getValue() : std::forward<U>(value); |
273 | } |
274 | |
275 | /// Apply a function to the value if present; otherwise return None. |
276 | template <class Function> |
277 | auto map(const Function &F) const LLVM_LVALUE_FUNCTION& |
278 | -> Optional<decltype(F(getValue()))> { |
279 | if (*this) return F(getValue()); |
280 | return None; |
281 | } |
282 | |
283 | #if LLVM_HAS_RVALUE_REFERENCE_THIS1 |
284 | T &&getValue() && { return std::move(Storage.getValue()); } |
285 | T &&operator*() && { return std::move(Storage.getValue()); } |
286 | |
287 | template <typename U> |
288 | T getValueOr(U &&value) && { |
289 | return hasValue() ? std::move(getValue()) : std::forward<U>(value); |
290 | } |
291 | |
292 | /// Apply a function to the value if present; otherwise return None. |
293 | template <class Function> |
294 | auto map(const Function &F) && |
295 | -> Optional<decltype(F(std::move(*this).getValue()))> { |
296 | if (*this) return F(std::move(*this).getValue()); |
297 | return None; |
298 | } |
299 | #endif |
300 | }; |
301 | |
302 | template <typename T, typename U> |
303 | constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) { |
304 | if (X && Y) |
305 | return *X == *Y; |
306 | return X.hasValue() == Y.hasValue(); |
307 | } |
308 | |
309 | template <typename T, typename U> |
310 | constexpr bool operator!=(const Optional<T> &X, const Optional<U> &Y) { |
311 | return !(X == Y); |
312 | } |
313 | |
314 | template <typename T, typename U> |
315 | constexpr bool operator<(const Optional<T> &X, const Optional<U> &Y) { |
316 | if (X && Y) |
317 | return *X < *Y; |
318 | return X.hasValue() < Y.hasValue(); |
319 | } |
320 | |
321 | template <typename T, typename U> |
322 | constexpr bool operator<=(const Optional<T> &X, const Optional<U> &Y) { |
323 | return !(Y < X); |
324 | } |
325 | |
326 | template <typename T, typename U> |
327 | constexpr bool operator>(const Optional<T> &X, const Optional<U> &Y) { |
328 | return Y < X; |
329 | } |
330 | |
331 | template <typename T, typename U> |
332 | constexpr bool operator>=(const Optional<T> &X, const Optional<U> &Y) { |
333 | return !(X < Y); |
334 | } |
335 | |
336 | template <typename T> |
337 | constexpr bool operator==(const Optional<T> &X, NoneType) { |
338 | return !X; |
339 | } |
340 | |
341 | template <typename T> |
342 | constexpr bool operator==(NoneType, const Optional<T> &X) { |
343 | return X == None; |
344 | } |
345 | |
346 | template <typename T> |
347 | constexpr bool operator!=(const Optional<T> &X, NoneType) { |
348 | return !(X == None); |
349 | } |
350 | |
351 | template <typename T> |
352 | constexpr bool operator!=(NoneType, const Optional<T> &X) { |
353 | return X != None; |
354 | } |
355 | |
356 | template <typename T> constexpr bool operator<(const Optional<T> &X, NoneType) { |
357 | return false; |
358 | } |
359 | |
360 | template <typename T> constexpr bool operator<(NoneType, const Optional<T> &X) { |
361 | return X.hasValue(); |
362 | } |
363 | |
364 | template <typename T> |
365 | constexpr bool operator<=(const Optional<T> &X, NoneType) { |
366 | return !(None < X); |
367 | } |
368 | |
369 | template <typename T> |
370 | constexpr bool operator<=(NoneType, const Optional<T> &X) { |
371 | return !(X < None); |
372 | } |
373 | |
374 | template <typename T> constexpr bool operator>(const Optional<T> &X, NoneType) { |
375 | return None < X; |
376 | } |
377 | |
378 | template <typename T> constexpr bool operator>(NoneType, const Optional<T> &X) { |
379 | return X < None; |
380 | } |
381 | |
382 | template <typename T> |
383 | constexpr bool operator>=(const Optional<T> &X, NoneType) { |
384 | return None <= X; |
385 | } |
386 | |
387 | template <typename T> |
388 | constexpr bool operator>=(NoneType, const Optional<T> &X) { |
389 | return X <= None; |
390 | } |
391 | |
392 | template <typename T> |
393 | constexpr bool operator==(const Optional<T> &X, const T &Y) { |
394 | return X && *X == Y; |
395 | } |
396 | |
397 | template <typename T> |
398 | constexpr bool operator==(const T &X, const Optional<T> &Y) { |
399 | return Y && X == *Y; |
400 | } |
401 | |
402 | template <typename T> |
403 | constexpr bool operator!=(const Optional<T> &X, const T &Y) { |
404 | return !(X == Y); |
405 | } |
406 | |
407 | template <typename T> |
408 | constexpr bool operator!=(const T &X, const Optional<T> &Y) { |
409 | return !(X == Y); |
410 | } |
411 | |
412 | template <typename T> |
413 | constexpr bool operator<(const Optional<T> &X, const T &Y) { |
414 | return !X || *X < Y; |
415 | } |
416 | |
417 | template <typename T> |
418 | constexpr bool operator<(const T &X, const Optional<T> &Y) { |
419 | return Y && X < *Y; |
420 | } |
421 | |
422 | template <typename T> |
423 | constexpr bool operator<=(const Optional<T> &X, const T &Y) { |
424 | return !(Y < X); |
425 | } |
426 | |
427 | template <typename T> |
428 | constexpr bool operator<=(const T &X, const Optional<T> &Y) { |
429 | return !(Y < X); |
430 | } |
431 | |
432 | template <typename T> |
433 | constexpr bool operator>(const Optional<T> &X, const T &Y) { |
434 | return Y < X; |
435 | } |
436 | |
437 | template <typename T> |
438 | constexpr bool operator>(const T &X, const Optional<T> &Y) { |
439 | return Y < X; |
440 | } |
441 | |
442 | template <typename T> |
443 | constexpr bool operator>=(const Optional<T> &X, const T &Y) { |
444 | return !(X < Y); |
445 | } |
446 | |
447 | template <typename T> |
448 | constexpr bool operator>=(const T &X, const Optional<T> &Y) { |
449 | return !(X < Y); |
450 | } |
451 | |
452 | raw_ostream &operator<<(raw_ostream &OS, NoneType); |
453 | |
454 | template <typename T, typename = decltype(std::declval<raw_ostream &>() |
455 | << std::declval<const T &>())> |
456 | raw_ostream &operator<<(raw_ostream &OS, const Optional<T> &O) { |
457 | if (O) |
458 | OS << *O; |
459 | else |
460 | OS << None; |
461 | return OS; |
462 | } |
463 | |
464 | } // end namespace llvm |
465 | |
466 | #endif // LLVM_ADT_OPTIONAL_H |
1 | //===-- llvm/Constants.h - Constant class subclass definitions --*- C++ -*-===// |
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 | /// @file |
10 | /// This file contains the declarations for the subclasses of Constant, |
11 | /// which represent the different flavors of constant values that live in LLVM. |
12 | /// Note that Constants are immutable (once created they never change) and are |
13 | /// fully shared by structural equivalence. This means that two structurally |
14 | /// equivalent constants will always have the same address. Constants are |
15 | /// created on demand as needed and never deleted: thus clients don't have to |
16 | /// worry about the lifetime of the objects. |
17 | // |
18 | //===----------------------------------------------------------------------===// |
19 | |
20 | #ifndef LLVM_IR_CONSTANTS_H |
21 | #define LLVM_IR_CONSTANTS_H |
22 | |
23 | #include "llvm/ADT/APFloat.h" |
24 | #include "llvm/ADT/APInt.h" |
25 | #include "llvm/ADT/ArrayRef.h" |
26 | #include "llvm/ADT/None.h" |
27 | #include "llvm/ADT/Optional.h" |
28 | #include "llvm/ADT/STLExtras.h" |
29 | #include "llvm/ADT/StringRef.h" |
30 | #include "llvm/IR/Constant.h" |
31 | #include "llvm/IR/DerivedTypes.h" |
32 | #include "llvm/IR/OperandTraits.h" |
33 | #include "llvm/IR/User.h" |
34 | #include "llvm/IR/Value.h" |
35 | #include "llvm/Support/Casting.h" |
36 | #include "llvm/Support/Compiler.h" |
37 | #include "llvm/Support/ErrorHandling.h" |
38 | #include <cassert> |
39 | #include <cstddef> |
40 | #include <cstdint> |
41 | |
42 | namespace llvm { |
43 | |
44 | template <class ConstantClass> struct ConstantAggrKeyType; |
45 | |
46 | /// Base class for constants with no operands. |
47 | /// |
48 | /// These constants have no operands; they represent their data directly. |
49 | /// Since they can be in use by unrelated modules (and are never based on |
50 | /// GlobalValues), it never makes sense to RAUW them. |
51 | class ConstantData : public Constant { |
52 | friend class Constant; |
53 | |
54 | Value *handleOperandChangeImpl(Value *From, Value *To) { |
55 | llvm_unreachable("Constant data does not have operands!")::llvm::llvm_unreachable_internal("Constant data does not have operands!" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 55); |
56 | } |
57 | |
58 | protected: |
59 | explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {} |
60 | |
61 | void *operator new(size_t s) { return User::operator new(s, 0); } |
62 | |
63 | public: |
64 | ConstantData(const ConstantData &) = delete; |
65 | |
66 | /// Methods to support type inquiry through isa, cast, and dyn_cast. |
67 | static bool classof(const Value *V) { |
68 | return V->getValueID() >= ConstantDataFirstVal && |
69 | V->getValueID() <= ConstantDataLastVal; |
70 | } |
71 | }; |
72 | |
73 | //===----------------------------------------------------------------------===// |
74 | /// This is the shared class of boolean and integer constants. This class |
75 | /// represents both boolean and integral constants. |
76 | /// Class for constant integers. |
77 | class ConstantInt final : public ConstantData { |
78 | friend class Constant; |
79 | |
80 | APInt Val; |
81 | |
82 | ConstantInt(IntegerType *Ty, const APInt& V); |
83 | |
84 | void destroyConstantImpl(); |
85 | |
86 | public: |
87 | ConstantInt(const ConstantInt &) = delete; |
88 | |
89 | static ConstantInt *getTrue(LLVMContext &Context); |
90 | static ConstantInt *getFalse(LLVMContext &Context); |
91 | static Constant *getTrue(Type *Ty); |
92 | static Constant *getFalse(Type *Ty); |
93 | |
94 | /// If Ty is a vector type, return a Constant with a splat of the given |
95 | /// value. Otherwise return a ConstantInt for the given value. |
96 | static Constant *get(Type *Ty, uint64_t V, bool isSigned = false); |
97 | |
98 | /// Return a ConstantInt with the specified integer value for the specified |
99 | /// type. If the type is wider than 64 bits, the value will be zero-extended |
100 | /// to fit the type, unless isSigned is true, in which case the value will |
101 | /// be interpreted as a 64-bit signed integer and sign-extended to fit |
102 | /// the type. |
103 | /// Get a ConstantInt for a specific value. |
104 | static ConstantInt *get(IntegerType *Ty, uint64_t V, |
105 | bool isSigned = false); |
106 | |
107 | /// Return a ConstantInt with the specified value for the specified type. The |
108 | /// value V will be canonicalized to a an unsigned APInt. Accessing it with |
109 | /// either getSExtValue() or getZExtValue() will yield a correctly sized and |
110 | /// signed value for the type Ty. |
111 | /// Get a ConstantInt for a specific signed value. |
112 | static ConstantInt *getSigned(IntegerType *Ty, int64_t V); |
113 | static Constant *getSigned(Type *Ty, int64_t V); |
114 | |
115 | /// Return a ConstantInt with the specified value and an implied Type. The |
116 | /// type is the integer type that corresponds to the bit width of the value. |
117 | static ConstantInt *get(LLVMContext &Context, const APInt &V); |
118 | |
119 | /// Return a ConstantInt constructed from the string strStart with the given |
120 | /// radix. |
121 | static ConstantInt *get(IntegerType *Ty, StringRef Str, |
122 | uint8_t radix); |
123 | |
124 | /// If Ty is a vector type, return a Constant with a splat of the given |
125 | /// value. Otherwise return a ConstantInt for the given value. |
126 | static Constant *get(Type* Ty, const APInt& V); |
127 | |
128 | /// Return the constant as an APInt value reference. This allows clients to |
129 | /// obtain a full-precision copy of the value. |
130 | /// Return the constant's value. |
131 | inline const APInt &getValue() const { |
132 | return Val; |
133 | } |
134 | |
135 | /// getBitWidth - Return the bitwidth of this constant. |
136 | unsigned getBitWidth() const { return Val.getBitWidth(); } |
137 | |
138 | /// Return the constant as a 64-bit unsigned integer value after it |
139 | /// has been zero extended as appropriate for the type of this constant. Note |
140 | /// that this method can assert if the value does not fit in 64 bits. |
141 | /// Return the zero extended value. |
142 | inline uint64_t getZExtValue() const { |
143 | return Val.getZExtValue(); |
144 | } |
145 | |
146 | /// Return the constant as a 64-bit integer value after it has been sign |
147 | /// extended as appropriate for the type of this constant. Note that |
148 | /// this method can assert if the value does not fit in 64 bits. |
149 | /// Return the sign extended value. |
150 | inline int64_t getSExtValue() const { |
151 | return Val.getSExtValue(); |
152 | } |
153 | |
154 | /// Return the constant as an llvm::MaybeAlign. |
155 | /// Note that this method can assert if the value does not fit in 64 bits or |
156 | /// is not a power of two. |
157 | inline MaybeAlign getMaybeAlignValue() const { |
158 | return MaybeAlign(getZExtValue()); |
159 | } |
160 | |
161 | /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`. |
162 | /// Note that this method can assert if the value does not fit in 64 bits or |
163 | /// is not a power of two. |
164 | inline Align getAlignValue() const { |
165 | return getMaybeAlignValue().valueOrOne(); |
166 | } |
167 | |
168 | /// A helper method that can be used to determine if the constant contained |
169 | /// within is equal to a constant. This only works for very small values, |
170 | /// because this is all that can be represented with all types. |
171 | /// Determine if this constant's value is same as an unsigned char. |
172 | bool equalsInt(uint64_t V) const { |
173 | return Val == V; |
174 | } |
175 | |
176 | /// getType - Specialize the getType() method to always return an IntegerType, |
177 | /// which reduces the amount of casting needed in parts of the compiler. |
178 | /// |
179 | inline IntegerType *getType() const { |
180 | return cast<IntegerType>(Value::getType()); |
181 | } |
182 | |
183 | /// This static method returns true if the type Ty is big enough to |
184 | /// represent the value V. This can be used to avoid having the get method |
185 | /// assert when V is larger than Ty can represent. Note that there are two |
186 | /// versions of this method, one for unsigned and one for signed integers. |
187 | /// Although ConstantInt canonicalizes everything to an unsigned integer, |
188 | /// the signed version avoids callers having to convert a signed quantity |
189 | /// to the appropriate unsigned type before calling the method. |
190 | /// @returns true if V is a valid value for type Ty |
191 | /// Determine if the value is in range for the given type. |
192 | static bool isValueValidForType(Type *Ty, uint64_t V); |
193 | static bool isValueValidForType(Type *Ty, int64_t V); |
194 | |
195 | bool isNegative() const { return Val.isNegative(); } |
196 | |
197 | /// This is just a convenience method to make client code smaller for a |
198 | /// common code. It also correctly performs the comparison without the |
199 | /// potential for an assertion from getZExtValue(). |
200 | bool isZero() const { |
201 | return Val.isNullValue(); |
202 | } |
203 | |
204 | /// This is just a convenience method to make client code smaller for a |
205 | /// common case. It also correctly performs the comparison without the |
206 | /// potential for an assertion from getZExtValue(). |
207 | /// Determine if the value is one. |
208 | bool isOne() const { |
209 | return Val.isOneValue(); |
210 | } |
211 | |
212 | /// This function will return true iff every bit in this constant is set |
213 | /// to true. |
214 | /// @returns true iff this constant's bits are all set to true. |
215 | /// Determine if the value is all ones. |
216 | bool isMinusOne() const { |
217 | return Val.isAllOnesValue(); |
218 | } |
219 | |
220 | /// This function will return true iff this constant represents the largest |
221 | /// value that may be represented by the constant's type. |
222 | /// @returns true iff this is the largest value that may be represented |
223 | /// by this type. |
224 | /// Determine if the value is maximal. |
225 | bool isMaxValue(bool isSigned) const { |
226 | if (isSigned) |
227 | return Val.isMaxSignedValue(); |
228 | else |
229 | return Val.isMaxValue(); |
230 | } |
231 | |
232 | /// This function will return true iff this constant represents the smallest |
233 | /// value that may be represented by this constant's type. |
234 | /// @returns true if this is the smallest value that may be represented by |
235 | /// this type. |
236 | /// Determine if the value is minimal. |
237 | bool isMinValue(bool isSigned) const { |
238 | if (isSigned) |
239 | return Val.isMinSignedValue(); |
240 | else |
241 | return Val.isMinValue(); |
242 | } |
243 | |
244 | /// This function will return true iff this constant represents a value with |
245 | /// active bits bigger than 64 bits or a value greater than the given uint64_t |
246 | /// value. |
247 | /// @returns true iff this constant is greater or equal to the given number. |
248 | /// Determine if the value is greater or equal to the given number. |
249 | bool uge(uint64_t Num) const { |
250 | return Val.uge(Num); |
251 | } |
252 | |
253 | /// getLimitedValue - If the value is smaller than the specified limit, |
254 | /// return it, otherwise return the limit value. This causes the value |
255 | /// to saturate to the limit. |
256 | /// @returns the min of the value of the constant and the specified value |
257 | /// Get the constant's value with a saturation limit |
258 | uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const { |
259 | return Val.getLimitedValue(Limit); |
260 | } |
261 | |
262 | /// Methods to support type inquiry through isa, cast, and dyn_cast. |
263 | static bool classof(const Value *V) { |
264 | return V->getValueID() == ConstantIntVal; |
265 | } |
266 | }; |
267 | |
268 | //===----------------------------------------------------------------------===// |
269 | /// ConstantFP - Floating Point Values [float, double] |
270 | /// |
271 | class ConstantFP final : public ConstantData { |
272 | friend class Constant; |
273 | |
274 | APFloat Val; |
275 | |
276 | ConstantFP(Type *Ty, const APFloat& V); |
277 | |
278 | void destroyConstantImpl(); |
279 | |
280 | public: |
281 | ConstantFP(const ConstantFP &) = delete; |
282 | |
283 | /// Floating point negation must be implemented with f(x) = -0.0 - x. This |
284 | /// method returns the negative zero constant for floating point or vector |
285 | /// floating point types; for all other types, it returns the null value. |
286 | static Constant *getZeroValueForNegation(Type *Ty); |
287 | |
288 | /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP, |
289 | /// for the specified value in the specified type. This should only be used |
290 | /// for simple constant values like 2.0/1.0 etc, that are known-valid both as |
291 | /// host double and as the target format. |
292 | static Constant *get(Type* Ty, double V); |
293 | |
294 | /// If Ty is a vector type, return a Constant with a splat of the given |
295 | /// value. Otherwise return a ConstantFP for the given value. |
296 | static Constant *get(Type *Ty, const APFloat &V); |
297 | |
298 | static Constant *get(Type* Ty, StringRef Str); |
299 | static ConstantFP *get(LLVMContext &Context, const APFloat &V); |
300 | static Constant *getNaN(Type *Ty, bool Negative = false, uint64_t Payload = 0); |
301 | static Constant *getQNaN(Type *Ty, bool Negative = false, |
302 | APInt *Payload = nullptr); |
303 | static Constant *getSNaN(Type *Ty, bool Negative = false, |
304 | APInt *Payload = nullptr); |
305 | static Constant *getNegativeZero(Type *Ty); |
306 | static Constant *getInfinity(Type *Ty, bool Negative = false); |
307 | |
308 | /// Return true if Ty is big enough to represent V. |
309 | static bool isValueValidForType(Type *Ty, const APFloat &V); |
310 | inline const APFloat &getValueAPF() const { return Val; } |
311 | inline const APFloat &getValue() const { return Val; } |
312 | |
313 | /// Return true if the value is positive or negative zero. |
314 | bool isZero() const { return Val.isZero(); } |
315 | |
316 | /// Return true if the sign bit is set. |
317 | bool isNegative() const { return Val.isNegative(); } |
318 | |
319 | /// Return true if the value is infinity |
320 | bool isInfinity() const { return Val.isInfinity(); } |
321 | |
322 | /// Return true if the value is a NaN. |
323 | bool isNaN() const { return Val.isNaN(); } |
324 | |
325 | /// We don't rely on operator== working on double values, as it returns true |
326 | /// for things that are clearly not equal, like -0.0 and 0.0. |
327 | /// As such, this method can be used to do an exact bit-for-bit comparison of |
328 | /// two floating point values. The version with a double operand is retained |
329 | /// because it's so convenient to write isExactlyValue(2.0), but please use |
330 | /// it only for simple constants. |
331 | bool isExactlyValue(const APFloat &V) const; |
332 | |
333 | bool isExactlyValue(double V) const { |
334 | bool ignored; |
335 | APFloat FV(V); |
336 | FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored); |
337 | return isExactlyValue(FV); |
338 | } |
339 | |
340 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
341 | static bool classof(const Value *V) { |
342 | return V->getValueID() == ConstantFPVal; |
343 | } |
344 | }; |
345 | |
346 | //===----------------------------------------------------------------------===// |
347 | /// All zero aggregate value |
348 | /// |
349 | class ConstantAggregateZero final : public ConstantData { |
350 | friend class Constant; |
351 | |
352 | explicit ConstantAggregateZero(Type *Ty) |
353 | : ConstantData(Ty, ConstantAggregateZeroVal) {} |
354 | |
355 | void destroyConstantImpl(); |
356 | |
357 | public: |
358 | ConstantAggregateZero(const ConstantAggregateZero &) = delete; |
359 | |
360 | static ConstantAggregateZero *get(Type *Ty); |
361 | |
362 | /// If this CAZ has array or vector type, return a zero with the right element |
363 | /// type. |
364 | Constant *getSequentialElement() const; |
365 | |
366 | /// If this CAZ has struct type, return a zero with the right element type for |
367 | /// the specified element. |
368 | Constant *getStructElement(unsigned Elt) const; |
369 | |
370 | /// Return a zero of the right value for the specified GEP index if we can, |
371 | /// otherwise return null (e.g. if C is a ConstantExpr). |
372 | Constant *getElementValue(Constant *C) const; |
373 | |
374 | /// Return a zero of the right value for the specified GEP index. |
375 | Constant *getElementValue(unsigned Idx) const; |
376 | |
377 | /// Return the number of elements in the array, vector, or struct. |
378 | unsigned getNumElements() const; |
379 | |
380 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
381 | /// |
382 | static bool classof(const Value *V) { |
383 | return V->getValueID() == ConstantAggregateZeroVal; |
384 | } |
385 | }; |
386 | |
387 | /// Base class for aggregate constants (with operands). |
388 | /// |
389 | /// These constants are aggregates of other constants, which are stored as |
390 | /// operands. |
391 | /// |
392 | /// Subclasses are \a ConstantStruct, \a ConstantArray, and \a |
393 | /// ConstantVector. |
394 | /// |
395 | /// \note Some subclasses of \a ConstantData are semantically aggregates -- |
396 | /// such as \a ConstantDataArray -- but are not subclasses of this because they |
397 | /// use operands. |
398 | class ConstantAggregate : public Constant { |
399 | protected: |
400 | ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V); |
401 | |
402 | public: |
403 | /// Transparently provide more efficient getOperand methods. |
404 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void setOperand(unsigned, Constant*); inline op_iterator op_begin (); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
405 | |
406 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
407 | static bool classof(const Value *V) { |
408 | return V->getValueID() >= ConstantAggregateFirstVal && |
409 | V->getValueID() <= ConstantAggregateLastVal; |
410 | } |
411 | }; |
412 | |
413 | template <> |
414 | struct OperandTraits<ConstantAggregate> |
415 | : public VariadicOperandTraits<ConstantAggregate> {}; |
416 | |
417 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)ConstantAggregate::op_iterator ConstantAggregate::op_begin() { return OperandTraits<ConstantAggregate>::op_begin(this ); } ConstantAggregate::const_op_iterator ConstantAggregate:: op_begin() const { return OperandTraits<ConstantAggregate> ::op_begin(const_cast<ConstantAggregate*>(this)); } ConstantAggregate ::op_iterator ConstantAggregate::op_end() { return OperandTraits <ConstantAggregate>::op_end(this); } ConstantAggregate:: const_op_iterator ConstantAggregate::op_end() const { return OperandTraits <ConstantAggregate>::op_end(const_cast<ConstantAggregate *>(this)); } Constant *ConstantAggregate::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ConstantAggregate >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 417, __PRETTY_FUNCTION__)); return cast_or_null<Constant >( OperandTraits<ConstantAggregate>::op_begin(const_cast <ConstantAggregate*>(this))[i_nocapture].get()); } void ConstantAggregate::setOperand(unsigned i_nocapture, Constant *Val_nocapture) { ((i_nocapture < OperandTraits<ConstantAggregate >::operands(this) && "setOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 417, __PRETTY_FUNCTION__)); OperandTraits<ConstantAggregate >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ConstantAggregate::getNumOperands() const { return OperandTraits <ConstantAggregate>::operands(this); } template <int Idx_nocapture> Use &ConstantAggregate::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &ConstantAggregate::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
418 | |
419 | //===----------------------------------------------------------------------===// |
420 | /// ConstantArray - Constant Array Declarations |
421 | /// |
422 | class ConstantArray final : public ConstantAggregate { |
423 | friend struct ConstantAggrKeyType<ConstantArray>; |
424 | friend class Constant; |
425 | |
426 | ConstantArray(ArrayType *T, ArrayRef<Constant *> Val); |
427 | |
428 | void destroyConstantImpl(); |
429 | Value *handleOperandChangeImpl(Value *From, Value *To); |
430 | |
431 | public: |
432 | // ConstantArray accessors |
433 | static Constant *get(ArrayType *T, ArrayRef<Constant*> V); |
434 | |
435 | private: |
436 | static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V); |
437 | |
438 | public: |
439 | /// Specialize the getType() method to always return an ArrayType, |
440 | /// which reduces the amount of casting needed in parts of the compiler. |
441 | inline ArrayType *getType() const { |
442 | return cast<ArrayType>(Value::getType()); |
443 | } |
444 | |
445 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
446 | static bool classof(const Value *V) { |
447 | return V->getValueID() == ConstantArrayVal; |
448 | } |
449 | }; |
450 | |
451 | //===----------------------------------------------------------------------===// |
452 | // Constant Struct Declarations |
453 | // |
454 | class ConstantStruct final : public ConstantAggregate { |
455 | friend struct ConstantAggrKeyType<ConstantStruct>; |
456 | friend class Constant; |
457 | |
458 | ConstantStruct(StructType *T, ArrayRef<Constant *> Val); |
459 | |
460 | void destroyConstantImpl(); |
461 | Value *handleOperandChangeImpl(Value *From, Value *To); |
462 | |
463 | public: |
464 | // ConstantStruct accessors |
465 | static Constant *get(StructType *T, ArrayRef<Constant*> V); |
466 | |
467 | template <typename... Csts> |
468 | static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *> |
469 | get(StructType *T, Csts *... Vs) { |
470 | SmallVector<Constant *, 8> Values({Vs...}); |
471 | return get(T, Values); |
472 | } |
473 | |
474 | /// Return an anonymous struct that has the specified elements. |
475 | /// If the struct is possibly empty, then you must specify a context. |
476 | static Constant *getAnon(ArrayRef<Constant*> V, bool Packed = false) { |
477 | return get(getTypeForElements(V, Packed), V); |
478 | } |
479 | static Constant *getAnon(LLVMContext &Ctx, |
480 | ArrayRef<Constant*> V, bool Packed = false) { |
481 | return get(getTypeForElements(Ctx, V, Packed), V); |
482 | } |
483 | |
484 | /// Return an anonymous struct type to use for a constant with the specified |
485 | /// set of elements. The list must not be empty. |
486 | static StructType *getTypeForElements(ArrayRef<Constant*> V, |
487 | bool Packed = false); |
488 | /// This version of the method allows an empty list. |
489 | static StructType *getTypeForElements(LLVMContext &Ctx, |
490 | ArrayRef<Constant*> V, |
491 | bool Packed = false); |
492 | |
493 | /// Specialization - reduce amount of casting. |
494 | inline StructType *getType() const { |
495 | return cast<StructType>(Value::getType()); |
496 | } |
497 | |
498 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
499 | static bool classof(const Value *V) { |
500 | return V->getValueID() == ConstantStructVal; |
501 | } |
502 | }; |
503 | |
504 | //===----------------------------------------------------------------------===// |
505 | /// Constant Vector Declarations |
506 | /// |
507 | class ConstantVector final : public ConstantAggregate { |
508 | friend struct ConstantAggrKeyType<ConstantVector>; |
509 | friend class Constant; |
510 | |
511 | ConstantVector(VectorType *T, ArrayRef<Constant *> Val); |
512 | |
513 | void destroyConstantImpl(); |
514 | Value *handleOperandChangeImpl(Value *From, Value *To); |
515 | |
516 | public: |
517 | // ConstantVector accessors |
518 | static Constant *get(ArrayRef<Constant*> V); |
519 | |
520 | private: |
521 | static Constant *getImpl(ArrayRef<Constant *> V); |
522 | |
523 | public: |
524 | /// Return a ConstantVector with the specified constant in each element. |
525 | /// Note that this might not return an instance of ConstantVector |
526 | static Constant *getSplat(ElementCount EC, Constant *Elt); |
527 | |
528 | /// Specialize the getType() method to always return a FixedVectorType, |
529 | /// which reduces the amount of casting needed in parts of the compiler. |
530 | inline FixedVectorType *getType() const { |
531 | return cast<FixedVectorType>(Value::getType()); |
532 | } |
533 | |
534 | /// If all elements of the vector constant have the same value, return that |
535 | /// value. Otherwise, return nullptr. Ignore undefined elements by setting |
536 | /// AllowUndefs to true. |
537 | Constant *getSplatValue(bool AllowUndefs = false) const; |
538 | |
539 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
540 | static bool classof(const Value *V) { |
541 | return V->getValueID() == ConstantVectorVal; |
542 | } |
543 | }; |
544 | |
545 | //===----------------------------------------------------------------------===// |
546 | /// A constant pointer value that points to null |
547 | /// |
548 | class ConstantPointerNull final : public ConstantData { |
549 | friend class Constant; |
550 | |
551 | explicit ConstantPointerNull(PointerType *T) |
552 | : ConstantData(T, Value::ConstantPointerNullVal) {} |
553 | |
554 | void destroyConstantImpl(); |
555 | |
556 | public: |
557 | ConstantPointerNull(const ConstantPointerNull &) = delete; |
558 | |
559 | /// Static factory methods - Return objects of the specified value |
560 | static ConstantPointerNull *get(PointerType *T); |
561 | |
562 | /// Specialize the getType() method to always return an PointerType, |
563 | /// which reduces the amount of casting needed in parts of the compiler. |
564 | inline PointerType *getType() const { |
565 | return cast<PointerType>(Value::getType()); |
566 | } |
567 | |
568 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
569 | static bool classof(const Value *V) { |
570 | return V->getValueID() == ConstantPointerNullVal; |
571 | } |
572 | }; |
573 | |
574 | //===----------------------------------------------------------------------===// |
575 | /// ConstantDataSequential - A vector or array constant whose element type is a |
576 | /// simple 1/2/4/8-byte integer or float/double, and whose elements are just |
577 | /// simple data values (i.e. ConstantInt/ConstantFP). This Constant node has no |
578 | /// operands because it stores all of the elements of the constant as densely |
579 | /// packed data, instead of as Value*'s. |
580 | /// |
581 | /// This is the common base class of ConstantDataArray and ConstantDataVector. |
582 | /// |
583 | class ConstantDataSequential : public ConstantData { |
584 | friend class LLVMContextImpl; |
585 | friend class Constant; |
586 | |
587 | /// A pointer to the bytes underlying this constant (which is owned by the |
588 | /// uniquing StringMap). |
589 | const char *DataElements; |
590 | |
591 | /// This forms a link list of ConstantDataSequential nodes that have |
592 | /// the same value but different type. For example, 0,0,0,1 could be a 4 |
593 | /// element array of i8, or a 1-element array of i32. They'll both end up in |
594 | /// the same StringMap bucket, linked up. |
595 | ConstantDataSequential *Next; |
596 | |
597 | void destroyConstantImpl(); |
598 | |
599 | protected: |
600 | explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data) |
601 | : ConstantData(ty, VT), DataElements(Data), Next(nullptr) {} |
602 | ~ConstantDataSequential() { delete Next; } |
603 | |
604 | static Constant *getImpl(StringRef Bytes, Type *Ty); |
605 | |
606 | public: |
607 | ConstantDataSequential(const ConstantDataSequential &) = delete; |
608 | |
609 | /// Return true if a ConstantDataSequential can be formed with a vector or |
610 | /// array of the specified element type. |
611 | /// ConstantDataArray only works with normal float and int types that are |
612 | /// stored densely in memory, not with things like i42 or x86_f80. |
613 | static bool isElementTypeCompatible(Type *Ty); |
614 | |
615 | /// If this is a sequential container of integers (of any size), return the |
616 | /// specified element in the low bits of a uint64_t. |
617 | uint64_t getElementAsInteger(unsigned i) const; |
618 | |
619 | /// If this is a sequential container of integers (of any size), return the |
620 | /// specified element as an APInt. |
621 | APInt getElementAsAPInt(unsigned i) const; |
622 | |
623 | /// If this is a sequential container of floating point type, return the |
624 | /// specified element as an APFloat. |
625 | APFloat getElementAsAPFloat(unsigned i) const; |
626 | |
627 | /// If this is an sequential container of floats, return the specified element |
628 | /// as a float. |
629 | float getElementAsFloat(unsigned i) const; |
630 | |
631 | /// If this is an sequential container of doubles, return the specified |
632 | /// element as a double. |
633 | double getElementAsDouble(unsigned i) const; |
634 | |
635 | /// Return a Constant for a specified index's element. |
636 | /// Note that this has to compute a new constant to return, so it isn't as |
637 | /// efficient as getElementAsInteger/Float/Double. |
638 | Constant *getElementAsConstant(unsigned i) const; |
639 | |
640 | /// Return the element type of the array/vector. |
641 | Type *getElementType() const; |
642 | |
643 | /// Return the number of elements in the array or vector. |
644 | unsigned getNumElements() const; |
645 | |
646 | /// Return the size (in bytes) of each element in the array/vector. |
647 | /// The size of the elements is known to be a multiple of one byte. |
648 | uint64_t getElementByteSize() const; |
649 | |
650 | /// This method returns true if this is an array of \p CharSize integers. |
651 | bool isString(unsigned CharSize = 8) const; |
652 | |
653 | /// This method returns true if the array "isString", ends with a null byte, |
654 | /// and does not contains any other null bytes. |
655 | bool isCString() const; |
656 | |
657 | /// If this array is isString(), then this method returns the array as a |
658 | /// StringRef. Otherwise, it asserts out. |
659 | StringRef getAsString() const { |
660 | assert(isString() && "Not a string")((isString() && "Not a string") ? static_cast<void > (0) : __assert_fail ("isString() && \"Not a string\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 660, __PRETTY_FUNCTION__)); |
661 | return getRawDataValues(); |
662 | } |
663 | |
664 | /// If this array is isCString(), then this method returns the array (without |
665 | /// the trailing null byte) as a StringRef. Otherwise, it asserts out. |
666 | StringRef getAsCString() const { |
667 | assert(isCString() && "Isn't a C string")((isCString() && "Isn't a C string") ? static_cast< void> (0) : __assert_fail ("isCString() && \"Isn't a C string\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 667, __PRETTY_FUNCTION__)); |
668 | StringRef Str = getAsString(); |
669 | return Str.substr(0, Str.size()-1); |
670 | } |
671 | |
672 | /// Return the raw, underlying, bytes of this data. Note that this is an |
673 | /// extremely tricky thing to work with, as it exposes the host endianness of |
674 | /// the data elements. |
675 | StringRef getRawDataValues() const; |
676 | |
677 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
678 | static bool classof(const Value *V) { |
679 | return V->getValueID() == ConstantDataArrayVal || |
680 | V->getValueID() == ConstantDataVectorVal; |
681 | } |
682 | |
683 | private: |
684 | const char *getElementPointer(unsigned Elt) const; |
685 | }; |
686 | |
687 | //===----------------------------------------------------------------------===// |
688 | /// An array constant whose element type is a simple 1/2/4/8-byte integer or |
689 | /// float/double, and whose elements are just simple data values |
690 | /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it |
691 | /// stores all of the elements of the constant as densely packed data, instead |
692 | /// of as Value*'s. |
693 | class ConstantDataArray final : public ConstantDataSequential { |
694 | friend class ConstantDataSequential; |
695 | |
696 | explicit ConstantDataArray(Type *ty, const char *Data) |
697 | : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {} |
698 | |
699 | public: |
700 | ConstantDataArray(const ConstantDataArray &) = delete; |
701 | |
702 | /// get() constructor - Return a constant with array type with an element |
703 | /// count and element type matching the ArrayRef passed in. Note that this |
704 | /// can return a ConstantAggregateZero object. |
705 | template <typename ElementTy> |
706 | static Constant *get(LLVMContext &Context, ArrayRef<ElementTy> Elts) { |
707 | const char *Data = reinterpret_cast<const char *>(Elts.data()); |
708 | return getRaw(StringRef(Data, Elts.size() * sizeof(ElementTy)), Elts.size(), |
709 | Type::getScalarTy<ElementTy>(Context)); |
710 | } |
711 | |
712 | /// get() constructor - ArrayTy needs to be compatible with |
713 | /// ArrayRef<ElementTy>. Calls get(LLVMContext, ArrayRef<ElementTy>). |
714 | template <typename ArrayTy> |
715 | static Constant *get(LLVMContext &Context, ArrayTy &Elts) { |
716 | return ConstantDataArray::get(Context, makeArrayRef(Elts)); |
717 | } |
718 | |
719 | /// get() constructor - Return a constant with array type with an element |
720 | /// count and element type matching the NumElements and ElementTy parameters |
721 | /// passed in. Note that this can return a ConstantAggregateZero object. |
722 | /// ElementTy needs to be one of i8/i16/i32/i64/float/double. Data is the |
723 | /// buffer containing the elements. Be careful to make sure Data uses the |
724 | /// right endianness, the buffer will be used as-is. |
725 | static Constant *getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy) { |
726 | Type *Ty = ArrayType::get(ElementTy, NumElements); |
727 | return getImpl(Data, Ty); |
728 | } |
729 | |
730 | /// getFP() constructors - Return a constant of array type with a float |
731 | /// element type taken from argument `ElementType', and count taken from |
732 | /// argument `Elts'. The amount of bits of the contained type must match the |
733 | /// number of bits of the type contained in the passed in ArrayRef. |
734 | /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note |
735 | /// that this can return a ConstantAggregateZero object. |
736 | static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts); |
737 | static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts); |
738 | static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts); |
739 | |
740 | /// This method constructs a CDS and initializes it with a text string. |
741 | /// The default behavior (AddNull==true) causes a null terminator to |
742 | /// be placed at the end of the array (increasing the length of the string by |
743 | /// one more than the StringRef would normally indicate. Pass AddNull=false |
744 | /// to disable this behavior. |
745 | static Constant *getString(LLVMContext &Context, StringRef Initializer, |
746 | bool AddNull = true); |
747 | |
748 | /// Specialize the getType() method to always return an ArrayType, |
749 | /// which reduces the amount of casting needed in parts of the compiler. |
750 | inline ArrayType *getType() const { |
751 | return cast<ArrayType>(Value::getType()); |
752 | } |
753 | |
754 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
755 | static bool classof(const Value *V) { |
756 | return V->getValueID() == ConstantDataArrayVal; |
757 | } |
758 | }; |
759 | |
760 | //===----------------------------------------------------------------------===// |
761 | /// A vector constant whose element type is a simple 1/2/4/8-byte integer or |
762 | /// float/double, and whose elements are just simple data values |
763 | /// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it |
764 | /// stores all of the elements of the constant as densely packed data, instead |
765 | /// of as Value*'s. |
766 | class ConstantDataVector final : public ConstantDataSequential { |
767 | friend class ConstantDataSequential; |
768 | |
769 | explicit ConstantDataVector(Type *ty, const char *Data) |
770 | : ConstantDataSequential(ty, ConstantDataVectorVal, Data), |
771 | IsSplatSet(false) {} |
772 | // Cache whether or not the constant is a splat. |
773 | mutable bool IsSplatSet : 1; |
774 | mutable bool IsSplat : 1; |
775 | bool isSplatData() const; |
776 | |
777 | public: |
778 | ConstantDataVector(const ConstantDataVector &) = delete; |
779 | |
780 | /// get() constructors - Return a constant with vector type with an element |
781 | /// count and element type matching the ArrayRef passed in. Note that this |
782 | /// can return a ConstantAggregateZero object. |
783 | static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts); |
784 | static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts); |
785 | static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts); |
786 | static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts); |
787 | static Constant *get(LLVMContext &Context, ArrayRef<float> Elts); |
788 | static Constant *get(LLVMContext &Context, ArrayRef<double> Elts); |
789 | |
790 | /// getFP() constructors - Return a constant of vector type with a float |
791 | /// element type taken from argument `ElementType', and count taken from |
792 | /// argument `Elts'. The amount of bits of the contained type must match the |
793 | /// number of bits of the type contained in the passed in ArrayRef. |
794 | /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note |
795 | /// that this can return a ConstantAggregateZero object. |
796 | static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts); |
797 | static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts); |
798 | static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts); |
799 | |
800 | /// Return a ConstantVector with the specified constant in each element. |
801 | /// The specified constant has to be a of a compatible type (i8/i16/ |
802 | /// i32/i64/float/double) and must be a ConstantFP or ConstantInt. |
803 | static Constant *getSplat(unsigned NumElts, Constant *Elt); |
804 | |
805 | /// Returns true if this is a splat constant, meaning that all elements have |
806 | /// the same value. |
807 | bool isSplat() const; |
808 | |
809 | /// If this is a splat constant, meaning that all of the elements have the |
810 | /// same value, return that value. Otherwise return NULL. |
811 | Constant *getSplatValue() const; |
812 | |
813 | /// Specialize the getType() method to always return a FixedVectorType, |
814 | /// which reduces the amount of casting needed in parts of the compiler. |
815 | inline FixedVectorType *getType() const { |
816 | return cast<FixedVectorType>(Value::getType()); |
817 | } |
818 | |
819 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
820 | static bool classof(const Value *V) { |
821 | return V->getValueID() == ConstantDataVectorVal; |
822 | } |
823 | }; |
824 | |
825 | //===----------------------------------------------------------------------===// |
826 | /// A constant token which is empty |
827 | /// |
828 | class ConstantTokenNone final : public ConstantData { |
829 | friend class Constant; |
830 | |
831 | explicit ConstantTokenNone(LLVMContext &Context) |
832 | : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {} |
833 | |
834 | void destroyConstantImpl(); |
835 | |
836 | public: |
837 | ConstantTokenNone(const ConstantTokenNone &) = delete; |
838 | |
839 | /// Return the ConstantTokenNone. |
840 | static ConstantTokenNone *get(LLVMContext &Context); |
841 | |
842 | /// Methods to support type inquiry through isa, cast, and dyn_cast. |
843 | static bool classof(const Value *V) { |
844 | return V->getValueID() == ConstantTokenNoneVal; |
845 | } |
846 | }; |
847 | |
848 | /// The address of a basic block. |
849 | /// |
850 | class BlockAddress final : public Constant { |
851 | friend class Constant; |
852 | |
853 | BlockAddress(Function *F, BasicBlock *BB); |
854 | |
855 | void *operator new(size_t s) { return User::operator new(s, 2); } |
856 | |
857 | void destroyConstantImpl(); |
858 | Value *handleOperandChangeImpl(Value *From, Value *To); |
859 | |
860 | public: |
861 | /// Return a BlockAddress for the specified function and basic block. |
862 | static BlockAddress *get(Function *F, BasicBlock *BB); |
863 | |
864 | /// Return a BlockAddress for the specified basic block. The basic |
865 | /// block must be embedded into a function. |
866 | static BlockAddress *get(BasicBlock *BB); |
867 | |
868 | /// Lookup an existing \c BlockAddress constant for the given BasicBlock. |
869 | /// |
870 | /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress. |
871 | static BlockAddress *lookup(const BasicBlock *BB); |
872 | |
873 | /// Transparently provide more efficient getOperand methods. |
874 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
875 | |
876 | Function *getFunction() const { return (Function*)Op<0>().get(); } |
877 | BasicBlock *getBasicBlock() const { return (BasicBlock*)Op<1>().get(); } |
878 | |
879 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
880 | static bool classof(const Value *V) { |
881 | return V->getValueID() == BlockAddressVal; |
882 | } |
883 | }; |
884 | |
885 | template <> |
886 | struct OperandTraits<BlockAddress> : |
887 | public FixedNumOperandTraits<BlockAddress, 2> { |
888 | }; |
889 | |
890 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)BlockAddress::op_iterator BlockAddress::op_begin() { return OperandTraits <BlockAddress>::op_begin(this); } BlockAddress::const_op_iterator BlockAddress::op_begin() const { return OperandTraits<BlockAddress >::op_begin(const_cast<BlockAddress*>(this)); } BlockAddress ::op_iterator BlockAddress::op_end() { return OperandTraits< BlockAddress>::op_end(this); } BlockAddress::const_op_iterator BlockAddress::op_end() const { return OperandTraits<BlockAddress >::op_end(const_cast<BlockAddress*>(this)); } Value * BlockAddress::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<BlockAddress>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 890, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<BlockAddress>::op_begin(const_cast<BlockAddress *>(this))[i_nocapture].get()); } void BlockAddress::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<BlockAddress>::operands(this) && "setOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 890, __PRETTY_FUNCTION__)); OperandTraits<BlockAddress> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BlockAddress ::getNumOperands() const { return OperandTraits<BlockAddress >::operands(this); } template <int Idx_nocapture> Use &BlockAddress::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & BlockAddress::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
891 | |
892 | //===----------------------------------------------------------------------===// |
893 | /// A constant value that is initialized with an expression using |
894 | /// other constant values. |
895 | /// |
896 | /// This class uses the standard Instruction opcodes to define the various |
897 | /// constant expressions. The Opcode field for the ConstantExpr class is |
898 | /// maintained in the Value::SubclassData field. |
899 | class ConstantExpr : public Constant { |
900 | friend struct ConstantExprKeyType; |
901 | friend class Constant; |
902 | |
903 | void destroyConstantImpl(); |
904 | Value *handleOperandChangeImpl(Value *From, Value *To); |
905 | |
906 | protected: |
907 | ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps) |
908 | : Constant(ty, ConstantExprVal, Ops, NumOps) { |
909 | // Operation type (an Instruction opcode) is stored as the SubclassData. |
910 | setValueSubclassData(Opcode); |
911 | } |
912 | |
913 | ~ConstantExpr() = default; |
914 | |
915 | public: |
916 | // Static methods to construct a ConstantExpr of different kinds. Note that |
917 | // these methods may return a object that is not an instance of the |
918 | // ConstantExpr class, because they will attempt to fold the constant |
919 | // expression into something simpler if possible. |
920 | |
921 | /// getAlignOf constant expr - computes the alignment of a type in a target |
922 | /// independent way (Note: the return type is an i64). |
923 | static Constant *getAlignOf(Type *Ty); |
924 | |
925 | /// getSizeOf constant expr - computes the (alloc) size of a type (in |
926 | /// address-units, not bits) in a target independent way (Note: the return |
927 | /// type is an i64). |
928 | /// |
929 | static Constant *getSizeOf(Type *Ty); |
930 | |
931 | /// getOffsetOf constant expr - computes the offset of a struct field in a |
932 | /// target independent way (Note: the return type is an i64). |
933 | /// |
934 | static Constant *getOffsetOf(StructType *STy, unsigned FieldNo); |
935 | |
936 | /// getOffsetOf constant expr - This is a generalized form of getOffsetOf, |
937 | /// which supports any aggregate type, and any Constant index. |
938 | /// |
939 | static Constant *getOffsetOf(Type *Ty, Constant *FieldNo); |
940 | |
941 | static Constant *getNeg(Constant *C, bool HasNUW = false, bool HasNSW =false); |
942 | static Constant *getFNeg(Constant *C); |
943 | static Constant *getNot(Constant *C); |
944 | static Constant *getAdd(Constant *C1, Constant *C2, |
945 | bool HasNUW = false, bool HasNSW = false); |
946 | static Constant *getFAdd(Constant *C1, Constant *C2); |
947 | static Constant *getSub(Constant *C1, Constant *C2, |
948 | bool HasNUW = false, bool HasNSW = false); |
949 | static Constant *getFSub(Constant *C1, Constant *C2); |
950 | static Constant *getMul(Constant *C1, Constant *C2, |
951 | bool HasNUW = false, bool HasNSW = false); |
952 | static Constant *getFMul(Constant *C1, Constant *C2); |
953 | static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false); |
954 | static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false); |
955 | static Constant *getFDiv(Constant *C1, Constant *C2); |
956 | static Constant *getURem(Constant *C1, Constant *C2); |
957 | static Constant *getSRem(Constant *C1, Constant *C2); |
958 | static Constant *getFRem(Constant *C1, Constant *C2); |
959 | static Constant *getAnd(Constant *C1, Constant *C2); |
960 | static Constant *getOr(Constant *C1, Constant *C2); |
961 | static Constant *getXor(Constant *C1, Constant *C2); |
962 | static Constant *getShl(Constant *C1, Constant *C2, |
963 | bool HasNUW = false, bool HasNSW = false); |
964 | static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false); |
965 | static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false); |
966 | static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
967 | static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
968 | static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
969 | static Constant *getFPTrunc(Constant *C, Type *Ty, |
970 | bool OnlyIfReduced = false); |
971 | static Constant *getFPExtend(Constant *C, Type *Ty, |
972 | bool OnlyIfReduced = false); |
973 | static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
974 | static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
975 | static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
976 | static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false); |
977 | static Constant *getPtrToInt(Constant *C, Type *Ty, |
978 | bool OnlyIfReduced = false); |
979 | static Constant *getIntToPtr(Constant *C, Type *Ty, |
980 | bool OnlyIfReduced = false); |
981 | static Constant *getBitCast(Constant *C, Type *Ty, |
982 | bool OnlyIfReduced = false); |
983 | static Constant *getAddrSpaceCast(Constant *C, Type *Ty, |
984 | bool OnlyIfReduced = false); |
985 | |
986 | static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); } |
987 | static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); } |
988 | |
989 | static Constant *getNSWAdd(Constant *C1, Constant *C2) { |
990 | return getAdd(C1, C2, false, true); |
991 | } |
992 | |
993 | static Constant *getNUWAdd(Constant *C1, Constant *C2) { |
994 | return getAdd(C1, C2, true, false); |
995 | } |
996 | |
997 | static Constant *getNSWSub(Constant *C1, Constant *C2) { |
998 | return getSub(C1, C2, false, true); |
999 | } |
1000 | |
1001 | static Constant *getNUWSub(Constant *C1, Constant *C2) { |
1002 | return getSub(C1, C2, true, false); |
1003 | } |
1004 | |
1005 | static Constant *getNSWMul(Constant *C1, Constant *C2) { |
1006 | return getMul(C1, C2, false, true); |
1007 | } |
1008 | |
1009 | static Constant *getNUWMul(Constant *C1, Constant *C2) { |
1010 | return getMul(C1, C2, true, false); |
1011 | } |
1012 | |
1013 | static Constant *getNSWShl(Constant *C1, Constant *C2) { |
1014 | return getShl(C1, C2, false, true); |
1015 | } |
1016 | |
1017 | static Constant *getNUWShl(Constant *C1, Constant *C2) { |
1018 | return getShl(C1, C2, true, false); |
1019 | } |
1020 | |
1021 | static Constant *getExactSDiv(Constant *C1, Constant *C2) { |
1022 | return getSDiv(C1, C2, true); |
1023 | } |
1024 | |
1025 | static Constant *getExactUDiv(Constant *C1, Constant *C2) { |
1026 | return getUDiv(C1, C2, true); |
1027 | } |
1028 | |
1029 | static Constant *getExactAShr(Constant *C1, Constant *C2) { |
1030 | return getAShr(C1, C2, true); |
1031 | } |
1032 | |
1033 | static Constant *getExactLShr(Constant *C1, Constant *C2) { |
1034 | return getLShr(C1, C2, true); |
1035 | } |
1036 | |
1037 | /// Return the identity constant for a binary opcode. |
1038 | /// The identity constant C is defined as X op C = X and C op X = X for every |
1039 | /// X when the binary operation is commutative. If the binop is not |
1040 | /// commutative, callers can acquire the operand 1 identity constant by |
1041 | /// setting AllowRHSConstant to true. For example, any shift has a zero |
1042 | /// identity constant for operand 1: X shift 0 = X. |
1043 | /// Return nullptr if the operator does not have an identity constant. |
1044 | static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty, |
1045 | bool AllowRHSConstant = false); |
1046 | |
1047 | /// Return the absorbing element for the given binary |
1048 | /// operation, i.e. a constant C such that X op C = C and C op X = C for |
1049 | /// every X. For example, this returns zero for integer multiplication. |
1050 | /// It returns null if the operator doesn't have an absorbing element. |
1051 | static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty); |
1052 | |
1053 | /// Transparently provide more efficient getOperand methods. |
1054 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void setOperand(unsigned, Constant*); inline op_iterator op_begin (); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1055 | |
1056 | /// Convenience function for getting a Cast operation. |
1057 | /// |
1058 | /// \param ops The opcode for the conversion |
1059 | /// \param C The constant to be converted |
1060 | /// \param Ty The type to which the constant is converted |
1061 | /// \param OnlyIfReduced see \a getWithOperands() docs. |
1062 | static Constant *getCast(unsigned ops, Constant *C, Type *Ty, |
1063 | bool OnlyIfReduced = false); |
1064 | |
1065 | // Create a ZExt or BitCast cast constant expression |
1066 | static Constant *getZExtOrBitCast( |
1067 | Constant *C, ///< The constant to zext or bitcast |
1068 | Type *Ty ///< The type to zext or bitcast C to |
1069 | ); |
1070 | |
1071 | // Create a SExt or BitCast cast constant expression |
1072 | static Constant *getSExtOrBitCast( |
1073 | Constant *C, ///< The constant to sext or bitcast |
1074 | Type *Ty ///< The type to sext or bitcast C to |
1075 | ); |
1076 | |
1077 | // Create a Trunc or BitCast cast constant expression |
1078 | static Constant *getTruncOrBitCast( |
1079 | Constant *C, ///< The constant to trunc or bitcast |
1080 | Type *Ty ///< The type to trunc or bitcast C to |
1081 | ); |
1082 | |
1083 | /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant |
1084 | /// expression. |
1085 | static Constant *getPointerCast( |
1086 | Constant *C, ///< The pointer value to be casted (operand 0) |
1087 | Type *Ty ///< The type to which cast should be made |
1088 | ); |
1089 | |
1090 | /// Create a BitCast or AddrSpaceCast for a pointer type depending on |
1091 | /// the address space. |
1092 | static Constant *getPointerBitCastOrAddrSpaceCast( |
1093 | Constant *C, ///< The constant to addrspacecast or bitcast |
1094 | Type *Ty ///< The type to bitcast or addrspacecast C to |
1095 | ); |
1096 | |
1097 | /// Create a ZExt, Bitcast or Trunc for integer -> integer casts |
1098 | static Constant *getIntegerCast( |
1099 | Constant *C, ///< The integer constant to be casted |
1100 | Type *Ty, ///< The integer type to cast to |
1101 | bool isSigned ///< Whether C should be treated as signed or not |
1102 | ); |
1103 | |
1104 | /// Create a FPExt, Bitcast or FPTrunc for fp -> fp casts |
1105 | static Constant *getFPCast( |
1106 | Constant *C, ///< The integer constant to be casted |
1107 | Type *Ty ///< The integer type to cast to |
1108 | ); |
1109 | |
1110 | /// Return true if this is a convert constant expression |
1111 | bool isCast() const; |
1112 | |
1113 | /// Return true if this is a compare constant expression |
1114 | bool isCompare() const; |
1115 | |
1116 | /// Return true if this is an insertvalue or extractvalue expression, |
1117 | /// and the getIndices() method may be used. |
1118 | bool hasIndices() const; |
1119 | |
1120 | /// Return true if this is a getelementptr expression and all |
1121 | /// the index operands are compile-time known integers within the |
1122 | /// corresponding notional static array extents. Note that this is |
1123 | /// not equivalant to, a subset of, or a superset of the "inbounds" |
1124 | /// property. |
1125 | bool isGEPWithNoNotionalOverIndexing() const; |
1126 | |
1127 | /// Select constant expr |
1128 | /// |
1129 | /// \param OnlyIfReducedTy see \a getWithOperands() docs. |
1130 | static Constant *getSelect(Constant *C, Constant *V1, Constant *V2, |
1131 | Type *OnlyIfReducedTy = nullptr); |
1132 | |
1133 | /// get - Return a unary operator constant expression, |
1134 | /// folding if possible. |
1135 | /// |
1136 | /// \param OnlyIfReducedTy see \a getWithOperands() docs. |
1137 | static Constant *get(unsigned Opcode, Constant *C1, unsigned Flags = 0, |
1138 | Type *OnlyIfReducedTy = nullptr); |
1139 | |
1140 | /// get - Return a binary or shift operator constant expression, |
1141 | /// folding if possible. |
1142 | /// |
1143 | /// \param OnlyIfReducedTy see \a getWithOperands() docs. |
1144 | static Constant *get(unsigned Opcode, Constant *C1, Constant *C2, |
1145 | unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr); |
1146 | |
1147 | /// Return an ICmp or FCmp comparison operator constant expression. |
1148 | /// |
1149 | /// \param OnlyIfReduced see \a getWithOperands() docs. |
1150 | static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2, |
1151 | bool OnlyIfReduced = false); |
1152 | |
1153 | /// get* - Return some common constants without having to |
1154 | /// specify the full Instruction::OPCODE identifier. |
1155 | /// |
1156 | static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS, |
1157 | bool OnlyIfReduced = false); |
1158 | static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, |
1159 | bool OnlyIfReduced = false); |
1160 | |
1161 | /// Getelementptr form. Value* is only accepted for convenience; |
1162 | /// all elements must be Constants. |
1163 | /// |
1164 | /// \param InRangeIndex the inrange index if present or None. |
1165 | /// \param OnlyIfReducedTy see \a getWithOperands() docs. |
1166 | static Constant *getGetElementPtr(Type *Ty, Constant *C, |
1167 | ArrayRef<Constant *> IdxList, |
1168 | bool InBounds = false, |
1169 | Optional<unsigned> InRangeIndex = None, |
1170 | Type *OnlyIfReducedTy = nullptr) { |
1171 | return getGetElementPtr( |
1172 | Ty, C, makeArrayRef((Value * const *)IdxList.data(), IdxList.size()), |
1173 | InBounds, InRangeIndex, OnlyIfReducedTy); |
1174 | } |
1175 | static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx, |
1176 | bool InBounds = false, |
1177 | Optional<unsigned> InRangeIndex = None, |
1178 | Type *OnlyIfReducedTy = nullptr) { |
1179 | // This form of the function only exists to avoid ambiguous overload |
1180 | // warnings about whether to convert Idx to ArrayRef<Constant *> or |
1181 | // ArrayRef<Value *>. |
1182 | return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex, |
1183 | OnlyIfReducedTy); |
1184 | } |
1185 | static Constant *getGetElementPtr(Type *Ty, Constant *C, |
1186 | ArrayRef<Value *> IdxList, |
1187 | bool InBounds = false, |
1188 | Optional<unsigned> InRangeIndex = None, |
1189 | Type *OnlyIfReducedTy = nullptr); |
1190 | |
1191 | /// Create an "inbounds" getelementptr. See the documentation for the |
1192 | /// "inbounds" flag in LangRef.html for details. |
1193 | static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, |
1194 | ArrayRef<Constant *> IdxList) { |
1195 | return getGetElementPtr(Ty, C, IdxList, true); |
1196 | } |
1197 | static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, |
1198 | Constant *Idx) { |
1199 | // This form of the function only exists to avoid ambiguous overload |
1200 | // warnings about whether to convert Idx to ArrayRef<Constant *> or |
1201 | // ArrayRef<Value *>. |
1202 | return getGetElementPtr(Ty, C, Idx, true); |
1203 | } |
1204 | static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C, |
1205 | ArrayRef<Value *> IdxList) { |
1206 | return getGetElementPtr(Ty, C, IdxList, true); |
1207 | } |
1208 | |
1209 | static Constant *getExtractElement(Constant *Vec, Constant *Idx, |
1210 | Type *OnlyIfReducedTy = nullptr); |
1211 | static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, |
1212 | Type *OnlyIfReducedTy = nullptr); |
1213 | static Constant *getShuffleVector(Constant *V1, Constant *V2, |
1214 | ArrayRef<int> Mask, |
1215 | Type *OnlyIfReducedTy = nullptr); |
1216 | static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs, |
1217 | Type *OnlyIfReducedTy = nullptr); |
1218 | static Constant *getInsertValue(Constant *Agg, Constant *Val, |
1219 | ArrayRef<unsigned> Idxs, |
1220 | Type *OnlyIfReducedTy = nullptr); |
1221 | |
1222 | /// Return the opcode at the root of this constant expression |
1223 | unsigned getOpcode() const { return getSubclassDataFromValue(); } |
1224 | |
1225 | /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or |
1226 | /// FCMP constant expression. |
1227 | unsigned getPredicate() const; |
1228 | |
1229 | /// Assert that this is an insertvalue or exactvalue |
1230 | /// expression and return the list of indices. |
1231 | ArrayRef<unsigned> getIndices() const; |
1232 | |
1233 | /// Assert that this is a shufflevector and return the mask. See class |
1234 | /// ShuffleVectorInst for a description of the mask representation. |
1235 | ArrayRef<int> getShuffleMask() const; |
1236 | |
1237 | /// Assert that this is a shufflevector and return the mask. |
1238 | /// |
1239 | /// TODO: This is a temporary hack until we update the bitcode format for |
1240 | /// shufflevector. |
1241 | Constant *getShuffleMaskForBitcode() const; |
1242 | |
1243 | /// Return a string representation for an opcode. |
1244 | const char *getOpcodeName() const; |
1245 | |
1246 | /// Return a constant expression identical to this one, but with the specified |
1247 | /// operand set to the specified value. |
1248 | Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const; |
1249 | |
1250 | /// This returns the current constant expression with the operands replaced |
1251 | /// with the specified values. The specified array must have the same number |
1252 | /// of operands as our current one. |
1253 | Constant *getWithOperands(ArrayRef<Constant*> Ops) const { |
1254 | return getWithOperands(Ops, getType()); |
1255 | } |
1256 | |
1257 | /// Get the current expression with the operands replaced. |
1258 | /// |
1259 | /// Return the current constant expression with the operands replaced with \c |
1260 | /// Ops and the type with \c Ty. The new operands must have the same number |
1261 | /// as the current ones. |
1262 | /// |
1263 | /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something |
1264 | /// gets constant-folded, the type changes, or the expression is otherwise |
1265 | /// canonicalized. This parameter should almost always be \c false. |
1266 | Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty, |
1267 | bool OnlyIfReduced = false, |
1268 | Type *SrcTy = nullptr) const; |
1269 | |
1270 | /// Returns an Instruction which implements the same operation as this |
1271 | /// ConstantExpr. The instruction is not linked to any basic block. |
1272 | /// |
1273 | /// A better approach to this could be to have a constructor for Instruction |
1274 | /// which would take a ConstantExpr parameter, but that would have spread |
1275 | /// implementation details of ConstantExpr outside of Constants.cpp, which |
1276 | /// would make it harder to remove ConstantExprs altogether. |
1277 | Instruction *getAsInstruction() const; |
1278 | |
1279 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1280 | static bool classof(const Value *V) { |
1281 | return V->getValueID() == ConstantExprVal; |
1282 | } |
1283 | |
1284 | private: |
1285 | // Shadow Value::setValueSubclassData with a private forwarding method so that |
1286 | // subclasses cannot accidentally use it. |
1287 | void setValueSubclassData(unsigned short D) { |
1288 | Value::setValueSubclassData(D); |
1289 | } |
1290 | }; |
1291 | |
1292 | template <> |
1293 | struct OperandTraits<ConstantExpr> : |
1294 | public VariadicOperandTraits<ConstantExpr, 1> { |
1295 | }; |
1296 | |
1297 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)ConstantExpr::op_iterator ConstantExpr::op_begin() { return OperandTraits <ConstantExpr>::op_begin(this); } ConstantExpr::const_op_iterator ConstantExpr::op_begin() const { return OperandTraits<ConstantExpr >::op_begin(const_cast<ConstantExpr*>(this)); } ConstantExpr ::op_iterator ConstantExpr::op_end() { return OperandTraits< ConstantExpr>::op_end(this); } ConstantExpr::const_op_iterator ConstantExpr::op_end() const { return OperandTraits<ConstantExpr >::op_end(const_cast<ConstantExpr*>(this)); } Constant *ConstantExpr::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ConstantExpr>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 1297, __PRETTY_FUNCTION__)); return cast_or_null<Constant >( OperandTraits<ConstantExpr>::op_begin(const_cast< ConstantExpr*>(this))[i_nocapture].get()); } void ConstantExpr ::setOperand(unsigned i_nocapture, Constant *Val_nocapture) { ((i_nocapture < OperandTraits<ConstantExpr>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Constants.h" , 1297, __PRETTY_FUNCTION__)); OperandTraits<ConstantExpr> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ConstantExpr ::getNumOperands() const { return OperandTraits<ConstantExpr >::operands(this); } template <int Idx_nocapture> Use &ConstantExpr::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ConstantExpr::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
1298 | |
1299 | //===----------------------------------------------------------------------===// |
1300 | /// 'undef' values are things that do not have specified contents. |
1301 | /// These are used for a variety of purposes, including global variable |
1302 | /// initializers and operands to instructions. 'undef' values can occur with |
1303 | /// any first-class type. |
1304 | /// |
1305 | /// Undef values aren't exactly constants; if they have multiple uses, they |
1306 | /// can appear to have different bit patterns at each use. See |
1307 | /// LangRef.html#undefvalues for details. |
1308 | /// |
1309 | class UndefValue final : public ConstantData { |
1310 | friend class Constant; |
1311 | |
1312 | explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {} |
1313 | |
1314 | void destroyConstantImpl(); |
1315 | |
1316 | public: |
1317 | UndefValue(const UndefValue &) = delete; |
1318 | |
1319 | /// Static factory methods - Return an 'undef' object of the specified type. |
1320 | static UndefValue *get(Type *T); |
1321 | |
1322 | /// If this Undef has array or vector type, return a undef with the right |
1323 | /// element type. |
1324 | UndefValue *getSequentialElement() const; |
1325 | |
1326 | /// If this undef has struct type, return a undef with the right element type |
1327 | /// for the specified element. |
1328 | UndefValue *getStructElement(unsigned Elt) const; |
1329 | |
1330 | /// Return an undef of the right value for the specified GEP index if we can, |
1331 | /// otherwise return null (e.g. if C is a ConstantExpr). |
1332 | UndefValue *getElementValue(Constant *C) const; |
1333 | |
1334 | /// Return an undef of the right value for the specified GEP index. |
1335 | UndefValue *getElementValue(unsigned Idx) const; |
1336 | |
1337 | /// Return the number of elements in the array, vector, or struct. |
1338 | unsigned getNumElements() const; |
1339 | |
1340 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1341 | static bool classof(const Value *V) { |
1342 | return V->getValueID() == UndefValueVal; |
1343 | } |
1344 | }; |
1345 | |
1346 | } // end namespace llvm |
1347 | |
1348 | #endif // LLVM_IR_CONSTANTS_H |
1 | //===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===// | ||||||||||
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 | /// \file | ||||||||||
10 | /// This file implements a class to represent arbitrary precision | ||||||||||
11 | /// integral constant values and operations on them. | ||||||||||
12 | /// | ||||||||||
13 | //===----------------------------------------------------------------------===// | ||||||||||
14 | |||||||||||
15 | #ifndef LLVM_ADT_APINT_H | ||||||||||
16 | #define LLVM_ADT_APINT_H | ||||||||||
17 | |||||||||||
18 | #include "llvm/Support/Compiler.h" | ||||||||||
19 | #include "llvm/Support/MathExtras.h" | ||||||||||
20 | #include <cassert> | ||||||||||
21 | #include <climits> | ||||||||||
22 | #include <cstring> | ||||||||||
23 | #include <string> | ||||||||||
24 | |||||||||||
25 | namespace llvm { | ||||||||||
26 | class FoldingSetNodeID; | ||||||||||
27 | class StringRef; | ||||||||||
28 | class hash_code; | ||||||||||
29 | class raw_ostream; | ||||||||||
30 | |||||||||||
31 | template <typename T> class SmallVectorImpl; | ||||||||||
32 | template <typename T> class ArrayRef; | ||||||||||
33 | template <typename T> class Optional; | ||||||||||
34 | template <typename T> struct DenseMapInfo; | ||||||||||
35 | |||||||||||
36 | class APInt; | ||||||||||
37 | |||||||||||
38 | inline APInt operator-(APInt); | ||||||||||
39 | |||||||||||
40 | //===----------------------------------------------------------------------===// | ||||||||||
41 | // APInt Class | ||||||||||
42 | //===----------------------------------------------------------------------===// | ||||||||||
43 | |||||||||||
44 | /// Class for arbitrary precision integers. | ||||||||||
45 | /// | ||||||||||
46 | /// APInt is a functional replacement for common case unsigned integer type like | ||||||||||
47 | /// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width | ||||||||||
48 | /// integer sizes and large integer value types such as 3-bits, 15-bits, or more | ||||||||||
49 | /// than 64-bits of precision. APInt provides a variety of arithmetic operators | ||||||||||
50 | /// and methods to manipulate integer values of any bit-width. It supports both | ||||||||||
51 | /// the typical integer arithmetic and comparison operations as well as bitwise | ||||||||||
52 | /// manipulation. | ||||||||||
53 | /// | ||||||||||
54 | /// The class has several invariants worth noting: | ||||||||||
55 | /// * All bit, byte, and word positions are zero-based. | ||||||||||
56 | /// * Once the bit width is set, it doesn't change except by the Truncate, | ||||||||||
57 | /// SignExtend, or ZeroExtend operations. | ||||||||||
58 | /// * All binary operators must be on APInt instances of the same bit width. | ||||||||||
59 | /// Attempting to use these operators on instances with different bit | ||||||||||
60 | /// widths will yield an assertion. | ||||||||||
61 | /// * The value is stored canonically as an unsigned value. For operations | ||||||||||
62 | /// where it makes a difference, there are both signed and unsigned variants | ||||||||||
63 | /// of the operation. For example, sdiv and udiv. However, because the bit | ||||||||||
64 | /// widths must be the same, operations such as Mul and Add produce the same | ||||||||||
65 | /// results regardless of whether the values are interpreted as signed or | ||||||||||
66 | /// not. | ||||||||||
67 | /// * In general, the class tries to follow the style of computation that LLVM | ||||||||||
68 | /// uses in its IR. This simplifies its use for LLVM. | ||||||||||
69 | /// | ||||||||||
70 | class LLVM_NODISCARD[[clang::warn_unused_result]] APInt { | ||||||||||
71 | public: | ||||||||||
72 | typedef uint64_t WordType; | ||||||||||
73 | |||||||||||
74 | /// This enum is used to hold the constants we needed for APInt. | ||||||||||
75 | enum : unsigned { | ||||||||||
76 | /// Byte size of a word. | ||||||||||
77 | APINT_WORD_SIZE = sizeof(WordType), | ||||||||||
78 | /// Bits in a word. | ||||||||||
79 | APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8 | ||||||||||
80 | }; | ||||||||||
81 | |||||||||||
82 | enum class Rounding { | ||||||||||
83 | DOWN, | ||||||||||
84 | TOWARD_ZERO, | ||||||||||
85 | UP, | ||||||||||
86 | }; | ||||||||||
87 | |||||||||||
88 | static constexpr WordType WORDTYPE_MAX = ~WordType(0); | ||||||||||
89 | |||||||||||
90 | private: | ||||||||||
91 | /// This union is used to store the integer value. When the | ||||||||||
92 | /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal. | ||||||||||
93 | union { | ||||||||||
94 | uint64_t VAL; ///< Used to store the <= 64 bits integer value. | ||||||||||
95 | uint64_t *pVal; ///< Used to store the >64 bits integer value. | ||||||||||
96 | } U; | ||||||||||
97 | |||||||||||
98 | unsigned BitWidth; ///< The number of bits in this APInt. | ||||||||||
99 | |||||||||||
100 | friend struct DenseMapInfo<APInt>; | ||||||||||
101 | |||||||||||
102 | friend class APSInt; | ||||||||||
103 | |||||||||||
104 | /// Fast internal constructor | ||||||||||
105 | /// | ||||||||||
106 | /// This constructor is used only internally for speed of construction of | ||||||||||
107 | /// temporaries. It is unsafe for general use so it is not public. | ||||||||||
108 | APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { | ||||||||||
109 | U.pVal = val; | ||||||||||
110 | } | ||||||||||
111 | |||||||||||
112 | /// Determine if this APInt just has one word to store value. | ||||||||||
113 | /// | ||||||||||
114 | /// \returns true if the number of bits <= 64, false otherwise. | ||||||||||
115 | bool isSingleWord() const { return BitWidth
| ||||||||||
116 | |||||||||||
117 | /// Determine which word a bit is in. | ||||||||||
118 | /// | ||||||||||
119 | /// \returns the word position for the specified bit position. | ||||||||||
120 | static unsigned whichWord(unsigned bitPosition) { | ||||||||||
121 | return bitPosition / APINT_BITS_PER_WORD; | ||||||||||
122 | } | ||||||||||
123 | |||||||||||
124 | /// Determine which bit in a word a bit is in. | ||||||||||
125 | /// | ||||||||||
126 | /// \returns the bit position in a word for the specified bit position | ||||||||||
127 | /// in the APInt. | ||||||||||
128 | static unsigned whichBit(unsigned bitPosition) { | ||||||||||
129 | return bitPosition % APINT_BITS_PER_WORD; | ||||||||||
130 | } | ||||||||||
131 | |||||||||||
132 | /// Get a single bit mask. | ||||||||||
133 | /// | ||||||||||
134 | /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set | ||||||||||
135 | /// This method generates and returns a uint64_t (word) mask for a single | ||||||||||
136 | /// bit at a specific bit position. This is used to mask the bit in the | ||||||||||
137 | /// corresponding word. | ||||||||||
138 | static uint64_t maskBit(unsigned bitPosition) { | ||||||||||
139 | return 1ULL << whichBit(bitPosition); | ||||||||||
140 | } | ||||||||||
141 | |||||||||||
142 | /// Clear unused high order bits | ||||||||||
143 | /// | ||||||||||
144 | /// This method is used internally to clear the top "N" bits in the high order | ||||||||||
145 | /// word that are not used by the APInt. This is needed after the most | ||||||||||
146 | /// significant word is assigned a value to ensure that those bits are | ||||||||||
147 | /// zero'd out. | ||||||||||
148 | APInt &clearUnusedBits() { | ||||||||||
149 | // Compute how many bits are used in the final word | ||||||||||
150 | unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1; | ||||||||||
151 | |||||||||||
152 | // Mask out the high bits. | ||||||||||
153 | uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits); | ||||||||||
154 | if (isSingleWord()) | ||||||||||
155 | U.VAL &= mask; | ||||||||||
156 | else | ||||||||||
157 | U.pVal[getNumWords() - 1] &= mask; | ||||||||||
158 | return *this; | ||||||||||
159 | } | ||||||||||
160 | |||||||||||
161 | /// Get the word corresponding to a bit position | ||||||||||
162 | /// \returns the corresponding word for the specified bit position. | ||||||||||
163 | uint64_t getWord(unsigned bitPosition) const { | ||||||||||
164 | return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)]; | ||||||||||
165 | } | ||||||||||
166 | |||||||||||
167 | /// Utility method to change the bit width of this APInt to new bit width, | ||||||||||
168 | /// allocating and/or deallocating as necessary. There is no guarantee on the | ||||||||||
169 | /// value of any bits upon return. Caller should populate the bits after. | ||||||||||
170 | void reallocate(unsigned NewBitWidth); | ||||||||||
171 | |||||||||||
172 | /// Convert a char array into an APInt | ||||||||||
173 | /// | ||||||||||
174 | /// \param radix 2, 8, 10, 16, or 36 | ||||||||||
175 | /// Converts a string into a number. The string must be non-empty | ||||||||||
176 | /// and well-formed as a number of the given base. The bit-width | ||||||||||
177 | /// must be sufficient to hold the result. | ||||||||||
178 | /// | ||||||||||
179 | /// This is used by the constructors that take string arguments. | ||||||||||
180 | /// | ||||||||||
181 | /// StringRef::getAsInteger is superficially similar but (1) does | ||||||||||
182 | /// not assume that the string is well-formed and (2) grows the | ||||||||||
183 | /// result to hold the input. | ||||||||||
184 | void fromString(unsigned numBits, StringRef str, uint8_t radix); | ||||||||||
185 | |||||||||||
186 | /// An internal division function for dividing APInts. | ||||||||||
187 | /// | ||||||||||
188 | /// This is used by the toString method to divide by the radix. It simply | ||||||||||
189 | /// provides a more convenient form of divide for internal use since KnuthDiv | ||||||||||
190 | /// has specific constraints on its inputs. If those constraints are not met | ||||||||||
191 | /// then it provides a simpler form of divide. | ||||||||||
192 | static void divide(const WordType *LHS, unsigned lhsWords, | ||||||||||
193 | const WordType *RHS, unsigned rhsWords, WordType *Quotient, | ||||||||||
194 | WordType *Remainder); | ||||||||||
195 | |||||||||||
196 | /// out-of-line slow case for inline constructor | ||||||||||
197 | void initSlowCase(uint64_t val, bool isSigned); | ||||||||||
198 | |||||||||||
199 | /// shared code between two array constructors | ||||||||||
200 | void initFromArray(ArrayRef<uint64_t> array); | ||||||||||
201 | |||||||||||
202 | /// out-of-line slow case for inline copy constructor | ||||||||||
203 | void initSlowCase(const APInt &that); | ||||||||||
204 | |||||||||||
205 | /// out-of-line slow case for shl | ||||||||||
206 | void shlSlowCase(unsigned ShiftAmt); | ||||||||||
207 | |||||||||||
208 | /// out-of-line slow case for lshr. | ||||||||||
209 | void lshrSlowCase(unsigned ShiftAmt); | ||||||||||
210 | |||||||||||
211 | /// out-of-line slow case for ashr. | ||||||||||
212 | void ashrSlowCase(unsigned ShiftAmt); | ||||||||||
213 | |||||||||||
214 | /// out-of-line slow case for operator= | ||||||||||
215 | void AssignSlowCase(const APInt &RHS); | ||||||||||
216 | |||||||||||
217 | /// out-of-line slow case for operator== | ||||||||||
218 | bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
219 | |||||||||||
220 | /// out-of-line slow case for countLeadingZeros | ||||||||||
221 | unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
222 | |||||||||||
223 | /// out-of-line slow case for countLeadingOnes. | ||||||||||
224 | unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
225 | |||||||||||
226 | /// out-of-line slow case for countTrailingZeros. | ||||||||||
227 | unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
228 | |||||||||||
229 | /// out-of-line slow case for countTrailingOnes | ||||||||||
230 | unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
231 | |||||||||||
232 | /// out-of-line slow case for countPopulation | ||||||||||
233 | unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
234 | |||||||||||
235 | /// out-of-line slow case for intersects. | ||||||||||
236 | bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
237 | |||||||||||
238 | /// out-of-line slow case for isSubsetOf. | ||||||||||
239 | bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
240 | |||||||||||
241 | /// out-of-line slow case for setBits. | ||||||||||
242 | void setBitsSlowCase(unsigned loBit, unsigned hiBit); | ||||||||||
243 | |||||||||||
244 | /// out-of-line slow case for flipAllBits. | ||||||||||
245 | void flipAllBitsSlowCase(); | ||||||||||
246 | |||||||||||
247 | /// out-of-line slow case for operator&=. | ||||||||||
248 | void AndAssignSlowCase(const APInt& RHS); | ||||||||||
249 | |||||||||||
250 | /// out-of-line slow case for operator|=. | ||||||||||
251 | void OrAssignSlowCase(const APInt& RHS); | ||||||||||
252 | |||||||||||
253 | /// out-of-line slow case for operator^=. | ||||||||||
254 | void XorAssignSlowCase(const APInt& RHS); | ||||||||||
255 | |||||||||||
256 | /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal | ||||||||||
257 | /// to, or greater than RHS. | ||||||||||
258 | int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
259 | |||||||||||
260 | /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal | ||||||||||
261 | /// to, or greater than RHS. | ||||||||||
262 | int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
263 | |||||||||||
264 | public: | ||||||||||
265 | /// \name Constructors | ||||||||||
266 | /// @{ | ||||||||||
267 | |||||||||||
268 | /// Create a new APInt of numBits width, initialized as val. | ||||||||||
269 | /// | ||||||||||
270 | /// If isSigned is true then val is treated as if it were a signed value | ||||||||||
271 | /// (i.e. as an int64_t) and the appropriate sign extension to the bit width | ||||||||||
272 | /// will be done. Otherwise, no sign extension occurs (high order bits beyond | ||||||||||
273 | /// the range of val are zero filled). | ||||||||||
274 | /// | ||||||||||
275 | /// \param numBits the bit width of the constructed APInt | ||||||||||
276 | /// \param val the initial value of the APInt | ||||||||||
277 | /// \param isSigned how to treat signedness of val | ||||||||||
278 | APInt(unsigned numBits, uint64_t val, bool isSigned = false) | ||||||||||
279 | : BitWidth(numBits) { | ||||||||||
280 | assert(BitWidth && "bitwidth too small")((BitWidth && "bitwidth too small") ? static_cast< void> (0) : __assert_fail ("BitWidth && \"bitwidth too small\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 280, __PRETTY_FUNCTION__)); | ||||||||||
281 | if (isSingleWord()) { | ||||||||||
282 | U.VAL = val; | ||||||||||
283 | clearUnusedBits(); | ||||||||||
284 | } else { | ||||||||||
285 | initSlowCase(val, isSigned); | ||||||||||
286 | } | ||||||||||
287 | } | ||||||||||
288 | |||||||||||
289 | /// Construct an APInt of numBits width, initialized as bigVal[]. | ||||||||||
290 | /// | ||||||||||
291 | /// Note that bigVal.size() can be smaller or larger than the corresponding | ||||||||||
292 | /// bit width but any extraneous bits will be dropped. | ||||||||||
293 | /// | ||||||||||
294 | /// \param numBits the bit width of the constructed APInt | ||||||||||
295 | /// \param bigVal a sequence of words to form the initial value of the APInt | ||||||||||
296 | APInt(unsigned numBits, ArrayRef<uint64_t> bigVal); | ||||||||||
297 | |||||||||||
298 | /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but | ||||||||||
299 | /// deprecated because this constructor is prone to ambiguity with the | ||||||||||
300 | /// APInt(unsigned, uint64_t, bool) constructor. | ||||||||||
301 | /// | ||||||||||
302 | /// If this overload is ever deleted, care should be taken to prevent calls | ||||||||||
303 | /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool) | ||||||||||
304 | /// constructor. | ||||||||||
305 | APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]); | ||||||||||
306 | |||||||||||
307 | /// Construct an APInt from a string representation. | ||||||||||
308 | /// | ||||||||||
309 | /// This constructor interprets the string \p str in the given radix. The | ||||||||||
310 | /// interpretation stops when the first character that is not suitable for the | ||||||||||
311 | /// radix is encountered, or the end of the string. Acceptable radix values | ||||||||||
312 | /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the | ||||||||||
313 | /// string to require more bits than numBits. | ||||||||||
314 | /// | ||||||||||
315 | /// \param numBits the bit width of the constructed APInt | ||||||||||
316 | /// \param str the string to be interpreted | ||||||||||
317 | /// \param radix the radix to use for the conversion | ||||||||||
318 | APInt(unsigned numBits, StringRef str, uint8_t radix); | ||||||||||
319 | |||||||||||
320 | /// Simply makes *this a copy of that. | ||||||||||
321 | /// Copy Constructor. | ||||||||||
322 | APInt(const APInt &that) : BitWidth(that.BitWidth) { | ||||||||||
323 | if (isSingleWord()) | ||||||||||
324 | U.VAL = that.U.VAL; | ||||||||||
325 | else | ||||||||||
326 | initSlowCase(that); | ||||||||||
327 | } | ||||||||||
328 | |||||||||||
329 | /// Move Constructor. | ||||||||||
330 | APInt(APInt &&that) : BitWidth(that.BitWidth) { | ||||||||||
331 | memcpy(&U, &that.U, sizeof(U)); | ||||||||||
332 | that.BitWidth = 0; | ||||||||||
333 | } | ||||||||||
334 | |||||||||||
335 | /// Destructor. | ||||||||||
336 | ~APInt() { | ||||||||||
337 | if (needsCleanup()) | ||||||||||
338 | delete[] U.pVal; | ||||||||||
339 | } | ||||||||||
340 | |||||||||||
341 | /// Default constructor that creates an uninteresting APInt | ||||||||||
342 | /// representing a 1-bit zero value. | ||||||||||
343 | /// | ||||||||||
344 | /// This is useful for object deserialization (pair this with the static | ||||||||||
345 | /// method Read). | ||||||||||
346 | explicit APInt() : BitWidth(1) { U.VAL = 0; } | ||||||||||
347 | |||||||||||
348 | /// Returns whether this instance allocated memory. | ||||||||||
349 | bool needsCleanup() const { return !isSingleWord(); } | ||||||||||
350 | |||||||||||
351 | /// Used to insert APInt objects, or objects that contain APInt objects, into | ||||||||||
352 | /// FoldingSets. | ||||||||||
353 | void Profile(FoldingSetNodeID &id) const; | ||||||||||
354 | |||||||||||
355 | /// @} | ||||||||||
356 | /// \name Value Tests | ||||||||||
357 | /// @{ | ||||||||||
358 | |||||||||||
359 | /// Determine sign of this APInt. | ||||||||||
360 | /// | ||||||||||
361 | /// This tests the high bit of this APInt to determine if it is set. | ||||||||||
362 | /// | ||||||||||
363 | /// \returns true if this APInt is negative, false otherwise | ||||||||||
364 | bool isNegative() const { return (*this)[BitWidth - 1]; } | ||||||||||
365 | |||||||||||
366 | /// Determine if this APInt Value is non-negative (>= 0) | ||||||||||
367 | /// | ||||||||||
368 | /// This tests the high bit of the APInt to determine if it is unset. | ||||||||||
369 | bool isNonNegative() const { return !isNegative(); } | ||||||||||
370 | |||||||||||
371 | /// Determine if sign bit of this APInt is set. | ||||||||||
372 | /// | ||||||||||
373 | /// This tests the high bit of this APInt to determine if it is set. | ||||||||||
374 | /// | ||||||||||
375 | /// \returns true if this APInt has its sign bit set, false otherwise. | ||||||||||
376 | bool isSignBitSet() const { return (*this)[BitWidth-1]; } | ||||||||||
377 | |||||||||||
378 | /// Determine if sign bit of this APInt is clear. | ||||||||||
379 | /// | ||||||||||
380 | /// This tests the high bit of this APInt to determine if it is clear. | ||||||||||
381 | /// | ||||||||||
382 | /// \returns true if this APInt has its sign bit clear, false otherwise. | ||||||||||
383 | bool isSignBitClear() const { return !isSignBitSet(); } | ||||||||||
384 | |||||||||||
385 | /// Determine if this APInt Value is positive. | ||||||||||
386 | /// | ||||||||||
387 | /// This tests if the value of this APInt is positive (> 0). Note | ||||||||||
388 | /// that 0 is not a positive value. | ||||||||||
389 | /// | ||||||||||
390 | /// \returns true if this APInt is positive. | ||||||||||
391 | bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); } | ||||||||||
392 | |||||||||||
393 | /// Determine if this APInt Value is non-positive (<= 0). | ||||||||||
394 | /// | ||||||||||
395 | /// \returns true if this APInt is non-positive. | ||||||||||
396 | bool isNonPositive() const { return !isStrictlyPositive(); } | ||||||||||
397 | |||||||||||
398 | /// Determine if all bits are set | ||||||||||
399 | /// | ||||||||||
400 | /// This checks to see if the value has all bits of the APInt are set or not. | ||||||||||
401 | bool isAllOnesValue() const { | ||||||||||
402 | if (isSingleWord()) | ||||||||||
403 | return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth); | ||||||||||
404 | return countTrailingOnesSlowCase() == BitWidth; | ||||||||||
405 | } | ||||||||||
406 | |||||||||||
407 | /// Determine if all bits are clear | ||||||||||
408 | /// | ||||||||||
409 | /// This checks to see if the value has all bits of the APInt are clear or | ||||||||||
410 | /// not. | ||||||||||
411 | bool isNullValue() const { return !*this; } | ||||||||||
412 | |||||||||||
413 | /// Determine if this is a value of 1. | ||||||||||
414 | /// | ||||||||||
415 | /// This checks to see if the value of this APInt is one. | ||||||||||
416 | bool isOneValue() const { | ||||||||||
417 | if (isSingleWord()) | ||||||||||
418 | return U.VAL == 1; | ||||||||||
419 | return countLeadingZerosSlowCase() == BitWidth - 1; | ||||||||||
420 | } | ||||||||||
421 | |||||||||||
422 | /// Determine if this is the largest unsigned value. | ||||||||||
423 | /// | ||||||||||
424 | /// This checks to see if the value of this APInt is the maximum unsigned | ||||||||||
425 | /// value for the APInt's bit width. | ||||||||||
426 | bool isMaxValue() const { return isAllOnesValue(); } | ||||||||||
427 | |||||||||||
428 | /// Determine if this is the largest signed value. | ||||||||||
429 | /// | ||||||||||
430 | /// This checks to see if the value of this APInt is the maximum signed | ||||||||||
431 | /// value for the APInt's bit width. | ||||||||||
432 | bool isMaxSignedValue() const { | ||||||||||
433 | if (isSingleWord()) | ||||||||||
434 | return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1); | ||||||||||
435 | return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1; | ||||||||||
436 | } | ||||||||||
437 | |||||||||||
438 | /// Determine if this is the smallest unsigned value. | ||||||||||
439 | /// | ||||||||||
440 | /// This checks to see if the value of this APInt is the minimum unsigned | ||||||||||
441 | /// value for the APInt's bit width. | ||||||||||
442 | bool isMinValue() const { return isNullValue(); } | ||||||||||
443 | |||||||||||
444 | /// Determine if this is the smallest signed value. | ||||||||||
445 | /// | ||||||||||
446 | /// This checks to see if the value of this APInt is the minimum signed | ||||||||||
447 | /// value for the APInt's bit width. | ||||||||||
448 | bool isMinSignedValue() const { | ||||||||||
449 | if (isSingleWord()) | ||||||||||
450 | return U.VAL == (WordType(1) << (BitWidth - 1)); | ||||||||||
451 | return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1; | ||||||||||
452 | } | ||||||||||
453 | |||||||||||
454 | /// Check if this APInt has an N-bits unsigned integer value. | ||||||||||
455 | bool isIntN(unsigned N) const { | ||||||||||
456 | assert(N && "N == 0 ???")((N && "N == 0 ???") ? static_cast<void> (0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 456, __PRETTY_FUNCTION__)); | ||||||||||
457 | return getActiveBits() <= N; | ||||||||||
458 | } | ||||||||||
459 | |||||||||||
460 | /// Check if this APInt has an N-bits signed integer value. | ||||||||||
461 | bool isSignedIntN(unsigned N) const { | ||||||||||
462 | assert(N && "N == 0 ???")((N && "N == 0 ???") ? static_cast<void> (0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 462, __PRETTY_FUNCTION__)); | ||||||||||
463 | return getMinSignedBits() <= N; | ||||||||||
464 | } | ||||||||||
465 | |||||||||||
466 | /// Check if this APInt's value is a power of two greater than zero. | ||||||||||
467 | /// | ||||||||||
468 | /// \returns true if the argument APInt value is a power of two > 0. | ||||||||||
469 | bool isPowerOf2() const { | ||||||||||
470 | if (isSingleWord()) | ||||||||||
471 | return isPowerOf2_64(U.VAL); | ||||||||||
472 | return countPopulationSlowCase() == 1; | ||||||||||
473 | } | ||||||||||
474 | |||||||||||
475 | /// Check if the APInt's value is returned by getSignMask. | ||||||||||
476 | /// | ||||||||||
477 | /// \returns true if this is the value returned by getSignMask. | ||||||||||
478 | bool isSignMask() const { return isMinSignedValue(); } | ||||||||||
479 | |||||||||||
480 | /// Convert APInt to a boolean value. | ||||||||||
481 | /// | ||||||||||
482 | /// This converts the APInt to a boolean value as a test against zero. | ||||||||||
483 | bool getBoolValue() const { return !!*this; } | ||||||||||
484 | |||||||||||
485 | /// If this value is smaller than the specified limit, return it, otherwise | ||||||||||
486 | /// return the limit value. This causes the value to saturate to the limit. | ||||||||||
487 | uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const { | ||||||||||
488 | return ugt(Limit) ? Limit : getZExtValue(); | ||||||||||
489 | } | ||||||||||
490 | |||||||||||
491 | /// Check if the APInt consists of a repeated bit pattern. | ||||||||||
492 | /// | ||||||||||
493 | /// e.g. 0x01010101 satisfies isSplat(8). | ||||||||||
494 | /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit | ||||||||||
495 | /// width without remainder. | ||||||||||
496 | bool isSplat(unsigned SplatSizeInBits) const; | ||||||||||
497 | |||||||||||
498 | /// \returns true if this APInt value is a sequence of \param numBits ones | ||||||||||
499 | /// starting at the least significant bit with the remainder zero. | ||||||||||
500 | bool isMask(unsigned numBits) const { | ||||||||||
501 | assert(numBits != 0 && "numBits must be non-zero")((numBits != 0 && "numBits must be non-zero") ? static_cast <void> (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 501, __PRETTY_FUNCTION__)); | ||||||||||
502 | assert(numBits <= BitWidth && "numBits out of range")((numBits <= BitWidth && "numBits out of range") ? static_cast<void> (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 502, __PRETTY_FUNCTION__)); | ||||||||||
503 | if (isSingleWord()) | ||||||||||
504 | return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits)); | ||||||||||
505 | unsigned Ones = countTrailingOnesSlowCase(); | ||||||||||
506 | return (numBits == Ones) && | ||||||||||
507 | ((Ones + countLeadingZerosSlowCase()) == BitWidth); | ||||||||||
508 | } | ||||||||||
509 | |||||||||||
510 | /// \returns true if this APInt is a non-empty sequence of ones starting at | ||||||||||
511 | /// the least significant bit with the remainder zero. | ||||||||||
512 | /// Ex. isMask(0x0000FFFFU) == true. | ||||||||||
513 | bool isMask() const { | ||||||||||
514 | if (isSingleWord()) | ||||||||||
515 | return isMask_64(U.VAL); | ||||||||||
516 | unsigned Ones = countTrailingOnesSlowCase(); | ||||||||||
517 | return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth); | ||||||||||
518 | } | ||||||||||
519 | |||||||||||
520 | /// Return true if this APInt value contains a sequence of ones with | ||||||||||
521 | /// the remainder zero. | ||||||||||
522 | bool isShiftedMask() const { | ||||||||||
523 | if (isSingleWord()) | ||||||||||
524 | return isShiftedMask_64(U.VAL); | ||||||||||
525 | unsigned Ones = countPopulationSlowCase(); | ||||||||||
526 | unsigned LeadZ = countLeadingZerosSlowCase(); | ||||||||||
527 | return (Ones + LeadZ + countTrailingZeros()) == BitWidth; | ||||||||||
528 | } | ||||||||||
529 | |||||||||||
530 | /// @} | ||||||||||
531 | /// \name Value Generators | ||||||||||
532 | /// @{ | ||||||||||
533 | |||||||||||
534 | /// Gets maximum unsigned value of APInt for specific bit width. | ||||||||||
535 | static APInt getMaxValue(unsigned numBits) { | ||||||||||
536 | return getAllOnesValue(numBits); | ||||||||||
537 | } | ||||||||||
538 | |||||||||||
539 | /// Gets maximum signed value of APInt for a specific bit width. | ||||||||||
540 | static APInt getSignedMaxValue(unsigned numBits) { | ||||||||||
541 | APInt API = getAllOnesValue(numBits); | ||||||||||
542 | API.clearBit(numBits - 1); | ||||||||||
543 | return API; | ||||||||||
544 | } | ||||||||||
545 | |||||||||||
546 | /// Gets minimum unsigned value of APInt for a specific bit width. | ||||||||||
547 | static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); } | ||||||||||
548 | |||||||||||
549 | /// Gets minimum signed value of APInt for a specific bit width. | ||||||||||
550 | static APInt getSignedMinValue(unsigned numBits) { | ||||||||||
551 | APInt API(numBits, 0); | ||||||||||
552 | API.setBit(numBits - 1); | ||||||||||
553 | return API; | ||||||||||
554 | } | ||||||||||
555 | |||||||||||
556 | /// Get the SignMask for a specific bit width. | ||||||||||
557 | /// | ||||||||||
558 | /// This is just a wrapper function of getSignedMinValue(), and it helps code | ||||||||||
559 | /// readability when we want to get a SignMask. | ||||||||||
560 | static APInt getSignMask(unsigned BitWidth) { | ||||||||||
561 | return getSignedMinValue(BitWidth); | ||||||||||
562 | } | ||||||||||
563 | |||||||||||
564 | /// Get the all-ones value. | ||||||||||
565 | /// | ||||||||||
566 | /// \returns the all-ones value for an APInt of the specified bit-width. | ||||||||||
567 | static APInt getAllOnesValue(unsigned numBits) { | ||||||||||
568 | return APInt(numBits, WORDTYPE_MAX, true); | ||||||||||
569 | } | ||||||||||
570 | |||||||||||
571 | /// Get the '0' value. | ||||||||||
572 | /// | ||||||||||
573 | /// \returns the '0' value for an APInt of the specified bit-width. | ||||||||||
574 | static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); } | ||||||||||
575 | |||||||||||
576 | /// Compute an APInt containing numBits highbits from this APInt. | ||||||||||
577 | /// | ||||||||||
578 | /// Get an APInt with the same BitWidth as this APInt, just zero mask | ||||||||||
579 | /// the low bits and right shift to the least significant bit. | ||||||||||
580 | /// | ||||||||||
581 | /// \returns the high "numBits" bits of this APInt. | ||||||||||
582 | APInt getHiBits(unsigned numBits) const; | ||||||||||
583 | |||||||||||
584 | /// Compute an APInt containing numBits lowbits from this APInt. | ||||||||||
585 | /// | ||||||||||
586 | /// Get an APInt with the same BitWidth as this APInt, just zero mask | ||||||||||
587 | /// the high bits. | ||||||||||
588 | /// | ||||||||||
589 | /// \returns the low "numBits" bits of this APInt. | ||||||||||
590 | APInt getLoBits(unsigned numBits) const; | ||||||||||
591 | |||||||||||
592 | /// Return an APInt with exactly one bit set in the result. | ||||||||||
593 | static APInt getOneBitSet(unsigned numBits, unsigned BitNo) { | ||||||||||
594 | APInt Res(numBits, 0); | ||||||||||
595 | Res.setBit(BitNo); | ||||||||||
596 | return Res; | ||||||||||
597 | } | ||||||||||
598 | |||||||||||
599 | /// Get a value with a block of bits set. | ||||||||||
600 | /// | ||||||||||
601 | /// Constructs an APInt value that has a contiguous range of bits set. The | ||||||||||
602 | /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other | ||||||||||
603 | /// bits will be zero. For example, with parameters(32, 0, 16) you would get | ||||||||||
604 | /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than | ||||||||||
605 | /// \p hiBit. | ||||||||||
606 | /// | ||||||||||
607 | /// \param numBits the intended bit width of the result | ||||||||||
608 | /// \param loBit the index of the lowest bit set. | ||||||||||
609 | /// \param hiBit the index of the highest bit set. | ||||||||||
610 | /// | ||||||||||
611 | /// \returns An APInt value with the requested bits set. | ||||||||||
612 | static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) { | ||||||||||
613 | assert(loBit <= hiBit && "loBit greater than hiBit")((loBit <= hiBit && "loBit greater than hiBit") ? static_cast <void> (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 613, __PRETTY_FUNCTION__)); | ||||||||||
614 | APInt Res(numBits, 0); | ||||||||||
615 | Res.setBits(loBit, hiBit); | ||||||||||
616 | return Res; | ||||||||||
617 | } | ||||||||||
618 | |||||||||||
619 | /// Wrap version of getBitsSet. | ||||||||||
620 | /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet. | ||||||||||
621 | /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example, | ||||||||||
622 | /// with parameters (32, 28, 4), you would get 0xF000000F. | ||||||||||
623 | /// If \p hiBit is equal to \p loBit, you would get a result with all bits | ||||||||||
624 | /// set. | ||||||||||
625 | static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit, | ||||||||||
626 | unsigned hiBit) { | ||||||||||
627 | APInt Res(numBits, 0); | ||||||||||
628 | Res.setBitsWithWrap(loBit, hiBit); | ||||||||||
629 | return Res; | ||||||||||
630 | } | ||||||||||
631 | |||||||||||
632 | /// Get a value with upper bits starting at loBit set. | ||||||||||
633 | /// | ||||||||||
634 | /// Constructs an APInt value that has a contiguous range of bits set. The | ||||||||||
635 | /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other | ||||||||||
636 | /// bits will be zero. For example, with parameters(32, 12) you would get | ||||||||||
637 | /// 0xFFFFF000. | ||||||||||
638 | /// | ||||||||||
639 | /// \param numBits the intended bit width of the result | ||||||||||
640 | /// \param loBit the index of the lowest bit to set. | ||||||||||
641 | /// | ||||||||||
642 | /// \returns An APInt value with the requested bits set. | ||||||||||
643 | static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) { | ||||||||||
644 | APInt Res(numBits, 0); | ||||||||||
645 | Res.setBitsFrom(loBit); | ||||||||||
646 | return Res; | ||||||||||
647 | } | ||||||||||
648 | |||||||||||
649 | /// Get a value with high bits set | ||||||||||
650 | /// | ||||||||||
651 | /// Constructs an APInt value that has the top hiBitsSet bits set. | ||||||||||
652 | /// | ||||||||||
653 | /// \param numBits the bitwidth of the result | ||||||||||
654 | /// \param hiBitsSet the number of high-order bits set in the result. | ||||||||||
655 | static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) { | ||||||||||
656 | APInt Res(numBits, 0); | ||||||||||
657 | Res.setHighBits(hiBitsSet); | ||||||||||
658 | return Res; | ||||||||||
659 | } | ||||||||||
660 | |||||||||||
661 | /// Get a value with low bits set | ||||||||||
662 | /// | ||||||||||
663 | /// Constructs an APInt value that has the bottom loBitsSet bits set. | ||||||||||
664 | /// | ||||||||||
665 | /// \param numBits the bitwidth of the result | ||||||||||
666 | /// \param loBitsSet the number of low-order bits set in the result. | ||||||||||
667 | static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) { | ||||||||||
668 | APInt Res(numBits, 0); | ||||||||||
669 | Res.setLowBits(loBitsSet); | ||||||||||
670 | return Res; | ||||||||||
671 | } | ||||||||||
672 | |||||||||||
673 | /// Return a value containing V broadcasted over NewLen bits. | ||||||||||
674 | static APInt getSplat(unsigned NewLen, const APInt &V); | ||||||||||
675 | |||||||||||
676 | /// Determine if two APInts have the same value, after zero-extending | ||||||||||
677 | /// one of them (if needed!) to ensure that the bit-widths match. | ||||||||||
678 | static bool isSameValue(const APInt &I1, const APInt &I2) { | ||||||||||
679 | if (I1.getBitWidth() == I2.getBitWidth()) | ||||||||||
680 | return I1 == I2; | ||||||||||
681 | |||||||||||
682 | if (I1.getBitWidth() > I2.getBitWidth()) | ||||||||||
683 | return I1 == I2.zext(I1.getBitWidth()); | ||||||||||
684 | |||||||||||
685 | return I1.zext(I2.getBitWidth()) == I2; | ||||||||||
686 | } | ||||||||||
687 | |||||||||||
688 | /// Overload to compute a hash_code for an APInt value. | ||||||||||
689 | friend hash_code hash_value(const APInt &Arg); | ||||||||||
690 | |||||||||||
691 | /// This function returns a pointer to the internal storage of the APInt. | ||||||||||
692 | /// This is useful for writing out the APInt in binary form without any | ||||||||||
693 | /// conversions. | ||||||||||
694 | const uint64_t *getRawData() const { | ||||||||||
695 | if (isSingleWord()) | ||||||||||
696 | return &U.VAL; | ||||||||||
697 | return &U.pVal[0]; | ||||||||||
698 | } | ||||||||||
699 | |||||||||||
700 | /// @} | ||||||||||
701 | /// \name Unary Operators | ||||||||||
702 | /// @{ | ||||||||||
703 | |||||||||||
704 | /// Postfix increment operator. | ||||||||||
705 | /// | ||||||||||
706 | /// Increments *this by 1. | ||||||||||
707 | /// | ||||||||||
708 | /// \returns a new APInt value representing the original value of *this. | ||||||||||
709 | const APInt operator++(int) { | ||||||||||
710 | APInt API(*this); | ||||||||||
711 | ++(*this); | ||||||||||
712 | return API; | ||||||||||
713 | } | ||||||||||
714 | |||||||||||
715 | /// Prefix increment operator. | ||||||||||
716 | /// | ||||||||||
717 | /// \returns *this incremented by one | ||||||||||
718 | APInt &operator++(); | ||||||||||
719 | |||||||||||
720 | /// Postfix decrement operator. | ||||||||||
721 | /// | ||||||||||
722 | /// Decrements *this by 1. | ||||||||||
723 | /// | ||||||||||
724 | /// \returns a new APInt value representing the original value of *this. | ||||||||||
725 | const APInt operator--(int) { | ||||||||||
726 | APInt API(*this); | ||||||||||
727 | --(*this); | ||||||||||
728 | return API; | ||||||||||
729 | } | ||||||||||
730 | |||||||||||
731 | /// Prefix decrement operator. | ||||||||||
732 | /// | ||||||||||
733 | /// \returns *this decremented by one. | ||||||||||
734 | APInt &operator--(); | ||||||||||
735 | |||||||||||
736 | /// Logical negation operator. | ||||||||||
737 | /// | ||||||||||
738 | /// Performs logical negation operation on this APInt. | ||||||||||
739 | /// | ||||||||||
740 | /// \returns true if *this is zero, false otherwise. | ||||||||||
741 | bool operator!() const { | ||||||||||
742 | if (isSingleWord()) | ||||||||||
743 | return U.VAL == 0; | ||||||||||
744 | return countLeadingZerosSlowCase() == BitWidth; | ||||||||||
745 | } | ||||||||||
746 | |||||||||||
747 | /// @} | ||||||||||
748 | /// \name Assignment Operators | ||||||||||
749 | /// @{ | ||||||||||
750 | |||||||||||
751 | /// Copy assignment operator. | ||||||||||
752 | /// | ||||||||||
753 | /// \returns *this after assignment of RHS. | ||||||||||
754 | APInt &operator=(const APInt &RHS) { | ||||||||||
755 | // If the bitwidths are the same, we can avoid mucking with memory | ||||||||||
756 | if (isSingleWord() && RHS.isSingleWord()) { | ||||||||||
757 | U.VAL = RHS.U.VAL; | ||||||||||
758 | BitWidth = RHS.BitWidth; | ||||||||||
759 | return clearUnusedBits(); | ||||||||||
760 | } | ||||||||||
761 | |||||||||||
762 | AssignSlowCase(RHS); | ||||||||||
763 | return *this; | ||||||||||
764 | } | ||||||||||
765 | |||||||||||
766 | /// Move assignment operator. | ||||||||||
767 | APInt &operator=(APInt &&that) { | ||||||||||
768 | #ifdef EXPENSIVE_CHECKS | ||||||||||
769 | // Some std::shuffle implementations still do self-assignment. | ||||||||||
770 | if (this == &that) | ||||||||||
771 | return *this; | ||||||||||
772 | #endif | ||||||||||
773 | assert(this != &that && "Self-move not supported")((this != &that && "Self-move not supported") ? static_cast <void> (0) : __assert_fail ("this != &that && \"Self-move not supported\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 773, __PRETTY_FUNCTION__)); | ||||||||||
774 | if (!isSingleWord()) | ||||||||||
775 | delete[] U.pVal; | ||||||||||
776 | |||||||||||
777 | // Use memcpy so that type based alias analysis sees both VAL and pVal | ||||||||||
778 | // as modified. | ||||||||||
779 | memcpy(&U, &that.U, sizeof(U)); | ||||||||||
780 | |||||||||||
781 | BitWidth = that.BitWidth; | ||||||||||
782 | that.BitWidth = 0; | ||||||||||
783 | |||||||||||
784 | return *this; | ||||||||||
785 | } | ||||||||||
786 | |||||||||||
787 | /// Assignment operator. | ||||||||||
788 | /// | ||||||||||
789 | /// The RHS value is assigned to *this. If the significant bits in RHS exceed | ||||||||||
790 | /// the bit width, the excess bits are truncated. If the bit width is larger | ||||||||||
791 | /// than 64, the value is zero filled in the unspecified high order bits. | ||||||||||
792 | /// | ||||||||||
793 | /// \returns *this after assignment of RHS value. | ||||||||||
794 | APInt &operator=(uint64_t RHS) { | ||||||||||
795 | if (isSingleWord()) { | ||||||||||
796 | U.VAL = RHS; | ||||||||||
797 | return clearUnusedBits(); | ||||||||||
798 | } | ||||||||||
799 | U.pVal[0] = RHS; | ||||||||||
800 | memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); | ||||||||||
801 | return *this; | ||||||||||
802 | } | ||||||||||
803 | |||||||||||
804 | /// Bitwise AND assignment operator. | ||||||||||
805 | /// | ||||||||||
806 | /// Performs a bitwise AND operation on this APInt and RHS. The result is | ||||||||||
807 | /// assigned to *this. | ||||||||||
808 | /// | ||||||||||
809 | /// \returns *this after ANDing with RHS. | ||||||||||
810 | APInt &operator&=(const APInt &RHS) { | ||||||||||
811 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 811, __PRETTY_FUNCTION__)); | ||||||||||
812 | if (isSingleWord()) | ||||||||||
813 | U.VAL &= RHS.U.VAL; | ||||||||||
814 | else | ||||||||||
815 | AndAssignSlowCase(RHS); | ||||||||||
816 | return *this; | ||||||||||
817 | } | ||||||||||
818 | |||||||||||
819 | /// Bitwise AND assignment operator. | ||||||||||
820 | /// | ||||||||||
821 | /// Performs a bitwise AND operation on this APInt and RHS. RHS is | ||||||||||
822 | /// logically zero-extended or truncated to match the bit-width of | ||||||||||
823 | /// the LHS. | ||||||||||
824 | APInt &operator&=(uint64_t RHS) { | ||||||||||
825 | if (isSingleWord()) { | ||||||||||
826 | U.VAL &= RHS; | ||||||||||
827 | return *this; | ||||||||||
828 | } | ||||||||||
829 | U.pVal[0] &= RHS; | ||||||||||
830 | memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); | ||||||||||
831 | return *this; | ||||||||||
832 | } | ||||||||||
833 | |||||||||||
834 | /// Bitwise OR assignment operator. | ||||||||||
835 | /// | ||||||||||
836 | /// Performs a bitwise OR operation on this APInt and RHS. The result is | ||||||||||
837 | /// assigned *this; | ||||||||||
838 | /// | ||||||||||
839 | /// \returns *this after ORing with RHS. | ||||||||||
840 | APInt &operator|=(const APInt &RHS) { | ||||||||||
841 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 841, __PRETTY_FUNCTION__)); | ||||||||||
842 | if (isSingleWord()) | ||||||||||
843 | U.VAL |= RHS.U.VAL; | ||||||||||
844 | else | ||||||||||
845 | OrAssignSlowCase(RHS); | ||||||||||
846 | return *this; | ||||||||||
847 | } | ||||||||||
848 | |||||||||||
849 | /// Bitwise OR assignment operator. | ||||||||||
850 | /// | ||||||||||
851 | /// Performs a bitwise OR operation on this APInt and RHS. RHS is | ||||||||||
852 | /// logically zero-extended or truncated to match the bit-width of | ||||||||||
853 | /// the LHS. | ||||||||||
854 | APInt &operator|=(uint64_t RHS) { | ||||||||||
855 | if (isSingleWord()) { | ||||||||||
856 | U.VAL |= RHS; | ||||||||||
857 | return clearUnusedBits(); | ||||||||||
858 | } | ||||||||||
859 | U.pVal[0] |= RHS; | ||||||||||
860 | return *this; | ||||||||||
861 | } | ||||||||||
862 | |||||||||||
863 | /// Bitwise XOR assignment operator. | ||||||||||
864 | /// | ||||||||||
865 | /// Performs a bitwise XOR operation on this APInt and RHS. The result is | ||||||||||
866 | /// assigned to *this. | ||||||||||
867 | /// | ||||||||||
868 | /// \returns *this after XORing with RHS. | ||||||||||
869 | APInt &operator^=(const APInt &RHS) { | ||||||||||
870 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 870, __PRETTY_FUNCTION__)); | ||||||||||
871 | if (isSingleWord()) | ||||||||||
872 | U.VAL ^= RHS.U.VAL; | ||||||||||
873 | else | ||||||||||
874 | XorAssignSlowCase(RHS); | ||||||||||
875 | return *this; | ||||||||||
876 | } | ||||||||||
877 | |||||||||||
878 | /// Bitwise XOR assignment operator. | ||||||||||
879 | /// | ||||||||||
880 | /// Performs a bitwise XOR operation on this APInt and RHS. RHS is | ||||||||||
881 | /// logically zero-extended or truncated to match the bit-width of | ||||||||||
882 | /// the LHS. | ||||||||||
883 | APInt &operator^=(uint64_t RHS) { | ||||||||||
884 | if (isSingleWord()) { | ||||||||||
885 | U.VAL ^= RHS; | ||||||||||
886 | return clearUnusedBits(); | ||||||||||
887 | } | ||||||||||
888 | U.pVal[0] ^= RHS; | ||||||||||
889 | return *this; | ||||||||||
890 | } | ||||||||||
891 | |||||||||||
892 | /// Multiplication assignment operator. | ||||||||||
893 | /// | ||||||||||
894 | /// Multiplies this APInt by RHS and assigns the result to *this. | ||||||||||
895 | /// | ||||||||||
896 | /// \returns *this | ||||||||||
897 | APInt &operator*=(const APInt &RHS); | ||||||||||
898 | APInt &operator*=(uint64_t RHS); | ||||||||||
899 | |||||||||||
900 | /// Addition assignment operator. | ||||||||||
901 | /// | ||||||||||
902 | /// Adds RHS to *this and assigns the result to *this. | ||||||||||
903 | /// | ||||||||||
904 | /// \returns *this | ||||||||||
905 | APInt &operator+=(const APInt &RHS); | ||||||||||
906 | APInt &operator+=(uint64_t RHS); | ||||||||||
907 | |||||||||||
908 | /// Subtraction assignment operator. | ||||||||||
909 | /// | ||||||||||
910 | /// Subtracts RHS from *this and assigns the result to *this. | ||||||||||
911 | /// | ||||||||||
912 | /// \returns *this | ||||||||||
913 | APInt &operator-=(const APInt &RHS); | ||||||||||
914 | APInt &operator-=(uint64_t RHS); | ||||||||||
915 | |||||||||||
916 | /// Left-shift assignment function. | ||||||||||
917 | /// | ||||||||||
918 | /// Shifts *this left by shiftAmt and assigns the result to *this. | ||||||||||
919 | /// | ||||||||||
920 | /// \returns *this after shifting left by ShiftAmt | ||||||||||
921 | APInt &operator<<=(unsigned ShiftAmt) { | ||||||||||
922 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 922, __PRETTY_FUNCTION__)); | ||||||||||
923 | if (isSingleWord()) { | ||||||||||
924 | if (ShiftAmt == BitWidth) | ||||||||||
925 | U.VAL = 0; | ||||||||||
926 | else | ||||||||||
927 | U.VAL <<= ShiftAmt; | ||||||||||
928 | return clearUnusedBits(); | ||||||||||
929 | } | ||||||||||
930 | shlSlowCase(ShiftAmt); | ||||||||||
931 | return *this; | ||||||||||
932 | } | ||||||||||
933 | |||||||||||
934 | /// Left-shift assignment function. | ||||||||||
935 | /// | ||||||||||
936 | /// Shifts *this left by shiftAmt and assigns the result to *this. | ||||||||||
937 | /// | ||||||||||
938 | /// \returns *this after shifting left by ShiftAmt | ||||||||||
939 | APInt &operator<<=(const APInt &ShiftAmt); | ||||||||||
940 | |||||||||||
941 | /// @} | ||||||||||
942 | /// \name Binary Operators | ||||||||||
943 | /// @{ | ||||||||||
944 | |||||||||||
945 | /// Multiplication operator. | ||||||||||
946 | /// | ||||||||||
947 | /// Multiplies this APInt by RHS and returns the result. | ||||||||||
948 | APInt operator*(const APInt &RHS) const; | ||||||||||
949 | |||||||||||
950 | /// Left logical shift operator. | ||||||||||
951 | /// | ||||||||||
952 | /// Shifts this APInt left by \p Bits and returns the result. | ||||||||||
953 | APInt operator<<(unsigned Bits) const { return shl(Bits); } | ||||||||||
954 | |||||||||||
955 | /// Left logical shift operator. | ||||||||||
956 | /// | ||||||||||
957 | /// Shifts this APInt left by \p Bits and returns the result. | ||||||||||
958 | APInt operator<<(const APInt &Bits) const { return shl(Bits); } | ||||||||||
959 | |||||||||||
960 | /// Arithmetic right-shift function. | ||||||||||
961 | /// | ||||||||||
962 | /// Arithmetic right-shift this APInt by shiftAmt. | ||||||||||
963 | APInt ashr(unsigned ShiftAmt) const { | ||||||||||
964 | APInt R(*this); | ||||||||||
965 | R.ashrInPlace(ShiftAmt); | ||||||||||
966 | return R; | ||||||||||
967 | } | ||||||||||
968 | |||||||||||
969 | /// Arithmetic right-shift this APInt by ShiftAmt in place. | ||||||||||
970 | void ashrInPlace(unsigned ShiftAmt) { | ||||||||||
971 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 971, __PRETTY_FUNCTION__)); | ||||||||||
972 | if (isSingleWord()) { | ||||||||||
973 | int64_t SExtVAL = SignExtend64(U.VAL, BitWidth); | ||||||||||
974 | if (ShiftAmt == BitWidth) | ||||||||||
975 | U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit. | ||||||||||
976 | else | ||||||||||
977 | U.VAL = SExtVAL >> ShiftAmt; | ||||||||||
978 | clearUnusedBits(); | ||||||||||
979 | return; | ||||||||||
980 | } | ||||||||||
981 | ashrSlowCase(ShiftAmt); | ||||||||||
982 | } | ||||||||||
983 | |||||||||||
984 | /// Logical right-shift function. | ||||||||||
985 | /// | ||||||||||
986 | /// Logical right-shift this APInt by shiftAmt. | ||||||||||
987 | APInt lshr(unsigned shiftAmt) const { | ||||||||||
988 | APInt R(*this); | ||||||||||
989 | R.lshrInPlace(shiftAmt); | ||||||||||
990 | return R; | ||||||||||
991 | } | ||||||||||
992 | |||||||||||
993 | /// Logical right-shift this APInt by ShiftAmt in place. | ||||||||||
994 | void lshrInPlace(unsigned ShiftAmt) { | ||||||||||
995 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 995, __PRETTY_FUNCTION__)); | ||||||||||
996 | if (isSingleWord()) { | ||||||||||
997 | if (ShiftAmt == BitWidth) | ||||||||||
998 | U.VAL = 0; | ||||||||||
999 | else | ||||||||||
1000 | U.VAL >>= ShiftAmt; | ||||||||||
1001 | return; | ||||||||||
1002 | } | ||||||||||
1003 | lshrSlowCase(ShiftAmt); | ||||||||||
1004 | } | ||||||||||
1005 | |||||||||||
1006 | /// Left-shift function. | ||||||||||
1007 | /// | ||||||||||
1008 | /// Left-shift this APInt by shiftAmt. | ||||||||||
1009 | APInt shl(unsigned shiftAmt) const { | ||||||||||
1010 | APInt R(*this); | ||||||||||
1011 | R <<= shiftAmt; | ||||||||||
1012 | return R; | ||||||||||
1013 | } | ||||||||||
1014 | |||||||||||
1015 | /// Rotate left by rotateAmt. | ||||||||||
1016 | APInt rotl(unsigned rotateAmt) const; | ||||||||||
1017 | |||||||||||
1018 | /// Rotate right by rotateAmt. | ||||||||||
1019 | APInt rotr(unsigned rotateAmt) const; | ||||||||||
1020 | |||||||||||
1021 | /// Arithmetic right-shift function. | ||||||||||
1022 | /// | ||||||||||
1023 | /// Arithmetic right-shift this APInt by shiftAmt. | ||||||||||
1024 | APInt ashr(const APInt &ShiftAmt) const { | ||||||||||
1025 | APInt R(*this); | ||||||||||
1026 | R.ashrInPlace(ShiftAmt); | ||||||||||
1027 | return R; | ||||||||||
1028 | } | ||||||||||
1029 | |||||||||||
1030 | /// Arithmetic right-shift this APInt by shiftAmt in place. | ||||||||||
1031 | void ashrInPlace(const APInt &shiftAmt); | ||||||||||
1032 | |||||||||||
1033 | /// Logical right-shift function. | ||||||||||
1034 | /// | ||||||||||
1035 | /// Logical right-shift this APInt by shiftAmt. | ||||||||||
1036 | APInt lshr(const APInt &ShiftAmt) const { | ||||||||||
1037 | APInt R(*this); | ||||||||||
1038 | R.lshrInPlace(ShiftAmt); | ||||||||||
1039 | return R; | ||||||||||
1040 | } | ||||||||||
1041 | |||||||||||
1042 | /// Logical right-shift this APInt by ShiftAmt in place. | ||||||||||
1043 | void lshrInPlace(const APInt &ShiftAmt); | ||||||||||
1044 | |||||||||||
1045 | /// Left-shift function. | ||||||||||
1046 | /// | ||||||||||
1047 | /// Left-shift this APInt by shiftAmt. | ||||||||||
1048 | APInt shl(const APInt &ShiftAmt) const { | ||||||||||
1049 | APInt R(*this); | ||||||||||
1050 | R <<= ShiftAmt; | ||||||||||
1051 | return R; | ||||||||||
1052 | } | ||||||||||
1053 | |||||||||||
1054 | /// Rotate left by rotateAmt. | ||||||||||
1055 | APInt rotl(const APInt &rotateAmt) const; | ||||||||||
1056 | |||||||||||
1057 | /// Rotate right by rotateAmt. | ||||||||||
1058 | APInt rotr(const APInt &rotateAmt) const; | ||||||||||
1059 | |||||||||||
1060 | /// Unsigned division operation. | ||||||||||
1061 | /// | ||||||||||
1062 | /// Perform an unsigned divide operation on this APInt by RHS. Both this and | ||||||||||
1063 | /// RHS are treated as unsigned quantities for purposes of this division. | ||||||||||
1064 | /// | ||||||||||
1065 | /// \returns a new APInt value containing the division result, rounded towards | ||||||||||
1066 | /// zero. | ||||||||||
1067 | APInt udiv(const APInt &RHS) const; | ||||||||||
1068 | APInt udiv(uint64_t RHS) const; | ||||||||||
1069 | |||||||||||
1070 | /// Signed division function for APInt. | ||||||||||
1071 | /// | ||||||||||
1072 | /// Signed divide this APInt by APInt RHS. | ||||||||||
1073 | /// | ||||||||||
1074 | /// The result is rounded towards zero. | ||||||||||
1075 | APInt sdiv(const APInt &RHS) const; | ||||||||||
1076 | APInt sdiv(int64_t RHS) const; | ||||||||||
1077 | |||||||||||
1078 | /// Unsigned remainder operation. | ||||||||||
1079 | /// | ||||||||||
1080 | /// Perform an unsigned remainder operation on this APInt with RHS being the | ||||||||||
1081 | /// divisor. Both this and RHS are treated as unsigned quantities for purposes | ||||||||||
1082 | /// of this operation. Note that this is a true remainder operation and not a | ||||||||||
1083 | /// modulo operation because the sign follows the sign of the dividend which | ||||||||||
1084 | /// is *this. | ||||||||||
1085 | /// | ||||||||||
1086 | /// \returns a new APInt value containing the remainder result | ||||||||||
1087 | APInt urem(const APInt &RHS) const; | ||||||||||
1088 | uint64_t urem(uint64_t RHS) const; | ||||||||||
1089 | |||||||||||
1090 | /// Function for signed remainder operation. | ||||||||||
1091 | /// | ||||||||||
1092 | /// Signed remainder operation on APInt. | ||||||||||
1093 | APInt srem(const APInt &RHS) const; | ||||||||||
1094 | int64_t srem(int64_t RHS) const; | ||||||||||
1095 | |||||||||||
1096 | /// Dual division/remainder interface. | ||||||||||
1097 | /// | ||||||||||
1098 | /// Sometimes it is convenient to divide two APInt values and obtain both the | ||||||||||
1099 | /// quotient and remainder. This function does both operations in the same | ||||||||||
1100 | /// computation making it a little more efficient. The pair of input arguments | ||||||||||
1101 | /// may overlap with the pair of output arguments. It is safe to call | ||||||||||
1102 | /// udivrem(X, Y, X, Y), for example. | ||||||||||
1103 | static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, | ||||||||||
1104 | APInt &Remainder); | ||||||||||
1105 | static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient, | ||||||||||
1106 | uint64_t &Remainder); | ||||||||||
1107 | |||||||||||
1108 | static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, | ||||||||||
1109 | APInt &Remainder); | ||||||||||
1110 | static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient, | ||||||||||
1111 | int64_t &Remainder); | ||||||||||
1112 | |||||||||||
1113 | // Operations that return overflow indicators. | ||||||||||
1114 | APInt sadd_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1115 | APInt uadd_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1116 | APInt ssub_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1117 | APInt usub_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1118 | APInt sdiv_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1119 | APInt smul_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1120 | APInt umul_ov(const APInt &RHS, bool &Overflow) const; | ||||||||||
1121 | APInt sshl_ov(const APInt &Amt, bool &Overflow) const; | ||||||||||
1122 | APInt ushl_ov(const APInt &Amt, bool &Overflow) const; | ||||||||||
1123 | |||||||||||
1124 | // Operations that saturate | ||||||||||
1125 | APInt sadd_sat(const APInt &RHS) const; | ||||||||||
1126 | APInt uadd_sat(const APInt &RHS) const; | ||||||||||
1127 | APInt ssub_sat(const APInt &RHS) const; | ||||||||||
1128 | APInt usub_sat(const APInt &RHS) const; | ||||||||||
1129 | APInt smul_sat(const APInt &RHS) const; | ||||||||||
1130 | APInt umul_sat(const APInt &RHS) const; | ||||||||||
1131 | APInt sshl_sat(const APInt &RHS) const; | ||||||||||
1132 | APInt ushl_sat(const APInt &RHS) const; | ||||||||||
1133 | |||||||||||
1134 | /// Array-indexing support. | ||||||||||
1135 | /// | ||||||||||
1136 | /// \returns the bit value at bitPosition | ||||||||||
1137 | bool operator[](unsigned bitPosition) const { | ||||||||||
1138 | assert(bitPosition < getBitWidth() && "Bit position out of bounds!")((bitPosition < getBitWidth() && "Bit position out of bounds!" ) ? static_cast<void> (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1138, __PRETTY_FUNCTION__)); | ||||||||||
1139 | return (maskBit(bitPosition) & getWord(bitPosition)) != 0; | ||||||||||
1140 | } | ||||||||||
1141 | |||||||||||
1142 | /// @} | ||||||||||
1143 | /// \name Comparison Operators | ||||||||||
1144 | /// @{ | ||||||||||
1145 | |||||||||||
1146 | /// Equality operator. | ||||||||||
1147 | /// | ||||||||||
1148 | /// Compares this APInt with RHS for the validity of the equality | ||||||||||
1149 | /// relationship. | ||||||||||
1150 | bool operator==(const APInt &RHS) const { | ||||||||||
1151 | assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")((BitWidth == RHS.BitWidth && "Comparison requires equal bit widths" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1151, __PRETTY_FUNCTION__)); | ||||||||||
1152 | if (isSingleWord()) | ||||||||||
1153 | return U.VAL == RHS.U.VAL; | ||||||||||
1154 | return EqualSlowCase(RHS); | ||||||||||
1155 | } | ||||||||||
1156 | |||||||||||
1157 | /// Equality operator. | ||||||||||
1158 | /// | ||||||||||
1159 | /// Compares this APInt with a uint64_t for the validity of the equality | ||||||||||
1160 | /// relationship. | ||||||||||
1161 | /// | ||||||||||
1162 | /// \returns true if *this == Val | ||||||||||
1163 | bool operator==(uint64_t Val) const { | ||||||||||
1164 | return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val; | ||||||||||
1165 | } | ||||||||||
1166 | |||||||||||
1167 | /// Equality comparison. | ||||||||||
1168 | /// | ||||||||||
1169 | /// Compares this APInt with RHS for the validity of the equality | ||||||||||
1170 | /// relationship. | ||||||||||
1171 | /// | ||||||||||
1172 | /// \returns true if *this == Val | ||||||||||
1173 | bool eq(const APInt &RHS) const { return (*this) == RHS; } | ||||||||||
1174 | |||||||||||
1175 | /// Inequality operator. | ||||||||||
1176 | /// | ||||||||||
1177 | /// Compares this APInt with RHS for the validity of the inequality | ||||||||||
1178 | /// relationship. | ||||||||||
1179 | /// | ||||||||||
1180 | /// \returns true if *this != Val | ||||||||||
1181 | bool operator!=(const APInt &RHS) const { return !((*this) == RHS); } | ||||||||||
1182 | |||||||||||
1183 | /// Inequality operator. | ||||||||||
1184 | /// | ||||||||||
1185 | /// Compares this APInt with a uint64_t for the validity of the inequality | ||||||||||
1186 | /// relationship. | ||||||||||
1187 | /// | ||||||||||
1188 | /// \returns true if *this != Val | ||||||||||
1189 | bool operator!=(uint64_t Val) const { return !((*this) == Val); } | ||||||||||
1190 | |||||||||||
1191 | /// Inequality comparison | ||||||||||
1192 | /// | ||||||||||
1193 | /// Compares this APInt with RHS for the validity of the inequality | ||||||||||
1194 | /// relationship. | ||||||||||
1195 | /// | ||||||||||
1196 | /// \returns true if *this != Val | ||||||||||
1197 | bool ne(const APInt &RHS) const { return !((*this) == RHS); } | ||||||||||
1198 | |||||||||||
1199 | /// Unsigned less than comparison | ||||||||||
1200 | /// | ||||||||||
1201 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||||||
1202 | /// the validity of the less-than relationship. | ||||||||||
1203 | /// | ||||||||||
1204 | /// \returns true if *this < RHS when both are considered unsigned. | ||||||||||
1205 | bool ult(const APInt &RHS) const { return compare(RHS) < 0; } | ||||||||||
1206 | |||||||||||
1207 | /// Unsigned less than comparison | ||||||||||
1208 | /// | ||||||||||
1209 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||||||
1210 | /// the validity of the less-than relationship. | ||||||||||
1211 | /// | ||||||||||
1212 | /// \returns true if *this < RHS when considered unsigned. | ||||||||||
1213 | bool ult(uint64_t RHS) const { | ||||||||||
1214 | // Only need to check active bits if not a single word. | ||||||||||
1215 | return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS; | ||||||||||
1216 | } | ||||||||||
1217 | |||||||||||
1218 | /// Signed less than comparison | ||||||||||
1219 | /// | ||||||||||
1220 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||||||
1221 | /// validity of the less-than relationship. | ||||||||||
1222 | /// | ||||||||||
1223 | /// \returns true if *this < RHS when both are considered signed. | ||||||||||
1224 | bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; } | ||||||||||
1225 | |||||||||||
1226 | /// Signed less than comparison | ||||||||||
1227 | /// | ||||||||||
1228 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||||||
1229 | /// the validity of the less-than relationship. | ||||||||||
1230 | /// | ||||||||||
1231 | /// \returns true if *this < RHS when considered signed. | ||||||||||
1232 | bool slt(int64_t RHS) const { | ||||||||||
1233 | return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative() | ||||||||||
1234 | : getSExtValue() < RHS; | ||||||||||
1235 | } | ||||||||||
1236 | |||||||||||
1237 | /// Unsigned less or equal comparison | ||||||||||
1238 | /// | ||||||||||
1239 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||||||
1240 | /// validity of the less-or-equal relationship. | ||||||||||
1241 | /// | ||||||||||
1242 | /// \returns true if *this <= RHS when both are considered unsigned. | ||||||||||
1243 | bool ule(const APInt &RHS) const { return compare(RHS) <= 0; } | ||||||||||
1244 | |||||||||||
1245 | /// Unsigned less or equal comparison | ||||||||||
1246 | /// | ||||||||||
1247 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||||||
1248 | /// the validity of the less-or-equal relationship. | ||||||||||
1249 | /// | ||||||||||
1250 | /// \returns true if *this <= RHS when considered unsigned. | ||||||||||
1251 | bool ule(uint64_t RHS) const { return !ugt(RHS); } | ||||||||||
1252 | |||||||||||
1253 | /// Signed less or equal comparison | ||||||||||
1254 | /// | ||||||||||
1255 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||||||
1256 | /// validity of the less-or-equal relationship. | ||||||||||
1257 | /// | ||||||||||
1258 | /// \returns true if *this <= RHS when both are considered signed. | ||||||||||
1259 | bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; } | ||||||||||
1260 | |||||||||||
1261 | /// Signed less or equal comparison | ||||||||||
1262 | /// | ||||||||||
1263 | /// Regards both *this as a signed quantity and compares it with RHS for the | ||||||||||
1264 | /// validity of the less-or-equal relationship. | ||||||||||
1265 | /// | ||||||||||
1266 | /// \returns true if *this <= RHS when considered signed. | ||||||||||
1267 | bool sle(uint64_t RHS) const { return !sgt(RHS); } | ||||||||||
1268 | |||||||||||
1269 | /// Unsigned greater than comparison | ||||||||||
1270 | /// | ||||||||||
1271 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||||||
1272 | /// the validity of the greater-than relationship. | ||||||||||
1273 | /// | ||||||||||
1274 | /// \returns true if *this > RHS when both are considered unsigned. | ||||||||||
1275 | bool ugt(const APInt &RHS) const { return !ule(RHS); } | ||||||||||
1276 | |||||||||||
1277 | /// Unsigned greater than comparison | ||||||||||
1278 | /// | ||||||||||
1279 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||||||
1280 | /// the validity of the greater-than relationship. | ||||||||||
1281 | /// | ||||||||||
1282 | /// \returns true if *this > RHS when considered unsigned. | ||||||||||
1283 | bool ugt(uint64_t RHS) const { | ||||||||||
1284 | // Only need to check active bits if not a single word. | ||||||||||
1285 | return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS; | ||||||||||
1286 | } | ||||||||||
1287 | |||||||||||
1288 | /// Signed greater than comparison | ||||||||||
1289 | /// | ||||||||||
1290 | /// Regards both *this and RHS as signed quantities and compares them for the | ||||||||||
1291 | /// validity of the greater-than relationship. | ||||||||||
1292 | /// | ||||||||||
1293 | /// \returns true if *this > RHS when both are considered signed. | ||||||||||
1294 | bool sgt(const APInt &RHS) const { return !sle(RHS); } | ||||||||||
1295 | |||||||||||
1296 | /// Signed greater than comparison | ||||||||||
1297 | /// | ||||||||||
1298 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||||||
1299 | /// the validity of the greater-than relationship. | ||||||||||
1300 | /// | ||||||||||
1301 | /// \returns true if *this > RHS when considered signed. | ||||||||||
1302 | bool sgt(int64_t RHS) const { | ||||||||||
1303 | return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative() | ||||||||||
1304 | : getSExtValue() > RHS; | ||||||||||
1305 | } | ||||||||||
1306 | |||||||||||
1307 | /// Unsigned greater or equal comparison | ||||||||||
1308 | /// | ||||||||||
1309 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||||||
1310 | /// validity of the greater-or-equal relationship. | ||||||||||
1311 | /// | ||||||||||
1312 | /// \returns true if *this >= RHS when both are considered unsigned. | ||||||||||
1313 | bool uge(const APInt &RHS) const { return !ult(RHS); } | ||||||||||
1314 | |||||||||||
1315 | /// Unsigned greater or equal comparison | ||||||||||
1316 | /// | ||||||||||
1317 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||||||
1318 | /// the validity of the greater-or-equal relationship. | ||||||||||
1319 | /// | ||||||||||
1320 | /// \returns true if *this >= RHS when considered unsigned. | ||||||||||
1321 | bool uge(uint64_t RHS) const { return !ult(RHS); } | ||||||||||
1322 | |||||||||||
1323 | /// Signed greater or equal comparison | ||||||||||
1324 | /// | ||||||||||
1325 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||||||
1326 | /// validity of the greater-or-equal relationship. | ||||||||||
1327 | /// | ||||||||||
1328 | /// \returns true if *this >= RHS when both are considered signed. | ||||||||||
1329 | bool sge(const APInt &RHS) const { return !slt(RHS); } | ||||||||||
1330 | |||||||||||
1331 | /// Signed greater or equal comparison | ||||||||||
1332 | /// | ||||||||||
1333 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||||||
1334 | /// the validity of the greater-or-equal relationship. | ||||||||||
1335 | /// | ||||||||||
1336 | /// \returns true if *this >= RHS when considered signed. | ||||||||||
1337 | bool sge(int64_t RHS) const { return !slt(RHS); } | ||||||||||
1338 | |||||||||||
1339 | /// This operation tests if there are any pairs of corresponding bits | ||||||||||
1340 | /// between this APInt and RHS that are both set. | ||||||||||
1341 | bool intersects(const APInt &RHS) const { | ||||||||||
1342 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1342, __PRETTY_FUNCTION__)); | ||||||||||
1343 | if (isSingleWord()) | ||||||||||
1344 | return (U.VAL & RHS.U.VAL) != 0; | ||||||||||
1345 | return intersectsSlowCase(RHS); | ||||||||||
1346 | } | ||||||||||
1347 | |||||||||||
1348 | /// This operation checks that all bits set in this APInt are also set in RHS. | ||||||||||
1349 | bool isSubsetOf(const APInt &RHS) const { | ||||||||||
1350 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1350, __PRETTY_FUNCTION__)); | ||||||||||
1351 | if (isSingleWord()) | ||||||||||
1352 | return (U.VAL & ~RHS.U.VAL) == 0; | ||||||||||
1353 | return isSubsetOfSlowCase(RHS); | ||||||||||
1354 | } | ||||||||||
1355 | |||||||||||
1356 | /// @} | ||||||||||
1357 | /// \name Resizing Operators | ||||||||||
1358 | /// @{ | ||||||||||
1359 | |||||||||||
1360 | /// Truncate to new width. | ||||||||||
1361 | /// | ||||||||||
1362 | /// Truncate the APInt to a specified width. It is an error to specify a width | ||||||||||
1363 | /// that is greater than or equal to the current width. | ||||||||||
1364 | APInt trunc(unsigned width) const; | ||||||||||
1365 | |||||||||||
1366 | /// Truncate to new width with unsigned saturation. | ||||||||||
1367 | /// | ||||||||||
1368 | /// If the APInt, treated as unsigned integer, can be losslessly truncated to | ||||||||||
1369 | /// the new bitwidth, then return truncated APInt. Else, return max value. | ||||||||||
1370 | APInt truncUSat(unsigned width) const; | ||||||||||
1371 | |||||||||||
1372 | /// Truncate to new width with signed saturation. | ||||||||||
1373 | /// | ||||||||||
1374 | /// If this APInt, treated as signed integer, can be losslessly truncated to | ||||||||||
1375 | /// the new bitwidth, then return truncated APInt. Else, return either | ||||||||||
1376 | /// signed min value if the APInt was negative, or signed max value. | ||||||||||
1377 | APInt truncSSat(unsigned width) const; | ||||||||||
1378 | |||||||||||
1379 | /// Sign extend to a new width. | ||||||||||
1380 | /// | ||||||||||
1381 | /// This operation sign extends the APInt to a new width. If the high order | ||||||||||
1382 | /// bit is set, the fill on the left will be done with 1 bits, otherwise zero. | ||||||||||
1383 | /// It is an error to specify a width that is less than or equal to the | ||||||||||
1384 | /// current width. | ||||||||||
1385 | APInt sext(unsigned width) const; | ||||||||||
1386 | |||||||||||
1387 | /// Zero extend to a new width. | ||||||||||
1388 | /// | ||||||||||
1389 | /// This operation zero extends the APInt to a new width. The high order bits | ||||||||||
1390 | /// are filled with 0 bits. It is an error to specify a width that is less | ||||||||||
1391 | /// than or equal to the current width. | ||||||||||
1392 | APInt zext(unsigned width) const; | ||||||||||
1393 | |||||||||||
1394 | /// Sign extend or truncate to width | ||||||||||
1395 | /// | ||||||||||
1396 | /// Make this APInt have the bit width given by \p width. The value is sign | ||||||||||
1397 | /// extended, truncated, or left alone to make it that width. | ||||||||||
1398 | APInt sextOrTrunc(unsigned width) const; | ||||||||||
1399 | |||||||||||
1400 | /// Zero extend or truncate to width | ||||||||||
1401 | /// | ||||||||||
1402 | /// Make this APInt have the bit width given by \p width. The value is zero | ||||||||||
1403 | /// extended, truncated, or left alone to make it that width. | ||||||||||
1404 | APInt zextOrTrunc(unsigned width) const; | ||||||||||
1405 | |||||||||||
1406 | /// Sign extend or truncate to width | ||||||||||
1407 | /// | ||||||||||
1408 | /// Make this APInt have the bit width given by \p width. The value is sign | ||||||||||
1409 | /// extended, or left alone to make it that width. | ||||||||||
1410 | APInt sextOrSelf(unsigned width) const; | ||||||||||
1411 | |||||||||||
1412 | /// Zero extend or truncate to width | ||||||||||
1413 | /// | ||||||||||
1414 | /// Make this APInt have the bit width given by \p width. The value is zero | ||||||||||
1415 | /// extended, or left alone to make it that width. | ||||||||||
1416 | APInt zextOrSelf(unsigned width) const; | ||||||||||
1417 | |||||||||||
1418 | /// @} | ||||||||||
1419 | /// \name Bit Manipulation Operators | ||||||||||
1420 | /// @{ | ||||||||||
1421 | |||||||||||
1422 | /// Set every bit to 1. | ||||||||||
1423 | void setAllBits() { | ||||||||||
1424 | if (isSingleWord()) | ||||||||||
1425 | U.VAL = WORDTYPE_MAX; | ||||||||||
1426 | else | ||||||||||
1427 | // Set all the bits in all the words. | ||||||||||
1428 | memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE); | ||||||||||
1429 | // Clear the unused ones | ||||||||||
1430 | clearUnusedBits(); | ||||||||||
1431 | } | ||||||||||
1432 | |||||||||||
1433 | /// Set a given bit to 1. | ||||||||||
1434 | /// | ||||||||||
1435 | /// Set the given bit to 1 whose position is given as "bitPosition". | ||||||||||
1436 | void setBit(unsigned BitPosition) { | ||||||||||
1437 | assert(BitPosition < BitWidth && "BitPosition out of range")((BitPosition < BitWidth && "BitPosition out of range" ) ? static_cast<void> (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1437, __PRETTY_FUNCTION__)); | ||||||||||
1438 | WordType Mask = maskBit(BitPosition); | ||||||||||
1439 | if (isSingleWord()) | ||||||||||
1440 | U.VAL |= Mask; | ||||||||||
1441 | else | ||||||||||
1442 | U.pVal[whichWord(BitPosition)] |= Mask; | ||||||||||
1443 | } | ||||||||||
1444 | |||||||||||
1445 | /// Set the sign bit to 1. | ||||||||||
1446 | void setSignBit() { | ||||||||||
1447 | setBit(BitWidth - 1); | ||||||||||
1448 | } | ||||||||||
1449 | |||||||||||
1450 | /// Set a given bit to a given value. | ||||||||||
1451 | void setBitVal(unsigned BitPosition, bool BitValue) { | ||||||||||
1452 | if (BitValue) | ||||||||||
1453 | setBit(BitPosition); | ||||||||||
1454 | else | ||||||||||
1455 | clearBit(BitPosition); | ||||||||||
1456 | } | ||||||||||
1457 | |||||||||||
1458 | /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1. | ||||||||||
1459 | /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls | ||||||||||
1460 | /// setBits when \p loBit < \p hiBit. | ||||||||||
1461 | /// For \p loBit == \p hiBit wrap case, set every bit to 1. | ||||||||||
1462 | void setBitsWithWrap(unsigned loBit, unsigned hiBit) { | ||||||||||
1463 | assert(hiBit <= BitWidth && "hiBit out of range")((hiBit <= BitWidth && "hiBit out of range") ? static_cast <void> (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1463, __PRETTY_FUNCTION__)); | ||||||||||
1464 | assert(loBit <= BitWidth && "loBit out of range")((loBit <= BitWidth && "loBit out of range") ? static_cast <void> (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1464, __PRETTY_FUNCTION__)); | ||||||||||
1465 | if (loBit < hiBit) { | ||||||||||
1466 | setBits(loBit, hiBit); | ||||||||||
1467 | return; | ||||||||||
1468 | } | ||||||||||
1469 | setLowBits(hiBit); | ||||||||||
1470 | setHighBits(BitWidth - loBit); | ||||||||||
1471 | } | ||||||||||
1472 | |||||||||||
1473 | /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1. | ||||||||||
1474 | /// This function handles case when \p loBit <= \p hiBit. | ||||||||||
1475 | void setBits(unsigned loBit, unsigned hiBit) { | ||||||||||
1476 | assert(hiBit <= BitWidth && "hiBit out of range")((hiBit <= BitWidth && "hiBit out of range") ? static_cast <void> (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1476, __PRETTY_FUNCTION__)); | ||||||||||
1477 | assert(loBit <= BitWidth && "loBit out of range")((loBit <= BitWidth && "loBit out of range") ? static_cast <void> (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1477, __PRETTY_FUNCTION__)); | ||||||||||
1478 | assert(loBit <= hiBit && "loBit greater than hiBit")((loBit <= hiBit && "loBit greater than hiBit") ? static_cast <void> (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1478, __PRETTY_FUNCTION__)); | ||||||||||
1479 | if (loBit == hiBit) | ||||||||||
1480 | return; | ||||||||||
1481 | if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) { | ||||||||||
1482 | uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit)); | ||||||||||
1483 | mask <<= loBit; | ||||||||||
1484 | if (isSingleWord()) | ||||||||||
1485 | U.VAL |= mask; | ||||||||||
1486 | else | ||||||||||
1487 | U.pVal[0] |= mask; | ||||||||||
1488 | } else { | ||||||||||
1489 | setBitsSlowCase(loBit, hiBit); | ||||||||||
1490 | } | ||||||||||
1491 | } | ||||||||||
1492 | |||||||||||
1493 | /// Set the top bits starting from loBit. | ||||||||||
1494 | void setBitsFrom(unsigned loBit) { | ||||||||||
1495 | return setBits(loBit, BitWidth); | ||||||||||
1496 | } | ||||||||||
1497 | |||||||||||
1498 | /// Set the bottom loBits bits. | ||||||||||
1499 | void setLowBits(unsigned loBits) { | ||||||||||
1500 | return setBits(0, loBits); | ||||||||||
1501 | } | ||||||||||
1502 | |||||||||||
1503 | /// Set the top hiBits bits. | ||||||||||
1504 | void setHighBits(unsigned hiBits) { | ||||||||||
1505 | return setBits(BitWidth - hiBits, BitWidth); | ||||||||||
1506 | } | ||||||||||
1507 | |||||||||||
1508 | /// Set every bit to 0. | ||||||||||
1509 | void clearAllBits() { | ||||||||||
1510 | if (isSingleWord()) | ||||||||||
1511 | U.VAL = 0; | ||||||||||
1512 | else | ||||||||||
1513 | memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE); | ||||||||||
1514 | } | ||||||||||
1515 | |||||||||||
1516 | /// Set a given bit to 0. | ||||||||||
1517 | /// | ||||||||||
1518 | /// Set the given bit to 0 whose position is given as "bitPosition". | ||||||||||
1519 | void clearBit(unsigned BitPosition) { | ||||||||||
1520 | assert(BitPosition < BitWidth && "BitPosition out of range")((BitPosition < BitWidth && "BitPosition out of range" ) ? static_cast<void> (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1520, __PRETTY_FUNCTION__)); | ||||||||||
1521 | WordType Mask = ~maskBit(BitPosition); | ||||||||||
1522 | if (isSingleWord()) | ||||||||||
1523 | U.VAL &= Mask; | ||||||||||
1524 | else | ||||||||||
1525 | U.pVal[whichWord(BitPosition)] &= Mask; | ||||||||||
1526 | } | ||||||||||
1527 | |||||||||||
1528 | /// Set bottom loBits bits to 0. | ||||||||||
1529 | void clearLowBits(unsigned loBits) { | ||||||||||
1530 | assert(loBits <= BitWidth && "More bits than bitwidth")((loBits <= BitWidth && "More bits than bitwidth") ? static_cast<void> (0) : __assert_fail ("loBits <= BitWidth && \"More bits than bitwidth\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1530, __PRETTY_FUNCTION__)); | ||||||||||
1531 | APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits); | ||||||||||
1532 | *this &= Keep; | ||||||||||
1533 | } | ||||||||||
1534 | |||||||||||
1535 | /// Set the sign bit to 0. | ||||||||||
1536 | void clearSignBit() { | ||||||||||
1537 | clearBit(BitWidth - 1); | ||||||||||
1538 | } | ||||||||||
1539 | |||||||||||
1540 | /// Toggle every bit to its opposite value. | ||||||||||
1541 | void flipAllBits() { | ||||||||||
1542 | if (isSingleWord()) { | ||||||||||
1543 | U.VAL ^= WORDTYPE_MAX; | ||||||||||
1544 | clearUnusedBits(); | ||||||||||
1545 | } else { | ||||||||||
1546 | flipAllBitsSlowCase(); | ||||||||||
1547 | } | ||||||||||
1548 | } | ||||||||||
1549 | |||||||||||
1550 | /// Toggles a given bit to its opposite value. | ||||||||||
1551 | /// | ||||||||||
1552 | /// Toggle a given bit to its opposite value whose position is given | ||||||||||
1553 | /// as "bitPosition". | ||||||||||
1554 | void flipBit(unsigned bitPosition); | ||||||||||
1555 | |||||||||||
1556 | /// Negate this APInt in place. | ||||||||||
1557 | void negate() { | ||||||||||
1558 | flipAllBits(); | ||||||||||
1559 | ++(*this); | ||||||||||
1560 | } | ||||||||||
1561 | |||||||||||
1562 | /// Insert the bits from a smaller APInt starting at bitPosition. | ||||||||||
1563 | void insertBits(const APInt &SubBits, unsigned bitPosition); | ||||||||||
1564 | void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits); | ||||||||||
1565 | |||||||||||
1566 | /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits). | ||||||||||
1567 | APInt extractBits(unsigned numBits, unsigned bitPosition) const; | ||||||||||
1568 | uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const; | ||||||||||
1569 | |||||||||||
1570 | /// @} | ||||||||||
1571 | /// \name Value Characterization Functions | ||||||||||
1572 | /// @{ | ||||||||||
1573 | |||||||||||
1574 | /// Return the number of bits in the APInt. | ||||||||||
1575 | unsigned getBitWidth() const { return BitWidth; } | ||||||||||
1576 | |||||||||||
1577 | /// Get the number of words. | ||||||||||
1578 | /// | ||||||||||
1579 | /// Here one word's bitwidth equals to that of uint64_t. | ||||||||||
1580 | /// | ||||||||||
1581 | /// \returns the number of words to hold the integer value of this APInt. | ||||||||||
1582 | unsigned getNumWords() const { return getNumWords(BitWidth); } | ||||||||||
1583 | |||||||||||
1584 | /// Get the number of words. | ||||||||||
1585 | /// | ||||||||||
1586 | /// *NOTE* Here one word's bitwidth equals to that of uint64_t. | ||||||||||
1587 | /// | ||||||||||
1588 | /// \returns the number of words to hold the integer value with a given bit | ||||||||||
1589 | /// width. | ||||||||||
1590 | static unsigned getNumWords(unsigned BitWidth) { | ||||||||||
1591 | return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; | ||||||||||
1592 | } | ||||||||||
1593 | |||||||||||
1594 | /// Compute the number of active bits in the value | ||||||||||
1595 | /// | ||||||||||
1596 | /// This function returns the number of active bits which is defined as the | ||||||||||
1597 | /// bit width minus the number of leading zeros. This is used in several | ||||||||||
1598 | /// computations to see how "wide" the value is. | ||||||||||
1599 | unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); } | ||||||||||
1600 | |||||||||||
1601 | /// Compute the number of active words in the value of this APInt. | ||||||||||
1602 | /// | ||||||||||
1603 | /// This is used in conjunction with getActiveData to extract the raw value of | ||||||||||
1604 | /// the APInt. | ||||||||||
1605 | unsigned getActiveWords() const { | ||||||||||
1606 | unsigned numActiveBits = getActiveBits(); | ||||||||||
1607 | return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1; | ||||||||||
1608 | } | ||||||||||
1609 | |||||||||||
1610 | /// Get the minimum bit size for this signed APInt | ||||||||||
1611 | /// | ||||||||||
1612 | /// Computes the minimum bit width for this APInt while considering it to be a | ||||||||||
1613 | /// signed (and probably negative) value. If the value is not negative, this | ||||||||||
1614 | /// function returns the same value as getActiveBits()+1. Otherwise, it | ||||||||||
1615 | /// returns the smallest bit width that will retain the negative value. For | ||||||||||
1616 | /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so | ||||||||||
1617 | /// for -1, this function will always return 1. | ||||||||||
1618 | unsigned getMinSignedBits() const { | ||||||||||
1619 | if (isNegative()) | ||||||||||
1620 | return BitWidth - countLeadingOnes() + 1; | ||||||||||
1621 | return getActiveBits() + 1; | ||||||||||
1622 | } | ||||||||||
1623 | |||||||||||
1624 | /// Get zero extended value | ||||||||||
1625 | /// | ||||||||||
1626 | /// This method attempts to return the value of this APInt as a zero extended | ||||||||||
1627 | /// uint64_t. The bitwidth must be <= 64 or the value must fit within a | ||||||||||
1628 | /// uint64_t. Otherwise an assertion will result. | ||||||||||
1629 | uint64_t getZExtValue() const { | ||||||||||
1630 | if (isSingleWord()) | ||||||||||
1631 | return U.VAL; | ||||||||||
1632 | assert(getActiveBits() <= 64 && "Too many bits for uint64_t")((getActiveBits() <= 64 && "Too many bits for uint64_t" ) ? static_cast<void> (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1632, __PRETTY_FUNCTION__)); | ||||||||||
1633 | return U.pVal[0]; | ||||||||||
1634 | } | ||||||||||
1635 | |||||||||||
1636 | /// Get sign extended value | ||||||||||
1637 | /// | ||||||||||
1638 | /// This method attempts to return the value of this APInt as a sign extended | ||||||||||
1639 | /// int64_t. The bit width must be <= 64 or the value must fit within an | ||||||||||
1640 | /// int64_t. Otherwise an assertion will result. | ||||||||||
1641 | int64_t getSExtValue() const { | ||||||||||
1642 | if (isSingleWord()) | ||||||||||
1643 | return SignExtend64(U.VAL, BitWidth); | ||||||||||
1644 | assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")((getMinSignedBits() <= 64 && "Too many bits for int64_t" ) ? static_cast<void> (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1644, __PRETTY_FUNCTION__)); | ||||||||||
1645 | return int64_t(U.pVal[0]); | ||||||||||
1646 | } | ||||||||||
1647 | |||||||||||
1648 | /// Get bits required for string value. | ||||||||||
1649 | /// | ||||||||||
1650 | /// This method determines how many bits are required to hold the APInt | ||||||||||
1651 | /// equivalent of the string given by \p str. | ||||||||||
1652 | static unsigned getBitsNeeded(StringRef str, uint8_t radix); | ||||||||||
1653 | |||||||||||
1654 | /// The APInt version of the countLeadingZeros functions in | ||||||||||
1655 | /// MathExtras.h. | ||||||||||
1656 | /// | ||||||||||
1657 | /// It counts the number of zeros from the most significant bit to the first | ||||||||||
1658 | /// one bit. | ||||||||||
1659 | /// | ||||||||||
1660 | /// \returns BitWidth if the value is zero, otherwise returns the number of | ||||||||||
1661 | /// zeros from the most significant bit to the first one bits. | ||||||||||
1662 | unsigned countLeadingZeros() const { | ||||||||||
1663 | if (isSingleWord()) { | ||||||||||
1664 | unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth; | ||||||||||
1665 | return llvm::countLeadingZeros(U.VAL) - unusedBits; | ||||||||||
1666 | } | ||||||||||
1667 | return countLeadingZerosSlowCase(); | ||||||||||
1668 | } | ||||||||||
1669 | |||||||||||
1670 | /// Count the number of leading one bits. | ||||||||||
1671 | /// | ||||||||||
1672 | /// This function is an APInt version of the countLeadingOnes | ||||||||||
1673 | /// functions in MathExtras.h. It counts the number of ones from the most | ||||||||||
1674 | /// significant bit to the first zero bit. | ||||||||||
1675 | /// | ||||||||||
1676 | /// \returns 0 if the high order bit is not set, otherwise returns the number | ||||||||||
1677 | /// of 1 bits from the most significant to the least | ||||||||||
1678 | unsigned countLeadingOnes() const { | ||||||||||
1679 | if (isSingleWord()) | ||||||||||
1680 | return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth)); | ||||||||||
1681 | return countLeadingOnesSlowCase(); | ||||||||||
1682 | } | ||||||||||
1683 | |||||||||||
1684 | /// Computes the number of leading bits of this APInt that are equal to its | ||||||||||
1685 | /// sign bit. | ||||||||||
1686 | unsigned getNumSignBits() const { | ||||||||||
1687 | return isNegative() ? countLeadingOnes() : countLeadingZeros(); | ||||||||||
1688 | } | ||||||||||
1689 | |||||||||||
1690 | /// Count the number of trailing zero bits. | ||||||||||
1691 | /// | ||||||||||
1692 | /// This function is an APInt version of the countTrailingZeros | ||||||||||
1693 | /// functions in MathExtras.h. It counts the number of zeros from the least | ||||||||||
1694 | /// significant bit to the first set bit. | ||||||||||
1695 | /// | ||||||||||
1696 | /// \returns BitWidth if the value is zero, otherwise returns the number of | ||||||||||
1697 | /// zeros from the least significant bit to the first one bit. | ||||||||||
1698 | unsigned countTrailingZeros() const { | ||||||||||
1699 | if (isSingleWord()) | ||||||||||
1700 | return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth); | ||||||||||
1701 | return countTrailingZerosSlowCase(); | ||||||||||
1702 | } | ||||||||||
1703 | |||||||||||
1704 | /// Count the number of trailing one bits. | ||||||||||
1705 | /// | ||||||||||
1706 | /// This function is an APInt version of the countTrailingOnes | ||||||||||
1707 | /// functions in MathExtras.h. It counts the number of ones from the least | ||||||||||
1708 | /// significant bit to the first zero bit. | ||||||||||
1709 | /// | ||||||||||
1710 | /// \returns BitWidth if the value is all ones, otherwise returns the number | ||||||||||
1711 | /// of ones from the least significant bit to the first zero bit. | ||||||||||
1712 | unsigned countTrailingOnes() const { | ||||||||||
1713 | if (isSingleWord()) | ||||||||||
1714 | return llvm::countTrailingOnes(U.VAL); | ||||||||||
1715 | return countTrailingOnesSlowCase(); | ||||||||||
1716 | } | ||||||||||
1717 | |||||||||||
1718 | /// Count the number of bits set. | ||||||||||
1719 | /// | ||||||||||
1720 | /// This function is an APInt version of the countPopulation functions | ||||||||||
1721 | /// in MathExtras.h. It counts the number of 1 bits in the APInt value. | ||||||||||
1722 | /// | ||||||||||
1723 | /// \returns 0 if the value is zero, otherwise returns the number of set bits. | ||||||||||
1724 | unsigned countPopulation() const { | ||||||||||
1725 | if (isSingleWord()) | ||||||||||
1726 | return llvm::countPopulation(U.VAL); | ||||||||||
1727 | return countPopulationSlowCase(); | ||||||||||
1728 | } | ||||||||||
1729 | |||||||||||
1730 | /// @} | ||||||||||
1731 | /// \name Conversion Functions | ||||||||||
1732 | /// @{ | ||||||||||
1733 | void print(raw_ostream &OS, bool isSigned) const; | ||||||||||
1734 | |||||||||||
1735 | /// Converts an APInt to a string and append it to Str. Str is commonly a | ||||||||||
1736 | /// SmallString. | ||||||||||
1737 | void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed, | ||||||||||
1738 | bool formatAsCLiteral = false) const; | ||||||||||
1739 | |||||||||||
1740 | /// Considers the APInt to be unsigned and converts it into a string in the | ||||||||||
1741 | /// radix given. The radix can be 2, 8, 10 16, or 36. | ||||||||||
1742 | void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { | ||||||||||
1743 | toString(Str, Radix, false, false); | ||||||||||
1744 | } | ||||||||||
1745 | |||||||||||
1746 | /// Considers the APInt to be signed and converts it into a string in the | ||||||||||
1747 | /// radix given. The radix can be 2, 8, 10, 16, or 36. | ||||||||||
1748 | void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { | ||||||||||
1749 | toString(Str, Radix, true, false); | ||||||||||
1750 | } | ||||||||||
1751 | |||||||||||
1752 | /// Return the APInt as a std::string. | ||||||||||
1753 | /// | ||||||||||
1754 | /// Note that this is an inefficient method. It is better to pass in a | ||||||||||
1755 | /// SmallVector/SmallString to the methods above to avoid thrashing the heap | ||||||||||
1756 | /// for the string. | ||||||||||
1757 | std::string toString(unsigned Radix, bool Signed) const; | ||||||||||
1758 | |||||||||||
1759 | /// \returns a byte-swapped representation of this APInt Value. | ||||||||||
1760 | APInt byteSwap() const; | ||||||||||
1761 | |||||||||||
1762 | /// \returns the value with the bit representation reversed of this APInt | ||||||||||
1763 | /// Value. | ||||||||||
1764 | APInt reverseBits() const; | ||||||||||
1765 | |||||||||||
1766 | /// Converts this APInt to a double value. | ||||||||||
1767 | double roundToDouble(bool isSigned) const; | ||||||||||
1768 | |||||||||||
1769 | /// Converts this unsigned APInt to a double value. | ||||||||||
1770 | double roundToDouble() const { return roundToDouble(false); } | ||||||||||
1771 | |||||||||||
1772 | /// Converts this signed APInt to a double value. | ||||||||||
1773 | double signedRoundToDouble() const { return roundToDouble(true); } | ||||||||||
1774 | |||||||||||
1775 | /// Converts APInt bits to a double | ||||||||||
1776 | /// | ||||||||||
1777 | /// The conversion does not do a translation from integer to double, it just | ||||||||||
1778 | /// re-interprets the bits as a double. Note that it is valid to do this on | ||||||||||
1779 | /// any bit width. Exactly 64 bits will be translated. | ||||||||||
1780 | double bitsToDouble() const { | ||||||||||
1781 | return BitsToDouble(getWord(0)); | ||||||||||
1782 | } | ||||||||||
1783 | |||||||||||
1784 | /// Converts APInt bits to a float | ||||||||||
1785 | /// | ||||||||||
1786 | /// The conversion does not do a translation from integer to float, it just | ||||||||||
1787 | /// re-interprets the bits as a float. Note that it is valid to do this on | ||||||||||
1788 | /// any bit width. Exactly 32 bits will be translated. | ||||||||||
1789 | float bitsToFloat() const { | ||||||||||
1790 | return BitsToFloat(static_cast<uint32_t>(getWord(0))); | ||||||||||
1791 | } | ||||||||||
1792 | |||||||||||
1793 | /// Converts a double to APInt bits. | ||||||||||
1794 | /// | ||||||||||
1795 | /// The conversion does not do a translation from double to integer, it just | ||||||||||
1796 | /// re-interprets the bits of the double. | ||||||||||
1797 | static APInt doubleToBits(double V) { | ||||||||||
1798 | return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V)); | ||||||||||
1799 | } | ||||||||||
1800 | |||||||||||
1801 | /// Converts a float to APInt bits. | ||||||||||
1802 | /// | ||||||||||
1803 | /// The conversion does not do a translation from float to integer, it just | ||||||||||
1804 | /// re-interprets the bits of the float. | ||||||||||
1805 | static APInt floatToBits(float V) { | ||||||||||
1806 | return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V)); | ||||||||||
1807 | } | ||||||||||
1808 | |||||||||||
1809 | /// @} | ||||||||||
1810 | /// \name Mathematics Operations | ||||||||||
1811 | /// @{ | ||||||||||
1812 | |||||||||||
1813 | /// \returns the floor log base 2 of this APInt. | ||||||||||
1814 | unsigned logBase2() const { return getActiveBits() - 1; } | ||||||||||
1815 | |||||||||||
1816 | /// \returns the ceil log base 2 of this APInt. | ||||||||||
1817 | unsigned ceilLogBase2() const { | ||||||||||
1818 | APInt temp(*this); | ||||||||||
1819 | --temp; | ||||||||||
1820 | return temp.getActiveBits(); | ||||||||||
1821 | } | ||||||||||
1822 | |||||||||||
1823 | /// \returns the nearest log base 2 of this APInt. Ties round up. | ||||||||||
1824 | /// | ||||||||||
1825 | /// NOTE: When we have a BitWidth of 1, we define: | ||||||||||
1826 | /// | ||||||||||
1827 | /// log2(0) = UINT32_MAX | ||||||||||
1828 | /// log2(1) = 0 | ||||||||||
1829 | /// | ||||||||||
1830 | /// to get around any mathematical concerns resulting from | ||||||||||
1831 | /// referencing 2 in a space where 2 does no exist. | ||||||||||
1832 | unsigned nearestLogBase2() const { | ||||||||||
1833 | // Special case when we have a bitwidth of 1. If VAL is 1, then we | ||||||||||
1834 | // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to | ||||||||||
1835 | // UINT32_MAX. | ||||||||||
1836 | if (BitWidth == 1) | ||||||||||
1837 | return U.VAL - 1; | ||||||||||
1838 | |||||||||||
1839 | // Handle the zero case. | ||||||||||
1840 | if (isNullValue()) | ||||||||||
1841 | return UINT32_MAX(4294967295U); | ||||||||||
1842 | |||||||||||
1843 | // The non-zero case is handled by computing: | ||||||||||
1844 | // | ||||||||||
1845 | // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1]. | ||||||||||
1846 | // | ||||||||||
1847 | // where x[i] is referring to the value of the ith bit of x. | ||||||||||
1848 | unsigned lg = logBase2(); | ||||||||||
1849 | return lg + unsigned((*this)[lg - 1]); | ||||||||||
1850 | } | ||||||||||
1851 | |||||||||||
1852 | /// \returns the log base 2 of this APInt if its an exact power of two, -1 | ||||||||||
1853 | /// otherwise | ||||||||||
1854 | int32_t exactLogBase2() const { | ||||||||||
1855 | if (!isPowerOf2()) | ||||||||||
1856 | return -1; | ||||||||||
1857 | return logBase2(); | ||||||||||
1858 | } | ||||||||||
1859 | |||||||||||
1860 | /// Compute the square root | ||||||||||
1861 | APInt sqrt() const; | ||||||||||
1862 | |||||||||||
1863 | /// Get the absolute value; | ||||||||||
1864 | /// | ||||||||||
1865 | /// If *this is < 0 then return -(*this), otherwise *this; | ||||||||||
1866 | APInt abs() const { | ||||||||||
1867 | if (isNegative()) | ||||||||||
1868 | return -(*this); | ||||||||||
1869 | return *this; | ||||||||||
1870 | } | ||||||||||
1871 | |||||||||||
1872 | /// \returns the multiplicative inverse for a given modulo. | ||||||||||
1873 | APInt multiplicativeInverse(const APInt &modulo) const; | ||||||||||
1874 | |||||||||||
1875 | /// @} | ||||||||||
1876 | /// \name Support for division by constant | ||||||||||
1877 | /// @{ | ||||||||||
1878 | |||||||||||
1879 | /// Calculate the magic number for signed division by a constant. | ||||||||||
1880 | struct ms; | ||||||||||
1881 | ms magic() const; | ||||||||||
1882 | |||||||||||
1883 | /// Calculate the magic number for unsigned division by a constant. | ||||||||||
1884 | struct mu; | ||||||||||
1885 | mu magicu(unsigned LeadingZeros = 0) const; | ||||||||||
1886 | |||||||||||
1887 | /// @} | ||||||||||
1888 | /// \name Building-block Operations for APInt and APFloat | ||||||||||
1889 | /// @{ | ||||||||||
1890 | |||||||||||
1891 | // These building block operations operate on a representation of arbitrary | ||||||||||
1892 | // precision, two's-complement, bignum integer values. They should be | ||||||||||
1893 | // sufficient to implement APInt and APFloat bignum requirements. Inputs are | ||||||||||
1894 | // generally a pointer to the base of an array of integer parts, representing | ||||||||||
1895 | // an unsigned bignum, and a count of how many parts there are. | ||||||||||
1896 | |||||||||||
1897 | /// Sets the least significant part of a bignum to the input value, and zeroes | ||||||||||
1898 | /// out higher parts. | ||||||||||
1899 | static void tcSet(WordType *, WordType, unsigned); | ||||||||||
1900 | |||||||||||
1901 | /// Assign one bignum to another. | ||||||||||
1902 | static void tcAssign(WordType *, const WordType *, unsigned); | ||||||||||
1903 | |||||||||||
1904 | /// Returns true if a bignum is zero, false otherwise. | ||||||||||
1905 | static bool tcIsZero(const WordType *, unsigned); | ||||||||||
1906 | |||||||||||
1907 | /// Extract the given bit of a bignum; returns 0 or 1. Zero-based. | ||||||||||
1908 | static int tcExtractBit(const WordType *, unsigned bit); | ||||||||||
1909 | |||||||||||
1910 | /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to | ||||||||||
1911 | /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least | ||||||||||
1912 | /// significant bit of DST. All high bits above srcBITS in DST are | ||||||||||
1913 | /// zero-filled. | ||||||||||
1914 | static void tcExtract(WordType *, unsigned dstCount, | ||||||||||
1915 | const WordType *, unsigned srcBits, | ||||||||||
1916 | unsigned srcLSB); | ||||||||||
1917 | |||||||||||
1918 | /// Set the given bit of a bignum. Zero-based. | ||||||||||
1919 | static void tcSetBit(WordType *, unsigned bit); | ||||||||||
1920 | |||||||||||
1921 | /// Clear the given bit of a bignum. Zero-based. | ||||||||||
1922 | static void tcClearBit(WordType *, unsigned bit); | ||||||||||
1923 | |||||||||||
1924 | /// Returns the bit number of the least or most significant set bit of a | ||||||||||
1925 | /// number. If the input number has no bits set -1U is returned. | ||||||||||
1926 | static unsigned tcLSB(const WordType *, unsigned n); | ||||||||||
1927 | static unsigned tcMSB(const WordType *parts, unsigned n); | ||||||||||
1928 | |||||||||||
1929 | /// Negate a bignum in-place. | ||||||||||
1930 | static void tcNegate(WordType *, unsigned); | ||||||||||
1931 | |||||||||||
1932 | /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag. | ||||||||||
1933 | static WordType tcAdd(WordType *, const WordType *, | ||||||||||
1934 | WordType carry, unsigned); | ||||||||||
1935 | /// DST += RHS. Returns the carry flag. | ||||||||||
1936 | static WordType tcAddPart(WordType *, WordType, unsigned); | ||||||||||
1937 | |||||||||||
1938 | /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag. | ||||||||||
1939 | static WordType tcSubtract(WordType *, const WordType *, | ||||||||||
1940 | WordType carry, unsigned); | ||||||||||
1941 | /// DST -= RHS. Returns the carry flag. | ||||||||||
1942 | static WordType tcSubtractPart(WordType *, WordType, unsigned); | ||||||||||
1943 | |||||||||||
1944 | /// DST += SRC * MULTIPLIER + PART if add is true | ||||||||||
1945 | /// DST = SRC * MULTIPLIER + PART if add is false | ||||||||||
1946 | /// | ||||||||||
1947 | /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must | ||||||||||
1948 | /// start at the same point, i.e. DST == SRC. | ||||||||||
1949 | /// | ||||||||||
1950 | /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned. | ||||||||||
1951 | /// Otherwise DST is filled with the least significant DSTPARTS parts of the | ||||||||||
1952 | /// result, and if all of the omitted higher parts were zero return zero, | ||||||||||
1953 | /// otherwise overflow occurred and return one. | ||||||||||
1954 | static int tcMultiplyPart(WordType *dst, const WordType *src, | ||||||||||
1955 | WordType multiplier, WordType carry, | ||||||||||
1956 | unsigned srcParts, unsigned dstParts, | ||||||||||
1957 | bool add); | ||||||||||
1958 | |||||||||||
1959 | /// DST = LHS * RHS, where DST has the same width as the operands and is | ||||||||||
1960 | /// filled with the least significant parts of the result. Returns one if | ||||||||||
1961 | /// overflow occurred, otherwise zero. DST must be disjoint from both | ||||||||||
1962 | /// operands. | ||||||||||
1963 | static int tcMultiply(WordType *, const WordType *, const WordType *, | ||||||||||
1964 | unsigned); | ||||||||||
1965 | |||||||||||
1966 | /// DST = LHS * RHS, where DST has width the sum of the widths of the | ||||||||||
1967 | /// operands. No overflow occurs. DST must be disjoint from both operands. | ||||||||||
1968 | static void tcFullMultiply(WordType *, const WordType *, | ||||||||||
1969 | const WordType *, unsigned, unsigned); | ||||||||||
1970 | |||||||||||
1971 | /// If RHS is zero LHS and REMAINDER are left unchanged, return one. | ||||||||||
1972 | /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set | ||||||||||
1973 | /// REMAINDER to the remainder, return zero. i.e. | ||||||||||
1974 | /// | ||||||||||
1975 | /// OLD_LHS = RHS * LHS + REMAINDER | ||||||||||
1976 | /// | ||||||||||
1977 | /// SCRATCH is a bignum of the same size as the operands and result for use by | ||||||||||
1978 | /// the routine; its contents need not be initialized and are destroyed. LHS, | ||||||||||
1979 | /// REMAINDER and SCRATCH must be distinct. | ||||||||||
1980 | static int tcDivide(WordType *lhs, const WordType *rhs, | ||||||||||
1981 | WordType *remainder, WordType *scratch, | ||||||||||
1982 | unsigned parts); | ||||||||||
1983 | |||||||||||
1984 | /// Shift a bignum left Count bits. Shifted in bits are zero. There are no | ||||||||||
1985 | /// restrictions on Count. | ||||||||||
1986 | static void tcShiftLeft(WordType *, unsigned Words, unsigned Count); | ||||||||||
1987 | |||||||||||
1988 | /// Shift a bignum right Count bits. Shifted in bits are zero. There are no | ||||||||||
1989 | /// restrictions on Count. | ||||||||||
1990 | static void tcShiftRight(WordType *, unsigned Words, unsigned Count); | ||||||||||
1991 | |||||||||||
1992 | /// The obvious AND, OR and XOR and complement operations. | ||||||||||
1993 | static void tcAnd(WordType *, const WordType *, unsigned); | ||||||||||
1994 | static void tcOr(WordType *, const WordType *, unsigned); | ||||||||||
1995 | static void tcXor(WordType *, const WordType *, unsigned); | ||||||||||
1996 | static void tcComplement(WordType *, unsigned); | ||||||||||
1997 | |||||||||||
1998 | /// Comparison (unsigned) of two bignums. | ||||||||||
1999 | static int tcCompare(const WordType *, const WordType *, unsigned); | ||||||||||
2000 | |||||||||||
2001 | /// Increment a bignum in-place. Return the carry flag. | ||||||||||
2002 | static WordType tcIncrement(WordType *dst, unsigned parts) { | ||||||||||
2003 | return tcAddPart(dst, 1, parts); | ||||||||||
2004 | } | ||||||||||
2005 | |||||||||||
2006 | /// Decrement a bignum in-place. Return the borrow flag. | ||||||||||
2007 | static WordType tcDecrement(WordType *dst, unsigned parts) { | ||||||||||
2008 | return tcSubtractPart(dst, 1, parts); | ||||||||||
2009 | } | ||||||||||
2010 | |||||||||||
2011 | /// Set the least significant BITS and clear the rest. | ||||||||||
2012 | static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits); | ||||||||||
2013 | |||||||||||
2014 | /// debug method | ||||||||||
2015 | void dump() const; | ||||||||||
2016 | |||||||||||
2017 | /// @} | ||||||||||
2018 | }; | ||||||||||
2019 | |||||||||||
2020 | /// Magic data for optimising signed division by a constant. | ||||||||||
2021 | struct APInt::ms { | ||||||||||
2022 | APInt m; ///< magic number | ||||||||||
2023 | unsigned s; ///< shift amount | ||||||||||
2024 | }; | ||||||||||
2025 | |||||||||||
2026 | /// Magic data for optimising unsigned division by a constant. | ||||||||||
2027 | struct APInt::mu { | ||||||||||
2028 | APInt m; ///< magic number | ||||||||||
2029 | bool a; ///< add indicator | ||||||||||
2030 | unsigned s; ///< shift amount | ||||||||||
2031 | }; | ||||||||||
2032 | |||||||||||
2033 | inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; } | ||||||||||
2034 | |||||||||||
2035 | inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; } | ||||||||||
2036 | |||||||||||
2037 | /// Unary bitwise complement operator. | ||||||||||
2038 | /// | ||||||||||
2039 | /// \returns an APInt that is the bitwise complement of \p v. | ||||||||||
2040 | inline APInt operator~(APInt v) { | ||||||||||
2041 | v.flipAllBits(); | ||||||||||
2042 | return v; | ||||||||||
2043 | } | ||||||||||
2044 | |||||||||||
2045 | inline APInt operator&(APInt a, const APInt &b) { | ||||||||||
2046 | a &= b; | ||||||||||
2047 | return a; | ||||||||||
2048 | } | ||||||||||
2049 | |||||||||||
2050 | inline APInt operator&(const APInt &a, APInt &&b) { | ||||||||||
2051 | b &= a; | ||||||||||
2052 | return std::move(b); | ||||||||||
2053 | } | ||||||||||
2054 | |||||||||||
2055 | inline APInt operator&(APInt a, uint64_t RHS) { | ||||||||||
2056 | a &= RHS; | ||||||||||
2057 | return a; | ||||||||||
2058 | } | ||||||||||
2059 | |||||||||||
2060 | inline APInt operator&(uint64_t LHS, APInt b) { | ||||||||||
2061 | b &= LHS; | ||||||||||
2062 | return b; | ||||||||||
2063 | } | ||||||||||
2064 | |||||||||||
2065 | inline APInt operator|(APInt a, const APInt &b) { | ||||||||||
2066 | a |= b; | ||||||||||
2067 | return a; | ||||||||||
2068 | } | ||||||||||
2069 | |||||||||||
2070 | inline APInt operator|(const APInt &a, APInt &&b) { | ||||||||||
2071 | b |= a; | ||||||||||
2072 | return std::move(b); | ||||||||||
2073 | } | ||||||||||
2074 | |||||||||||
2075 | inline APInt operator|(APInt a, uint64_t RHS) { | ||||||||||
2076 | a |= RHS; | ||||||||||
2077 | return a; | ||||||||||
2078 | } | ||||||||||
2079 | |||||||||||
2080 | inline APInt operator|(uint64_t LHS, APInt b) { | ||||||||||
2081 | b |= LHS; | ||||||||||
2082 | return b; | ||||||||||
2083 | } | ||||||||||
2084 | |||||||||||
2085 | inline APInt operator^(APInt a, const APInt &b) { | ||||||||||
2086 | a ^= b; | ||||||||||
2087 | return a; | ||||||||||
2088 | } | ||||||||||
2089 | |||||||||||
2090 | inline APInt operator^(const APInt &a, APInt &&b) { | ||||||||||
2091 | b ^= a; | ||||||||||
2092 | return std::move(b); | ||||||||||
2093 | } | ||||||||||
2094 | |||||||||||
2095 | inline APInt operator^(APInt a, uint64_t RHS) { | ||||||||||
2096 | a ^= RHS; | ||||||||||
2097 | return a; | ||||||||||
2098 | } | ||||||||||
2099 | |||||||||||
2100 | inline APInt operator^(uint64_t LHS, APInt b) { | ||||||||||
2101 | b ^= LHS; | ||||||||||
2102 | return b; | ||||||||||
2103 | } | ||||||||||
2104 | |||||||||||
2105 | inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { | ||||||||||
2106 | I.print(OS, true); | ||||||||||
2107 | return OS; | ||||||||||
2108 | } | ||||||||||
2109 | |||||||||||
2110 | inline APInt operator-(APInt v) { | ||||||||||
2111 | v.negate(); | ||||||||||
2112 | return v; | ||||||||||
2113 | } | ||||||||||
2114 | |||||||||||
2115 | inline APInt operator+(APInt a, const APInt &b) { | ||||||||||
2116 | a += b; | ||||||||||
2117 | return a; | ||||||||||
2118 | } | ||||||||||
2119 | |||||||||||
2120 | inline APInt operator+(const APInt &a, APInt &&b) { | ||||||||||
2121 | b += a; | ||||||||||
2122 | return std::move(b); | ||||||||||
2123 | } | ||||||||||
2124 | |||||||||||
2125 | inline APInt operator+(APInt a, uint64_t RHS) { | ||||||||||
2126 | a += RHS; | ||||||||||
2127 | return a; | ||||||||||
2128 | } | ||||||||||
2129 | |||||||||||
2130 | inline APInt operator+(uint64_t LHS, APInt b) { | ||||||||||
2131 | b += LHS; | ||||||||||
2132 | return b; | ||||||||||
2133 | } | ||||||||||
2134 | |||||||||||
2135 | inline APInt operator-(APInt a, const APInt &b) { | ||||||||||
2136 | a -= b; | ||||||||||
2137 | return a; | ||||||||||
2138 | } | ||||||||||
2139 | |||||||||||
2140 | inline APInt operator-(const APInt &a, APInt &&b) { | ||||||||||
2141 | b.negate(); | ||||||||||
2142 | b += a; | ||||||||||
2143 | return std::move(b); | ||||||||||
2144 | } | ||||||||||
2145 | |||||||||||
2146 | inline APInt operator-(APInt a, uint64_t RHS) { | ||||||||||
2147 | a -= RHS; | ||||||||||
2148 | return a; | ||||||||||
2149 | } | ||||||||||
2150 | |||||||||||
2151 | inline APInt operator-(uint64_t LHS, APInt b) { | ||||||||||
2152 | b.negate(); | ||||||||||
2153 | b += LHS; | ||||||||||
2154 | return b; | ||||||||||
2155 | } | ||||||||||
2156 | |||||||||||
2157 | inline APInt operator*(APInt a, uint64_t RHS) { | ||||||||||
2158 | a *= RHS; | ||||||||||
2159 | return a; | ||||||||||
2160 | } | ||||||||||
2161 | |||||||||||
2162 | inline APInt operator*(uint64_t LHS, APInt b) { | ||||||||||
2163 | b *= LHS; | ||||||||||
2164 | return b; | ||||||||||
2165 | } | ||||||||||
2166 | |||||||||||
2167 | |||||||||||
2168 | namespace APIntOps { | ||||||||||
2169 | |||||||||||
2170 | /// Determine the smaller of two APInts considered to be signed. | ||||||||||
2171 | inline const APInt &smin(const APInt &A, const APInt &B) { | ||||||||||
2172 | return A.slt(B) ? A : B; | ||||||||||
2173 | } | ||||||||||
2174 | |||||||||||
2175 | /// Determine the larger of two APInts considered to be signed. | ||||||||||
2176 | inline const APInt &smax(const APInt &A, const APInt &B) { | ||||||||||
2177 | return A.sgt(B) ? A : B; | ||||||||||
2178 | } | ||||||||||
2179 | |||||||||||
2180 | /// Determine the smaller of two APInts considered to be signed. | ||||||||||
2181 | inline const APInt &umin(const APInt &A, const APInt &B) { | ||||||||||
2182 | return A.ult(B) ? A : B; | ||||||||||
2183 | } | ||||||||||
2184 | |||||||||||
2185 | /// Determine the larger of two APInts considered to be unsigned. | ||||||||||
2186 | inline const APInt &umax(const APInt &A, const APInt &B) { | ||||||||||
2187 | return A.ugt(B) ? A : B; | ||||||||||
2188 | } | ||||||||||
2189 | |||||||||||
2190 | /// Compute GCD of two unsigned APInt values. | ||||||||||
2191 | /// | ||||||||||
2192 | /// This function returns the greatest common divisor of the two APInt values | ||||||||||
2193 | /// using Stein's algorithm. | ||||||||||
2194 | /// | ||||||||||
2195 | /// \returns the greatest common divisor of A and B. | ||||||||||
2196 | APInt GreatestCommonDivisor(APInt A, APInt B); | ||||||||||
2197 | |||||||||||
2198 | /// Converts the given APInt to a double value. | ||||||||||
2199 | /// | ||||||||||
2200 | /// Treats the APInt as an unsigned value for conversion purposes. | ||||||||||
2201 | inline double RoundAPIntToDouble(const APInt &APIVal) { | ||||||||||
2202 | return APIVal.roundToDouble(); | ||||||||||
2203 | } | ||||||||||
2204 | |||||||||||
2205 | /// Converts the given APInt to a double value. | ||||||||||
2206 | /// | ||||||||||
2207 | /// Treats the APInt as a signed value for conversion purposes. | ||||||||||
2208 | inline double RoundSignedAPIntToDouble(const APInt &APIVal) { | ||||||||||
2209 | return APIVal.signedRoundToDouble(); | ||||||||||
2210 | } | ||||||||||
2211 | |||||||||||
2212 | /// Converts the given APInt to a float vlalue. | ||||||||||
2213 | inline float RoundAPIntToFloat(const APInt &APIVal) { | ||||||||||
2214 | return float(RoundAPIntToDouble(APIVal)); | ||||||||||
2215 | } | ||||||||||
2216 | |||||||||||
2217 | /// Converts the given APInt to a float value. | ||||||||||
2218 | /// | ||||||||||
2219 | /// Treats the APInt as a signed value for conversion purposes. | ||||||||||
2220 | inline float RoundSignedAPIntToFloat(const APInt &APIVal) { | ||||||||||
2221 | return float(APIVal.signedRoundToDouble()); | ||||||||||
2222 | } | ||||||||||
2223 | |||||||||||
2224 | /// Converts the given double value into a APInt. | ||||||||||
2225 | /// | ||||||||||
2226 | /// This function convert a double value to an APInt value. | ||||||||||
2227 | APInt RoundDoubleToAPInt(double Double, unsigned width); | ||||||||||
2228 | |||||||||||
2229 | /// Converts a float value into a APInt. | ||||||||||
2230 | /// | ||||||||||
2231 | /// Converts a float value into an APInt value. | ||||||||||
2232 | inline APInt RoundFloatToAPInt(float Float, unsigned width) { | ||||||||||
2233 | return RoundDoubleToAPInt(double(Float), width); | ||||||||||
2234 | } | ||||||||||
2235 | |||||||||||
2236 | /// Return A unsign-divided by B, rounded by the given rounding mode. | ||||||||||
2237 | APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM); | ||||||||||
2238 | |||||||||||
2239 | /// Return A sign-divided by B, rounded by the given rounding mode. | ||||||||||
2240 | APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM); | ||||||||||
2241 | |||||||||||
2242 | /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range | ||||||||||
2243 | /// (e.g. 32 for i32). | ||||||||||
2244 | /// This function finds the smallest number n, such that | ||||||||||
2245 | /// (a) n >= 0 and q(n) = 0, or | ||||||||||
2246 | /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all | ||||||||||
2247 | /// integers, belong to two different intervals [Rk, Rk+R), | ||||||||||
2248 | /// where R = 2^BW, and k is an integer. | ||||||||||
2249 | /// The idea here is to find when q(n) "overflows" 2^BW, while at the | ||||||||||
2250 | /// same time "allowing" subtraction. In unsigned modulo arithmetic a | ||||||||||
2251 | /// subtraction (treated as addition of negated numbers) would always | ||||||||||
2252 | /// count as an overflow, but here we want to allow values to decrease | ||||||||||
2253 | /// and increase as long as they are within the same interval. | ||||||||||
2254 | /// Specifically, adding of two negative numbers should not cause an | ||||||||||
2255 | /// overflow (as long as the magnitude does not exceed the bit width). | ||||||||||
2256 | /// On the other hand, given a positive number, adding a negative | ||||||||||
2257 | /// number to it can give a negative result, which would cause the | ||||||||||
2258 | /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is | ||||||||||
2259 | /// treated as a special case of an overflow. | ||||||||||
2260 | /// | ||||||||||
2261 | /// This function returns None if after finding k that minimizes the | ||||||||||
2262 | /// positive solution to q(n) = kR, both solutions are contained between | ||||||||||
2263 | /// two consecutive integers. | ||||||||||
2264 | /// | ||||||||||
2265 | /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation | ||||||||||
2266 | /// in arithmetic modulo 2^BW, and treating the values as signed) by the | ||||||||||
2267 | /// virtue of *signed* overflow. This function will *not* find such an n, | ||||||||||
2268 | /// however it may find a value of n satisfying the inequalities due to | ||||||||||
2269 | /// an *unsigned* overflow (if the values are treated as unsigned). | ||||||||||
2270 | /// To find a solution for a signed overflow, treat it as a problem of | ||||||||||
2271 | /// finding an unsigned overflow with a range with of BW-1. | ||||||||||
2272 | /// | ||||||||||
2273 | /// The returned value may have a different bit width from the input | ||||||||||
2274 | /// coefficients. | ||||||||||
2275 | Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, | ||||||||||
2276 | unsigned RangeWidth); | ||||||||||
2277 | |||||||||||
2278 | /// Compare two values, and if they are different, return the position of the | ||||||||||
2279 | /// most significant bit that is different in the values. | ||||||||||
2280 | Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A, | ||||||||||
2281 | const APInt &B); | ||||||||||
2282 | |||||||||||
2283 | } // End of APIntOps namespace | ||||||||||
2284 | |||||||||||
2285 | // See friend declaration above. This additional declaration is required in | ||||||||||
2286 | // order to compile LLVM with IBM xlC compiler. | ||||||||||
2287 | hash_code hash_value(const APInt &Arg); | ||||||||||
2288 | |||||||||||
2289 | /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst | ||||||||||
2290 | /// with the integer held in IntVal. | ||||||||||
2291 | void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes); | ||||||||||
2292 | |||||||||||
2293 | /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting | ||||||||||
2294 | /// from Src into IntVal, which is assumed to be wide enough and to hold zero. | ||||||||||
2295 | void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes); | ||||||||||
2296 | |||||||||||
2297 | } // namespace llvm | ||||||||||
2298 | |||||||||||
2299 | #endif |