Line data Source code
1 : //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 : //
3 : // The LLVM Compiler Infrastructure
4 : //
5 : // This file is distributed under the University of Illinois Open Source
6 : // License. See LICENSE.TXT for details.
7 : //
8 : //===----------------------------------------------------------------------===//
9 : //
10 : // This file contains the implementation of the scalar evolution analysis
11 : // engine, which is used primarily to analyze expressions involving induction
12 : // variables in loops.
13 : //
14 : // There are several aspects to this library. First is the representation of
15 : // scalar expressions, which are represented as subclasses of the SCEV class.
16 : // These classes are used to represent certain types of subexpressions that we
17 : // can handle. We only create one SCEV of a particular shape, so
18 : // pointer-comparisons for equality are legal.
19 : //
20 : // One important aspect of the SCEV objects is that they are never cyclic, even
21 : // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22 : // the PHI node is one of the idioms that we can represent (e.g., a polynomial
23 : // recurrence) then we represent it directly as a recurrence node, otherwise we
24 : // represent it as a SCEVUnknown node.
25 : //
26 : // In addition to being able to represent expressions of various types, we also
27 : // have folders that are used to build the *canonical* representation for a
28 : // particular expression. These folders are capable of using a variety of
29 : // rewrite rules to simplify the expressions.
30 : //
31 : // Once the folders are defined, we can implement the more interesting
32 : // higher-level code, such as the code that recognizes PHI nodes of various
33 : // types, computes the execution count of a loop, etc.
34 : //
35 : // TODO: We should use these routines and value representations to implement
36 : // dependence analysis!
37 : //
38 : //===----------------------------------------------------------------------===//
39 : //
40 : // There are several good references for the techniques used in this analysis.
41 : //
42 : // Chains of recurrences -- a method to expedite the evaluation
43 : // of closed-form functions
44 : // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 : //
46 : // On computational properties of chains of recurrences
47 : // Eugene V. Zima
48 : //
49 : // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50 : // Robert A. van Engelen
51 : //
52 : // Efficient Symbolic Analysis for Optimizing Compilers
53 : // Robert A. van Engelen
54 : //
55 : // Using the chains of recurrences algebra for data dependence testing and
56 : // induction variable substitution
57 : // MS Thesis, Johnie Birch
58 : //
59 : //===----------------------------------------------------------------------===//
60 :
61 : #include "llvm/Analysis/ScalarEvolution.h"
62 : #include "llvm/ADT/APInt.h"
63 : #include "llvm/ADT/ArrayRef.h"
64 : #include "llvm/ADT/DenseMap.h"
65 : #include "llvm/ADT/DepthFirstIterator.h"
66 : #include "llvm/ADT/EquivalenceClasses.h"
67 : #include "llvm/ADT/FoldingSet.h"
68 : #include "llvm/ADT/None.h"
69 : #include "llvm/ADT/Optional.h"
70 : #include "llvm/ADT/STLExtras.h"
71 : #include "llvm/ADT/ScopeExit.h"
72 : #include "llvm/ADT/Sequence.h"
73 : #include "llvm/ADT/SetVector.h"
74 : #include "llvm/ADT/SmallPtrSet.h"
75 : #include "llvm/ADT/SmallSet.h"
76 : #include "llvm/ADT/SmallVector.h"
77 : #include "llvm/ADT/Statistic.h"
78 : #include "llvm/ADT/StringRef.h"
79 : #include "llvm/Analysis/AssumptionCache.h"
80 : #include "llvm/Analysis/ConstantFolding.h"
81 : #include "llvm/Analysis/InstructionSimplify.h"
82 : #include "llvm/Analysis/LoopInfo.h"
83 : #include "llvm/Analysis/ScalarEvolutionExpressions.h"
84 : #include "llvm/Analysis/TargetLibraryInfo.h"
85 : #include "llvm/Analysis/ValueTracking.h"
86 : #include "llvm/Config/llvm-config.h"
87 : #include "llvm/IR/Argument.h"
88 : #include "llvm/IR/BasicBlock.h"
89 : #include "llvm/IR/CFG.h"
90 : #include "llvm/IR/CallSite.h"
91 : #include "llvm/IR/Constant.h"
92 : #include "llvm/IR/ConstantRange.h"
93 : #include "llvm/IR/Constants.h"
94 : #include "llvm/IR/DataLayout.h"
95 : #include "llvm/IR/DerivedTypes.h"
96 : #include "llvm/IR/Dominators.h"
97 : #include "llvm/IR/Function.h"
98 : #include "llvm/IR/GlobalAlias.h"
99 : #include "llvm/IR/GlobalValue.h"
100 : #include "llvm/IR/GlobalVariable.h"
101 : #include "llvm/IR/InstIterator.h"
102 : #include "llvm/IR/InstrTypes.h"
103 : #include "llvm/IR/Instruction.h"
104 : #include "llvm/IR/Instructions.h"
105 : #include "llvm/IR/IntrinsicInst.h"
106 : #include "llvm/IR/Intrinsics.h"
107 : #include "llvm/IR/LLVMContext.h"
108 : #include "llvm/IR/Metadata.h"
109 : #include "llvm/IR/Operator.h"
110 : #include "llvm/IR/PatternMatch.h"
111 : #include "llvm/IR/Type.h"
112 : #include "llvm/IR/Use.h"
113 : #include "llvm/IR/User.h"
114 : #include "llvm/IR/Value.h"
115 : #include "llvm/Pass.h"
116 : #include "llvm/Support/Casting.h"
117 : #include "llvm/Support/CommandLine.h"
118 : #include "llvm/Support/Compiler.h"
119 : #include "llvm/Support/Debug.h"
120 : #include "llvm/Support/ErrorHandling.h"
121 : #include "llvm/Support/KnownBits.h"
122 : #include "llvm/Support/SaveAndRestore.h"
123 : #include "llvm/Support/raw_ostream.h"
124 : #include <algorithm>
125 : #include <cassert>
126 : #include <climits>
127 : #include <cstddef>
128 : #include <cstdint>
129 : #include <cstdlib>
130 : #include <map>
131 : #include <memory>
132 : #include <tuple>
133 : #include <utility>
134 : #include <vector>
135 :
136 : using namespace llvm;
137 :
138 : #define DEBUG_TYPE "scalar-evolution"
139 :
140 : STATISTIC(NumArrayLenItCounts,
141 : "Number of trip counts computed with array length");
142 : STATISTIC(NumTripCountsComputed,
143 : "Number of loops with predictable loop counts");
144 : STATISTIC(NumTripCountsNotComputed,
145 : "Number of loops without predictable loop counts");
146 : STATISTIC(NumBruteForceTripCountsComputed,
147 : "Number of loops with trip counts computed by force");
148 :
149 : static cl::opt<unsigned>
150 : MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151 : cl::desc("Maximum number of iterations SCEV will "
152 : "symbolically execute a constant "
153 : "derived loop"),
154 : cl::init(100));
155 :
156 : // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
157 : static cl::opt<bool> VerifySCEV(
158 : "verify-scev", cl::Hidden,
159 : cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
160 : static cl::opt<bool>
161 : VerifySCEVMap("verify-scev-maps", cl::Hidden,
162 : cl::desc("Verify no dangling value in ScalarEvolution's "
163 : "ExprValueMap (slow)"));
164 :
165 : static cl::opt<unsigned> MulOpsInlineThreshold(
166 : "scev-mulops-inline-threshold", cl::Hidden,
167 : cl::desc("Threshold for inlining multiplication operands into a SCEV"),
168 : cl::init(32));
169 :
170 : static cl::opt<unsigned> AddOpsInlineThreshold(
171 : "scev-addops-inline-threshold", cl::Hidden,
172 : cl::desc("Threshold for inlining addition operands into a SCEV"),
173 : cl::init(500));
174 :
175 : static cl::opt<unsigned> MaxSCEVCompareDepth(
176 : "scalar-evolution-max-scev-compare-depth", cl::Hidden,
177 : cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
178 : cl::init(32));
179 :
180 : static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
181 : "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
182 : cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
183 : cl::init(2));
184 :
185 : static cl::opt<unsigned> MaxValueCompareDepth(
186 : "scalar-evolution-max-value-compare-depth", cl::Hidden,
187 : cl::desc("Maximum depth of recursive value complexity comparisons"),
188 : cl::init(2));
189 :
190 : static cl::opt<unsigned>
191 : MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
192 : cl::desc("Maximum depth of recursive arithmetics"),
193 : cl::init(32));
194 :
195 : static cl::opt<unsigned> MaxConstantEvolvingDepth(
196 : "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
197 : cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
198 :
199 : static cl::opt<unsigned>
200 : MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
201 : cl::desc("Maximum depth of recursive SExt/ZExt"),
202 : cl::init(8));
203 :
204 : static cl::opt<unsigned>
205 : MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
206 : cl::desc("Max coefficients in AddRec during evolving"),
207 : cl::init(8));
208 :
209 : //===----------------------------------------------------------------------===//
210 : // SCEV class definitions
211 : //===----------------------------------------------------------------------===//
212 :
213 : //===----------------------------------------------------------------------===//
214 : // Implementation of the SCEV class.
215 : //
216 :
217 : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218 : LLVM_DUMP_METHOD void SCEV::dump() const {
219 : print(dbgs());
220 : dbgs() << '\n';
221 : }
222 : #endif
223 :
224 60436 : void SCEV::print(raw_ostream &OS) const {
225 120872 : switch (static_cast<SCEVTypes>(getSCEVType())) {
226 : case scConstant:
227 21013 : cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
228 21013 : return;
229 : case scTruncate: {
230 : const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
231 1253 : const SCEV *Op = Trunc->getOperand();
232 2506 : OS << "(trunc " << *Op->getType() << " " << *Op << " to "
233 1253 : << *Trunc->getType() << ")";
234 1253 : return;
235 : }
236 : case scZeroExtend: {
237 : const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
238 2560 : const SCEV *Op = ZExt->getOperand();
239 5120 : OS << "(zext " << *Op->getType() << " " << *Op << " to "
240 2560 : << *ZExt->getType() << ")";
241 2560 : return;
242 : }
243 : case scSignExtend: {
244 : const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
245 459 : const SCEV *Op = SExt->getOperand();
246 918 : OS << "(sext " << *Op->getType() << " " << *Op << " to "
247 459 : << *SExt->getType() << ")";
248 459 : return;
249 : }
250 : case scAddRecExpr: {
251 : const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
252 3602 : OS << "{" << *AR->getOperand(0);
253 7731 : for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
254 4129 : OS << ",+," << *AR->getOperand(i);
255 3602 : OS << "}<";
256 3602 : if (AR->hasNoUnsignedWrap())
257 480 : OS << "nuw><";
258 3602 : if (AR->hasNoSignedWrap())
259 648 : OS << "nsw><";
260 3602 : if (AR->hasNoSelfWrap() &&
261 : !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
262 174 : OS << "nw><";
263 7204 : AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
264 3602 : OS << ">";
265 3602 : return;
266 : }
267 : case scAddExpr:
268 : case scMulExpr:
269 : case scUMaxExpr:
270 : case scSMaxExpr: {
271 : const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
272 : const char *OpStr = nullptr;
273 : switch (NAry->getSCEVType()) {
274 7249 : case scAddExpr: OpStr = " + "; break;
275 7905 : case scMulExpr: OpStr = " * "; break;
276 2727 : case scUMaxExpr: OpStr = " umax "; break;
277 306 : case scSMaxExpr: OpStr = " smax "; break;
278 : }
279 18187 : OS << "(";
280 18187 : for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
281 58431 : I != E; ++I) {
282 40244 : OS << **I;
283 40244 : if (std::next(I) != E)
284 22057 : OS << OpStr;
285 : }
286 18187 : OS << ")";
287 18187 : switch (NAry->getSCEVType()) {
288 : case scAddExpr:
289 : case scMulExpr:
290 15154 : if (NAry->hasNoUnsignedWrap())
291 458 : OS << "<nuw>";
292 15154 : if (NAry->hasNoSignedWrap())
293 4681 : OS << "<nsw>";
294 : }
295 : return;
296 : }
297 : case scUDivExpr: {
298 : const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
299 467 : OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
300 467 : return;
301 : }
302 : case scUnknown: {
303 : const SCEVUnknown *U = cast<SCEVUnknown>(this);
304 : Type *AllocTy;
305 12895 : if (U->isSizeOf(AllocTy)) {
306 4 : OS << "sizeof(" << *AllocTy << ")";
307 4 : return;
308 : }
309 12891 : if (U->isAlignOf(AllocTy)) {
310 3 : OS << "alignof(" << *AllocTy << ")";
311 3 : return;
312 : }
313 :
314 : Type *CTy;
315 : Constant *FieldNo;
316 12888 : if (U->isOffsetOf(CTy, FieldNo)) {
317 1 : OS << "offsetof(" << *CTy << ", ";
318 1 : FieldNo->printAsOperand(OS, false);
319 1 : OS << ")";
320 1 : return;
321 : }
322 :
323 : // Otherwise just print it normally.
324 12887 : U->getValue()->printAsOperand(OS, false);
325 12887 : return;
326 : }
327 0 : case scCouldNotCompute:
328 0 : OS << "***COULDNOTCOMPUTE***";
329 0 : return;
330 : }
331 0 : llvm_unreachable("Unknown SCEV kind!");
332 : }
333 :
334 8983730 : Type *SCEV::getType() const {
335 9061350 : switch (static_cast<SCEVTypes>(getSCEVType())) {
336 : case scConstant:
337 7167722 : return cast<SCEVConstant>(this)->getType();
338 : case scTruncate:
339 : case scZeroExtend:
340 : case scSignExtend:
341 209377 : return cast<SCEVCastExpr>(this)->getType();
342 : case scAddRecExpr:
343 : case scMulExpr:
344 : case scUMaxExpr:
345 : case scSMaxExpr:
346 1812052 : return cast<SCEVNAryExpr>(this)->getType();
347 : case scAddExpr:
348 1041278 : return cast<SCEVAddExpr>(this)->getType();
349 : case scUDivExpr:
350 77620 : return cast<SCEVUDivExpr>(this)->getType();
351 : case scUnknown:
352 2337162 : return cast<SCEVUnknown>(this)->getType();
353 : case scCouldNotCompute:
354 : llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
355 : }
356 0 : llvm_unreachable("Unknown SCEV kind!");
357 : }
358 :
359 1501626 : bool SCEV::isZero() const {
360 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
361 968255 : return SC->getValue()->isZero();
362 : return false;
363 : }
364 :
365 49140 : bool SCEV::isOne() const {
366 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
367 33347 : return SC->getValue()->isOne();
368 : return false;
369 : }
370 :
371 684666 : bool SCEV::isAllOnesValue() const {
372 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
373 680741 : return SC->getValue()->isMinusOne();
374 : return false;
375 : }
376 :
377 23334 : bool SCEV::isNonConstantNegative() const {
378 : const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
379 : if (!Mul) return false;
380 :
381 : // If there is a constant factor, it will be first.
382 4863 : const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
383 : if (!SC) return false;
384 :
385 : // Return true if the value is negative, this matches things like (-42 * V).
386 4181 : return SC->getAPInt().isNegative();
387 : }
388 :
389 557960 : SCEVCouldNotCompute::SCEVCouldNotCompute() :
390 557960 : SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
391 :
392 663509 : bool SCEVCouldNotCompute::classof(const SCEV *S) {
393 663509 : return S->getSCEVType() == scCouldNotCompute;
394 : }
395 :
396 5965399 : const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
397 : FoldingSetNodeID ID;
398 5965399 : ID.AddInteger(scConstant);
399 5965399 : ID.AddPointer(V);
400 5965399 : void *IP = nullptr;
401 5965399 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
402 413480 : SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
403 413480 : UniqueSCEVs.InsertNode(S, IP);
404 413480 : return S;
405 : }
406 :
407 2376486 : const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
408 2376486 : return getConstant(ConstantInt::get(getContext(), Val));
409 : }
410 :
411 : const SCEV *
412 1361765 : ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
413 1361765 : IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
414 1361765 : return getConstant(ConstantInt::get(ITy, V, isSigned));
415 : }
416 :
417 75732 : SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
418 75732 : unsigned SCEVTy, const SCEV *op, Type *ty)
419 75732 : : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
420 :
421 5155 : SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
422 5155 : const SCEV *op, Type *ty)
423 5155 : : SCEVCastExpr(ID, scTruncate, op, ty) {
424 : assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
425 : "Cannot truncate non-integer value!");
426 5155 : }
427 :
428 44742 : SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
429 44742 : const SCEV *op, Type *ty)
430 44742 : : SCEVCastExpr(ID, scZeroExtend, op, ty) {
431 : assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
432 : "Cannot zero extend non-integer value!");
433 44742 : }
434 :
435 25835 : SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
436 25835 : const SCEV *op, Type *ty)
437 25835 : : SCEVCastExpr(ID, scSignExtend, op, ty) {
438 : assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
439 : "Cannot sign extend non-integer value!");
440 25835 : }
441 :
442 1464 : void SCEVUnknown::deleted() {
443 : // Clear this SCEVUnknown from various maps.
444 1464 : SE->forgetMemoizedResults(this);
445 :
446 : // Remove this SCEVUnknown from the uniquing map.
447 1464 : SE->UniqueSCEVs.RemoveNode(this);
448 :
449 : // Release the value.
450 : setValPtr(nullptr);
451 1464 : }
452 :
453 2014 : void SCEVUnknown::allUsesReplacedWith(Value *New) {
454 : // Remove this SCEVUnknown from the uniquing map.
455 2014 : SE->UniqueSCEVs.RemoveNode(this);
456 :
457 : // Update this SCEVUnknown to point to the new value. This is needed
458 : // because there may still be outstanding SCEVs which still point to
459 : // this SCEVUnknown.
460 : setValPtr(New);
461 2014 : }
462 :
463 12895 : bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
464 : if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
465 13 : if (VCE->getOpcode() == Instruction::PtrToInt)
466 : if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
467 8 : if (CE->getOpcode() == Instruction::GetElementPtr &&
468 24 : CE->getOperand(0)->isNullValue() &&
469 : CE->getNumOperands() == 2)
470 : if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
471 4 : if (CI->isOne()) {
472 4 : AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
473 4 : ->getElementType();
474 4 : return true;
475 : }
476 :
477 : return false;
478 : }
479 :
480 12891 : bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
481 : if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
482 9 : if (VCE->getOpcode() == Instruction::PtrToInt)
483 : if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
484 8 : if (CE->getOpcode() == Instruction::GetElementPtr &&
485 4 : CE->getOperand(0)->isNullValue()) {
486 : Type *Ty =
487 4 : cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
488 : if (StructType *STy = dyn_cast<StructType>(Ty))
489 4 : if (!STy->isPacked() &&
490 8 : CE->getNumOperands() == 3 &&
491 4 : CE->getOperand(1)->isNullValue()) {
492 : if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
493 3 : if (CI->isOne() &&
494 7 : STy->getNumElements() == 2 &&
495 6 : STy->getElementType(0)->isIntegerTy(1)) {
496 3 : AllocTy = STy->getElementType(1);
497 3 : return true;
498 : }
499 : }
500 : }
501 :
502 : return false;
503 : }
504 :
505 12888 : bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
506 : if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
507 6 : if (VCE->getOpcode() == Instruction::PtrToInt)
508 : if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
509 1 : if (CE->getOpcode() == Instruction::GetElementPtr &&
510 1 : CE->getNumOperands() == 3 &&
511 3 : CE->getOperand(0)->isNullValue() &&
512 1 : CE->getOperand(1)->isNullValue()) {
513 : Type *Ty =
514 1 : cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
515 : // Ignore vector types here so that ScalarEvolutionExpander doesn't
516 : // emit getelementptrs that index into vectors.
517 1 : if (Ty->isStructTy() || Ty->isArrayTy()) {
518 1 : CTy = Ty;
519 1 : FieldNo = CE->getOperand(2);
520 1 : return true;
521 : }
522 : }
523 :
524 : return false;
525 : }
526 :
527 : //===----------------------------------------------------------------------===//
528 : // SCEV Utilities
529 : //===----------------------------------------------------------------------===//
530 :
531 : /// Compare the two values \p LV and \p RV in terms of their "complexity" where
532 : /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
533 : /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
534 : /// have been previously deemed to be "equally complex" by this routine. It is
535 : /// intended to avoid exponential time complexity in cases like:
536 : ///
537 : /// %a = f(%x, %y)
538 : /// %b = f(%a, %a)
539 : /// %c = f(%b, %b)
540 : ///
541 : /// %d = f(%x, %y)
542 : /// %e = f(%d, %d)
543 : /// %f = f(%e, %e)
544 : ///
545 : /// CompareValueComplexity(%f, %c)
546 : ///
547 : /// Since we do not continue running this routine on expression trees once we
548 : /// have seen unequal values, there is no need to track them in the cache.
549 : static int
550 4136317 : CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
551 : const LoopInfo *const LI, Value *LV, Value *RV,
552 : unsigned Depth) {
553 4136317 : if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
554 2034519 : return 0;
555 :
556 : // Order pointer values after integer values. This helps SCEVExpander form
557 : // GEPs.
558 2101798 : bool LIsPointer = LV->getType()->isPointerTy(),
559 2101798 : RIsPointer = RV->getType()->isPointerTy();
560 2101798 : if (LIsPointer != RIsPointer)
561 20538 : return (int)LIsPointer - (int)RIsPointer;
562 :
563 : // Compare getValueID values.
564 2081260 : unsigned LID = LV->getValueID(), RID = RV->getValueID();
565 2081260 : if (LID != RID)
566 699798 : return (int)LID - (int)RID;
567 :
568 : // Sort arguments by their position.
569 : if (const auto *LA = dyn_cast<Argument>(LV)) {
570 : const auto *RA = cast<Argument>(RV);
571 10670 : unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
572 10670 : return (int)LArgNo - (int)RArgNo;
573 : }
574 :
575 : if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
576 : const auto *RGV = cast<GlobalValue>(RV);
577 :
578 : const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
579 : auto LT = GV->getLinkage();
580 5682 : return !(GlobalValue::isPrivateLinkage(LT) ||
581 : GlobalValue::isInternalLinkage(LT));
582 : };
583 :
584 : // Use the names to distinguish the two values, but only if the
585 : // names are semantically important.
586 : if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
587 11364 : return LGV->getName().compare(RGV->getName());
588 : }
589 :
590 : // For instructions, compare their loop depth, and their operand count. This
591 : // is pretty loose.
592 : if (const auto *LInst = dyn_cast<Instruction>(LV)) {
593 : const auto *RInst = cast<Instruction>(RV);
594 :
595 : // Compare loop depths.
596 1361661 : const BasicBlock *LParent = LInst->getParent(),
597 1361661 : *RParent = RInst->getParent();
598 1361661 : if (LParent != RParent) {
599 937121 : unsigned LDepth = LI->getLoopDepth(LParent),
600 937121 : RDepth = LI->getLoopDepth(RParent);
601 937121 : if (LDepth != RDepth)
602 415 : return (int)LDepth - (int)RDepth;
603 : }
604 :
605 : // Compare the number of operands.
606 : unsigned LNumOps = LInst->getNumOperands(),
607 : RNumOps = RInst->getNumOperands();
608 1361246 : if (LNumOps != RNumOps)
609 169 : return (int)LNumOps - (int)RNumOps;
610 :
611 4139251 : for (unsigned Idx : seq(0u, LNumOps)) {
612 : int Result =
613 8534064 : CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
614 : RInst->getOperand(Idx), Depth + 1);
615 2844688 : if (Result != 0)
616 : return Result;
617 : }
618 : }
619 :
620 1298012 : EqCacheValue.unionSets(LV, RV);
621 1298012 : return 0;
622 : }
623 :
624 : // Return negative, zero, or positive, if LHS is less than, equal to, or greater
625 : // than RHS, respectively. A three-way result allows recursive comparisons to be
626 : // more efficient.
627 8999173 : static int CompareSCEVComplexity(
628 : EquivalenceClasses<const SCEV *> &EqCacheSCEV,
629 : EquivalenceClasses<const Value *> &EqCacheValue,
630 : const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
631 : DominatorTree &DT, unsigned Depth = 0) {
632 : // Fast-path: SCEVs are uniqued so we can do a quick equality check.
633 8999173 : if (LHS == RHS)
634 : return 0;
635 :
636 : // Primarily, sort the SCEVs by their getSCEVType().
637 8012228 : unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
638 8012228 : if (LType != RType)
639 3324573 : return (int)LType - (int)RType;
640 :
641 4687655 : if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
642 954058 : return 0;
643 : // Aside from the getSCEVType() ordering, the particular ordering
644 : // isn't very important except that it's beneficial to be consistent,
645 : // so that (a + b) and (b + a) don't end up as different expressions.
646 3733597 : switch (static_cast<SCEVTypes>(LType)) {
647 1291629 : case scUnknown: {
648 1291629 : const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
649 1291629 : const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
650 :
651 2583258 : int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
652 : RU->getValue(), Depth + 1);
653 1291629 : if (X == 0)
654 554357 : EqCacheSCEV.unionSets(LHS, RHS);
655 : return X;
656 : }
657 :
658 1615757 : case scConstant: {
659 1615757 : const SCEVConstant *LC = cast<SCEVConstant>(LHS);
660 1615757 : const SCEVConstant *RC = cast<SCEVConstant>(RHS);
661 :
662 : // Compare constant values.
663 : const APInt &LA = LC->getAPInt();
664 : const APInt &RA = RC->getAPInt();
665 1615757 : unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
666 1615757 : if (LBitWidth != RBitWidth)
667 1 : return (int)LBitWidth - (int)RBitWidth;
668 1615756 : return LA.ult(RA) ? -1 : 1;
669 : }
670 :
671 21815 : case scAddRecExpr: {
672 21815 : const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
673 21815 : const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
674 :
675 : // There is always a dominance between two recs that are used by one SCEV,
676 : // so we can safely sort recs by loop header dominance. We require such
677 : // order in getAddExpr.
678 21815 : const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
679 21815 : if (LLoop != RLoop) {
680 : const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
681 : assert(LHead != RHead && "Two loops share the same header?");
682 4480 : if (DT.dominates(LHead, RHead))
683 : return 1;
684 : else
685 : assert(DT.dominates(RHead, LHead) &&
686 : "No dominance between recurrences used by one SCEV?");
687 2355 : return -1;
688 : }
689 :
690 : // Addrec complexity grows with operand count.
691 17335 : unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
692 17335 : if (LNumOps != RNumOps)
693 3248 : return (int)LNumOps - (int)RNumOps;
694 :
695 : // Lexicographically compare.
696 14317 : for (unsigned i = 0; i != LNumOps; ++i) {
697 42951 : int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
698 : LA->getOperand(i), RA->getOperand(i), DT,
699 : Depth + 1);
700 14317 : if (X != 0)
701 14087 : return X;
702 : }
703 0 : EqCacheSCEV.unionSets(LHS, RHS);
704 0 : return 0;
705 : }
706 :
707 780517 : case scAddExpr:
708 : case scMulExpr:
709 : case scSMaxExpr:
710 : case scUMaxExpr: {
711 780517 : const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
712 780517 : const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
713 :
714 : // Lexicographically compare n-ary expressions.
715 780517 : unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
716 780517 : if (LNumOps != RNumOps)
717 91950 : return (int)LNumOps - (int)RNumOps;
718 :
719 1496671 : for (unsigned i = 0; i != LNumOps; ++i) {
720 3689853 : int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
721 : LC->getOperand(i), RC->getOperand(i), DT,
722 : Depth + 1);
723 1229951 : if (X != 0)
724 421847 : return X;
725 : }
726 266720 : EqCacheSCEV.unionSets(LHS, RHS);
727 266720 : return 0;
728 : }
729 :
730 4314 : case scUDivExpr: {
731 4314 : const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
732 4314 : const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
733 :
734 : // Lexicographically compare udiv expressions.
735 4314 : int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
736 : RC->getLHS(), DT, Depth + 1);
737 4314 : if (X != 0)
738 : return X;
739 580 : X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
740 : RC->getRHS(), DT, Depth + 1);
741 580 : if (X == 0)
742 349 : EqCacheSCEV.unionSets(LHS, RHS);
743 : return X;
744 : }
745 :
746 19565 : case scTruncate:
747 : case scZeroExtend:
748 : case scSignExtend: {
749 19565 : const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
750 19565 : const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
751 :
752 : // Compare cast expressions by operand.
753 19565 : int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
754 : LC->getOperand(), RC->getOperand(), DT,
755 : Depth + 1);
756 19565 : if (X == 0)
757 10885 : EqCacheSCEV.unionSets(LHS, RHS);
758 : return X;
759 : }
760 :
761 : case scCouldNotCompute:
762 : llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
763 : }
764 0 : llvm_unreachable("Unknown SCEV kind!");
765 : }
766 :
767 : /// Given a list of SCEV objects, order them by their complexity, and group
768 : /// objects of the same complexity together by value. When this routine is
769 : /// finished, we know that any duplicates in the vector are consecutive and that
770 : /// complexity is monotonically increasing.
771 : ///
772 : /// Note that we go take special precautions to ensure that we get deterministic
773 : /// results from this routine. In other words, we don't want the results of
774 : /// this to depend on where the addresses of various SCEV objects happened to
775 : /// land in memory.
776 4344134 : static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
777 : LoopInfo *LI, DominatorTree &DT) {
778 12566038 : if (Ops.size() < 2) return; // Noop
779 :
780 : EquivalenceClasses<const SCEV *> EqCacheSCEV;
781 : EquivalenceClasses<const Value *> EqCacheValue;
782 4344134 : if (Ops.size() == 2) {
783 : // This is the common case, which also happens to be trivially simple.
784 : // Special case it.
785 : const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
786 3828103 : if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
787 : std::swap(LHS, RHS);
788 3828103 : return;
789 : }
790 :
791 : // Do the rough sort by complexity.
792 : std::stable_sort(Ops.begin(), Ops.end(),
793 : [&](const SCEV *LHS, const SCEV *RHS) {
794 : return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
795 : LHS, RHS, DT) < 0;
796 : });
797 :
798 : // Now that we are sorted by complexity, group elements of the same
799 : // complexity. Note that this is, at worst, N^2, but the vector is likely to
800 : // be extremely short in practice. Note that we take this approach because we
801 : // do not want to depend on the addresses of the objects we are grouping.
802 1655060 : for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
803 1188696 : const SCEV *S = Ops[i];
804 1188696 : unsigned Complexity = S->getSCEVType();
805 :
806 : // If there are any objects of the same complexity and same value as this
807 : // one, group them.
808 13570706 : for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
809 12431677 : if (Ops[j] == S) { // Found a duplicate.
810 : // Move it to immediately after i'th element.
811 82420 : std::swap(Ops[i+1], Ops[j]);
812 : ++i; // no need to rescan it.
813 82420 : if (i == e-2) return; // Done!
814 : }
815 : }
816 : }
817 : }
818 :
819 : // Returns the size of the SCEV S.
820 72 : static inline int sizeOfSCEV(const SCEV *S) {
821 : struct FindSCEVSize {
822 : int Size = 0;
823 :
824 : FindSCEVSize() = default;
825 :
826 0 : bool follow(const SCEV *S) {
827 209 : ++Size;
828 : // Keep looking at all operands of S.
829 0 : return true;
830 : }
831 :
832 0 : bool isDone() const {
833 0 : return false;
834 : }
835 : };
836 :
837 72 : FindSCEVSize F;
838 72 : SCEVTraversal<FindSCEVSize> ST(F);
839 72 : ST.visitAll(S);
840 72 : return F.Size;
841 : }
842 :
843 : namespace {
844 :
845 : struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
846 : public:
847 : // Computes the Quotient and Remainder of the division of Numerator by
848 : // Denominator.
849 37763 : static void divide(ScalarEvolution &SE, const SCEV *Numerator,
850 : const SCEV *Denominator, const SCEV **Quotient,
851 : const SCEV **Remainder) {
852 : assert(Numerator && Denominator && "Uninitialized SCEV");
853 :
854 37763 : SCEVDivision D(SE, Numerator, Denominator);
855 :
856 : // Check for the trivial case here to avoid having to check for it in the
857 : // rest of the code.
858 37763 : if (Numerator == Denominator) {
859 11068 : *Quotient = D.One;
860 11068 : *Remainder = D.Zero;
861 13752 : return;
862 : }
863 :
864 26695 : if (Numerator->isZero()) {
865 2630 : *Quotient = D.Zero;
866 2630 : *Remainder = D.Zero;
867 2630 : return;
868 : }
869 :
870 : // A simple case when N/1. The quotient is N.
871 24065 : if (Denominator->isOne()) {
872 44 : *Quotient = Numerator;
873 44 : *Remainder = D.Zero;
874 44 : return;
875 : }
876 :
877 : // Split the Denominator when it is a product.
878 : if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
879 : const SCEV *Q, *R;
880 10 : *Quotient = Numerator;
881 14 : for (const SCEV *Op : T->operands()) {
882 12 : divide(SE, *Quotient, Op, &Q, &R);
883 12 : *Quotient = Q;
884 :
885 : // Bail out when the Numerator is not divisible by one of the terms of
886 : // the Denominator.
887 12 : if (!R->isZero()) {
888 8 : *Quotient = D.Zero;
889 8 : *Remainder = Numerator;
890 8 : return;
891 : }
892 : }
893 2 : *Remainder = D.Zero;
894 2 : return;
895 : }
896 :
897 24011 : D.visit(Numerator);
898 24011 : *Quotient = D.Quotient;
899 24011 : *Remainder = D.Remainder;
900 : }
901 :
902 : // Except in the trivial case described above, we do not know how to divide
903 : // Expr by Denominator for the following functions with empty implementation.
904 0 : void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
905 0 : void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
906 0 : void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
907 0 : void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
908 0 : void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
909 0 : void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
910 0 : void visitUnknown(const SCEVUnknown *Numerator) {}
911 0 : void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
912 :
913 3560 : void visitConstant(const SCEVConstant *Numerator) {
914 3560 : if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
915 : APInt NumeratorVal = Numerator->getAPInt();
916 : APInt DenominatorVal = D->getAPInt();
917 384 : uint32_t NumeratorBW = NumeratorVal.getBitWidth();
918 384 : uint32_t DenominatorBW = DenominatorVal.getBitWidth();
919 :
920 384 : if (NumeratorBW > DenominatorBW)
921 0 : DenominatorVal = DenominatorVal.sext(NumeratorBW);
922 384 : else if (NumeratorBW < DenominatorBW)
923 0 : NumeratorVal = NumeratorVal.sext(DenominatorBW);
924 :
925 384 : APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
926 384 : APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
927 384 : APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
928 384 : Quotient = SE.getConstant(QuotientVal);
929 384 : Remainder = SE.getConstant(RemainderVal);
930 : return;
931 : }
932 : }
933 :
934 9328 : void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
935 : const SCEV *StartQ, *StartR, *StepQ, *StepR;
936 9328 : if (!Numerator->isAffine())
937 13 : return cannotDivide(Numerator);
938 18654 : divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
939 9327 : divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
940 : // Bail out if the types do not match.
941 9327 : Type *Ty = Denominator->getType();
942 27969 : if (Ty != StartQ->getType() || Ty != StartR->getType() ||
943 27957 : Ty != StepQ->getType() || Ty != StepR->getType())
944 12 : return cannotDivide(Numerator);
945 18630 : Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
946 : Numerator->getNoWrapFlags());
947 18630 : Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
948 : Numerator->getNoWrapFlags());
949 : }
950 :
951 1079 : void visitAddExpr(const SCEVAddExpr *Numerator) {
952 : SmallVector<const SCEV *, 2> Qs, Rs;
953 1079 : Type *Ty = Denominator->getType();
954 :
955 3270 : for (const SCEV *Op : Numerator->operands()) {
956 : const SCEV *Q, *R;
957 2191 : divide(SE, Op, Denominator, &Q, &R);
958 :
959 : // Bail out if types do not match.
960 2191 : if (Ty != Q->getType() || Ty != R->getType())
961 0 : return cannotDivide(Numerator);
962 :
963 2191 : Qs.push_back(Q);
964 2191 : Rs.push_back(R);
965 : }
966 :
967 1079 : if (Qs.size() == 1) {
968 0 : Quotient = Qs[0];
969 0 : Remainder = Rs[0];
970 0 : return;
971 : }
972 :
973 1079 : Quotient = SE.getAddExpr(Qs);
974 1079 : Remainder = SE.getAddExpr(Rs);
975 : }
976 :
977 6996 : void visitMulExpr(const SCEVMulExpr *Numerator) {
978 : SmallVector<const SCEV *, 2> Qs;
979 6996 : Type *Ty = Denominator->getType();
980 :
981 : bool FoundDenominatorTerm = false;
982 24236 : for (const SCEV *Op : Numerator->operands()) {
983 : // Bail out if types do not match.
984 17240 : if (Ty != Op->getType())
985 0 : return cannotDivide(Numerator);
986 :
987 17240 : if (FoundDenominatorTerm) {
988 7174 : Qs.push_back(Op);
989 10304 : continue;
990 : }
991 :
992 : // Check whether Denominator divides one of the product operands.
993 : const SCEV *Q, *R;
994 10066 : divide(SE, Op, Denominator, &Q, &R);
995 10066 : if (!R->isZero()) {
996 3130 : Qs.push_back(Op);
997 3130 : continue;
998 : }
999 :
1000 : // Bail out if types do not match.
1001 6936 : if (Ty != Q->getType())
1002 0 : return cannotDivide(Numerator);
1003 :
1004 : FoundDenominatorTerm = true;
1005 6936 : Qs.push_back(Q);
1006 : }
1007 :
1008 6996 : if (FoundDenominatorTerm) {
1009 6936 : Remainder = Zero;
1010 6936 : if (Qs.size() == 1)
1011 0 : Quotient = Qs[0];
1012 : else
1013 6936 : Quotient = SE.getMulExpr(Qs);
1014 6936 : return;
1015 : }
1016 :
1017 60 : if (!isa<SCEVUnknown>(Denominator))
1018 24 : return cannotDivide(Numerator);
1019 :
1020 : // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1021 : ValueToValueMap RewriteMap;
1022 36 : RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1023 36 : cast<SCEVConstant>(Zero)->getValue();
1024 36 : Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1025 :
1026 36 : if (Remainder->isZero()) {
1027 : // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1028 0 : RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1029 0 : cast<SCEVConstant>(One)->getValue();
1030 0 : Quotient =
1031 0 : SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1032 0 : return;
1033 : }
1034 :
1035 : // Quotient is (Numerator - Remainder) divided by Denominator.
1036 : const SCEV *Q, *R;
1037 36 : const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1038 : // This SCEV does not seem to simplify: fail the division here.
1039 36 : if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1040 0 : return cannotDivide(Numerator);
1041 36 : divide(SE, Diff, Denominator, &Q, &R);
1042 36 : if (R != Zero)
1043 0 : return cannotDivide(Numerator);
1044 36 : Quotient = Q;
1045 : }
1046 :
1047 : private:
1048 37763 : SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1049 : const SCEV *Denominator)
1050 37763 : : SE(S), Denominator(Denominator) {
1051 37763 : Zero = SE.getZero(Denominator->getType());
1052 37763 : One = SE.getOne(Denominator->getType());
1053 :
1054 : // We generally do not know how to divide Expr by Denominator. We
1055 : // initialize the division to a "cannot divide" state to simplify the rest
1056 : // of the code.
1057 : cannotDivide(Numerator);
1058 37763 : }
1059 :
1060 : // Convenience function for giving up on the division. We set the quotient to
1061 : // be equal to zero and the remainder to be equal to the numerator.
1062 : void cannotDivide(const SCEV *Numerator) {
1063 37800 : Quotient = Zero;
1064 37 : Remainder = Numerator;
1065 : }
1066 :
1067 : ScalarEvolution &SE;
1068 : const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1069 : };
1070 :
1071 : } // end anonymous namespace
1072 :
1073 : //===----------------------------------------------------------------------===//
1074 : // Simple SCEV method implementations
1075 : //===----------------------------------------------------------------------===//
1076 :
1077 : /// Compute BC(It, K). The result has width W. Assume, K > 0.
1078 30456 : static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1079 : ScalarEvolution &SE,
1080 : Type *ResultTy) {
1081 : // Handle the simplest case efficiently.
1082 30456 : if (K == 1)
1083 27995 : return SE.getTruncateOrZeroExtend(It, ResultTy);
1084 :
1085 : // We are using the following formula for BC(It, K):
1086 : //
1087 : // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1088 : //
1089 : // Suppose, W is the bitwidth of the return value. We must be prepared for
1090 : // overflow. Hence, we must assure that the result of our computation is
1091 : // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1092 : // safe in modular arithmetic.
1093 : //
1094 : // However, this code doesn't use exactly that formula; the formula it uses
1095 : // is something like the following, where T is the number of factors of 2 in
1096 : // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1097 : // exponentiation:
1098 : //
1099 : // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1100 : //
1101 : // This formula is trivially equivalent to the previous formula. However,
1102 : // this formula can be implemented much more efficiently. The trick is that
1103 : // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1104 : // arithmetic. To do exact division in modular arithmetic, all we have
1105 : // to do is multiply by the inverse. Therefore, this step can be done at
1106 : // width W.
1107 : //
1108 : // The next issue is how to safely do the division by 2^T. The way this
1109 : // is done is by doing the multiplication step at a width of at least W + T
1110 : // bits. This way, the bottom W+T bits of the product are accurate. Then,
1111 : // when we perform the division by 2^T (which is equivalent to a right shift
1112 : // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1113 : // truncated out after the division by 2^T.
1114 : //
1115 : // In comparison to just directly using the first formula, this technique
1116 : // is much more efficient; using the first formula requires W * K bits,
1117 : // but this formula less than W + K bits. Also, the first formula requires
1118 : // a division step, whereas this formula only requires multiplies and shifts.
1119 : //
1120 : // It doesn't matter whether the subtraction step is done in the calculation
1121 : // width or the input iteration count's width; if the subtraction overflows,
1122 : // the result must be zero anyway. We prefer here to do it in the width of
1123 : // the induction variable because it helps a lot for certain cases; CodeGen
1124 : // isn't smart enough to ignore the overflow, which leads to much less
1125 : // efficient code if the width of the subtraction is wider than the native
1126 : // register width.
1127 : //
1128 : // (It's possible to not widen at all by pulling out factors of 2 before
1129 : // the multiplication; for example, K=2 can be calculated as
1130 : // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1131 : // extra arithmetic, so it's not an obvious win, and it gets
1132 : // much more complicated for K > 3.)
1133 :
1134 : // Protection from insane SCEVs; this bound is conservative,
1135 : // but it probably doesn't matter.
1136 2461 : if (K > 1000)
1137 0 : return SE.getCouldNotCompute();
1138 :
1139 2461 : unsigned W = SE.getTypeSizeInBits(ResultTy);
1140 :
1141 : // Calculate K! / 2^T and T; we divide out the factors of two before
1142 : // multiplying for calculating K! / 2^T to avoid overflow.
1143 : // Other overflow doesn't matter because we only care about the bottom
1144 : // W bits of the result.
1145 : APInt OddFactorial(W, 1);
1146 : unsigned T = 1;
1147 4195 : for (unsigned i = 3; i <= K; ++i) {
1148 1734 : APInt Mult(W, i);
1149 1734 : unsigned TwoFactors = Mult.countTrailingZeros();
1150 1734 : T += TwoFactors;
1151 : Mult.lshrInPlace(TwoFactors);
1152 1734 : OddFactorial *= Mult;
1153 : }
1154 :
1155 : // We need at least W + T bits for the multiplication step
1156 2461 : unsigned CalculationBits = W + T;
1157 :
1158 : // Calculate 2^T, at width T+W.
1159 2461 : APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1160 :
1161 : // Calculate the multiplicative inverse of K! / 2^T;
1162 : // this multiplication factor will perform the exact division by
1163 : // K! / 2^T.
1164 2461 : APInt Mod = APInt::getSignedMinValue(W+1);
1165 2461 : APInt MultiplyFactor = OddFactorial.zext(W+1);
1166 2461 : MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1167 2461 : MultiplyFactor = MultiplyFactor.trunc(W);
1168 :
1169 : // Calculate the product, at width T+W
1170 2461 : IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1171 : CalculationBits);
1172 2461 : const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1173 6656 : for (unsigned i = 1; i != K; ++i) {
1174 4195 : const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1175 4195 : Dividend = SE.getMulExpr(Dividend,
1176 : SE.getTruncateOrZeroExtend(S, CalculationTy));
1177 : }
1178 :
1179 : // Divide by 2^T
1180 2461 : const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1181 :
1182 : // Truncate the result, and divide by K! / 2^T.
1183 :
1184 2461 : return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1185 : SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1186 : }
1187 :
1188 : /// Return the value of this chain of recurrences at the specified iteration
1189 : /// number. We can evaluate this recurrence by multiplying each element in the
1190 : /// chain by the binomial coefficient corresponding to it. In other words, we
1191 : /// can evaluate {A,+,B,+,C,+,D} as:
1192 : ///
1193 : /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1194 : ///
1195 : /// where BC(It, k) stands for binomial coefficient.
1196 27995 : const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1197 : ScalarEvolution &SE) const {
1198 27995 : const SCEV *Result = getStart();
1199 58451 : for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1200 : // The computation is correct in the face of overflow provided that the
1201 : // multiplication is performed _after_ the evaluation of the binomial
1202 : // coefficient.
1203 30456 : const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1204 30456 : if (isa<SCEVCouldNotCompute>(Coeff))
1205 : return Coeff;
1206 :
1207 60912 : Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1208 : }
1209 : return Result;
1210 : }
1211 :
1212 : //===----------------------------------------------------------------------===//
1213 : // SCEV Expression folder implementations
1214 : //===----------------------------------------------------------------------===//
1215 :
1216 32650 : const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
1217 : Type *Ty) {
1218 : assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1219 : "This is not a truncating conversion!");
1220 : assert(isSCEVable(Ty) &&
1221 : "This is not a conversion to a SCEVable type!");
1222 32650 : Ty = getEffectiveSCEVType(Ty);
1223 :
1224 : FoldingSetNodeID ID;
1225 32650 : ID.AddInteger(scTruncate);
1226 32650 : ID.AddPointer(Op);
1227 32650 : ID.AddPointer(Ty);
1228 32650 : void *IP = nullptr;
1229 32650 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1230 :
1231 : // Fold if the operand is constant.
1232 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1233 14993 : return getConstant(
1234 29986 : cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1235 :
1236 : // trunc(trunc(x)) --> trunc(x)
1237 : if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1238 21 : return getTruncateExpr(ST->getOperand(), Ty);
1239 :
1240 : // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1241 : if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1242 279 : return getTruncateOrSignExtend(SS->getOperand(), Ty);
1243 :
1244 : // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1245 : if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1246 3133 : return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1247 :
1248 : // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1249 : // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1250 : // if after transforming we have at most one truncate, not counting truncates
1251 : // that replace other casts.
1252 11387 : if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1253 : auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1254 : SmallVector<const SCEV *, 4> Operands;
1255 : unsigned numTruncs = 0;
1256 9204 : for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1257 : ++i) {
1258 12340 : const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
1259 9102 : if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1260 1309 : numTruncs++;
1261 6170 : Operands.push_back(S);
1262 : }
1263 3034 : if (numTruncs < 2) {
1264 2878 : if (isa<SCEVAddExpr>(Op))
1265 1773 : return getAddExpr(Operands);
1266 1105 : else if (isa<SCEVMulExpr>(Op))
1267 1105 : return getMulExpr(Operands);
1268 : else
1269 0 : llvm_unreachable("Unexpected SCEV type for Op.");
1270 : }
1271 : // Although we checked in the beginning that ID is not in the cache, it is
1272 : // possible that during recursion and different modification ID was inserted
1273 : // into the cache. So if we find it, just return it.
1274 156 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1275 : return S;
1276 : }
1277 :
1278 : // If the input value is a chrec scev, truncate the chrec's operands.
1279 : if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1280 : SmallVector<const SCEV *, 4> Operands;
1281 10078 : for (const SCEV *Op : AddRec->operands())
1282 6724 : Operands.push_back(getTruncateExpr(Op, Ty));
1283 3354 : return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1284 : }
1285 :
1286 : // The cast wasn't folded; create an explicit cast node. We can reuse
1287 : // the existing insert position since if we get here, we won't have
1288 : // made any changes which would invalidate it.
1289 5155 : SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1290 5155 : Op, Ty);
1291 5155 : UniqueSCEVs.InsertNode(S, IP);
1292 5155 : addToLoopUseLists(S);
1293 5155 : return S;
1294 : }
1295 :
1296 : // Get the limit of a recurrence such that incrementing by Step cannot cause
1297 : // signed overflow as long as the value of the recurrence within the
1298 : // loop does not exceed this limit before incrementing.
1299 6357 : static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1300 : ICmpInst::Predicate *Pred,
1301 : ScalarEvolution *SE) {
1302 6357 : unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1303 6357 : if (SE->isKnownPositive(Step)) {
1304 4075 : *Pred = ICmpInst::ICMP_SLT;
1305 8154 : return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1306 4075 : SE->getSignedRangeMax(Step));
1307 : }
1308 2282 : if (SE->isKnownNegative(Step)) {
1309 2156 : *Pred = ICmpInst::ICMP_SGT;
1310 4312 : return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1311 2156 : SE->getSignedRangeMin(Step));
1312 : }
1313 : return nullptr;
1314 : }
1315 :
1316 : // Get the limit of a recurrence such that incrementing by Step cannot cause
1317 : // unsigned overflow as long as the value of the recurrence within the loop does
1318 : // not exceed this limit before incrementing.
1319 547 : static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1320 : ICmpInst::Predicate *Pred,
1321 : ScalarEvolution *SE) {
1322 547 : unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1323 547 : *Pred = ICmpInst::ICMP_ULT;
1324 :
1325 1094 : return SE->getConstant(APInt::getMinValue(BitWidth) -
1326 547 : SE->getUnsignedRangeMax(Step));
1327 : }
1328 :
1329 : namespace {
1330 :
1331 : struct ExtendOpTraitsBase {
1332 : typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1333 : unsigned);
1334 : };
1335 :
1336 : // Used to make code generic over signed and unsigned overflow.
1337 : template <typename ExtendOp> struct ExtendOpTraits {
1338 : // Members present:
1339 : //
1340 : // static const SCEV::NoWrapFlags WrapType;
1341 : //
1342 : // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1343 : //
1344 : // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1345 : // ICmpInst::Predicate *Pred,
1346 : // ScalarEvolution *SE);
1347 : };
1348 :
1349 : template <>
1350 : struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1351 : static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1352 :
1353 : static const GetExtendExprTy GetExtendExpr;
1354 :
1355 133 : static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1356 : ICmpInst::Predicate *Pred,
1357 : ScalarEvolution *SE) {
1358 133 : return getSignedOverflowLimitForStep(Step, Pred, SE);
1359 : }
1360 : };
1361 :
1362 : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1363 : SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1364 :
1365 : template <>
1366 : struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1367 : static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1368 :
1369 : static const GetExtendExprTy GetExtendExpr;
1370 :
1371 201 : static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1372 : ICmpInst::Predicate *Pred,
1373 : ScalarEvolution *SE) {
1374 201 : return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1375 : }
1376 : };
1377 :
1378 : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1379 : SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1380 :
1381 : } // end anonymous namespace
1382 :
1383 : // The recurrence AR has been shown to have no signed/unsigned wrap or something
1384 : // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1385 : // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1386 : // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1387 : // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1388 : // expression "Step + sext/zext(PreIncAR)" is congruent with
1389 : // "sext/zext(PostIncAR)"
1390 : template <typename ExtendOpTy>
1391 0 : static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1392 : ScalarEvolution *SE, unsigned Depth) {
1393 : auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1394 : auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1395 :
1396 0 : const Loop *L = AR->getLoop();
1397 0 : const SCEV *Start = AR->getStart();
1398 0 : const SCEV *Step = AR->getStepRecurrence(*SE);
1399 :
1400 : // Check for a simple looking step prior to loop entry.
1401 : const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1402 : if (!SA)
1403 0 : return nullptr;
1404 :
1405 : // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1406 : // subtraction is expensive. For this purpose, perform a quick and dirty
1407 : // difference, by checking for Step in the operand list.
1408 : SmallVector<const SCEV *, 4> DiffOps;
1409 0 : for (const SCEV *Op : SA->operands())
1410 0 : if (Op != Step)
1411 0 : DiffOps.push_back(Op);
1412 :
1413 0 : if (DiffOps.size() == SA->getNumOperands())
1414 0 : return nullptr;
1415 :
1416 : // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1417 : // `Step`:
1418 :
1419 : // 1. NSW/NUW flags on the step increment.
1420 : auto PreStartFlags =
1421 0 : ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1422 0 : const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1423 0 : const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1424 : SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1425 :
1426 : // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1427 : // "S+X does not sign/unsign-overflow".
1428 : //
1429 :
1430 0 : const SCEV *BECount = SE->getBackedgeTakenCount(L);
1431 0 : if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1432 0 : !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1433 0 : return PreStart;
1434 :
1435 : // 2. Direct overflow check on the step operation's expression.
1436 0 : unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1437 0 : Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1438 0 : const SCEV *OperandExtendedStart =
1439 : SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1440 : (SE->*GetExtendExpr)(Step, WideTy, Depth));
1441 0 : if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1442 0 : if (PreAR && AR->getNoWrapFlags(WrapType)) {
1443 : // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1444 : // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1445 : // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1446 : const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1447 : }
1448 0 : return PreStart;
1449 : }
1450 :
1451 : // 3. Loop precondition.
1452 : ICmpInst::Predicate Pred;
1453 : const SCEV *OverflowLimit =
1454 0 : ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1455 :
1456 0 : if (OverflowLimit &&
1457 0 : SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1458 0 : return PreStart;
1459 :
1460 : return nullptr;
1461 : }
1462 0 :
1463 : // Get the normalized zero or sign extended expression for this AddRec's Start.
1464 : template <typename ExtendOpTy>
1465 : static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1466 : ScalarEvolution *SE,
1467 0 : unsigned Depth) {
1468 0 : auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1469 0 :
1470 : const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1471 : if (!PreStart)
1472 : return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1473 :
1474 0 : return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1475 : Depth),
1476 : (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1477 : }
1478 :
1479 : // Try to prove away overflow by looking at "nearby" add recurrences. A
1480 0 : // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1481 0 : // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1482 0 : //
1483 : // Formally:
1484 0 : //
1485 0 : // {S,+,X} == {S-T,+,X} + T
1486 : // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1487 : //
1488 : // If ({S-T,+,X} + T) does not overflow ... (1)
1489 : //
1490 : // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1491 : //
1492 0 : // If {S-T,+,X} does not overflow ... (2)
1493 0 : //
1494 0 : // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1495 : // == {Ext(S-T)+Ext(T),+,Ext(X)}
1496 : //
1497 : // If (S-T)+T does not overflow ... (3)
1498 : //
1499 : // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1500 : // == {Ext(S),+,Ext(X)} == LHS
1501 0 : //
1502 0 : // Thus, if (1), (2) and (3) are true for some T, then
1503 0 : // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1504 0 : //
1505 : // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1506 : // does not overflow" restricted to the 0th iteration. Therefore we only need
1507 0 : // to check for (1) and (2).
1508 0 : //
1509 0 : // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1510 : // is `Delta` (defined below).
1511 : template <typename ExtendOpTy>
1512 0 : bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1513 0 : const SCEV *Step,
1514 : const Loop *L) {
1515 : auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1516 :
1517 : // We restrict `Start` to a constant to prevent SCEV from spending too much
1518 : // time here. It is correct (but more expensive) to continue with a
1519 0 : // non-constant `Start` and do a general SCEV subtraction to compute
1520 : // `PreStart` below.
1521 : const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1522 : if (!StartC)
1523 : return false;
1524 :
1525 0 : APInt StartAI = StartC->getAPInt();
1526 :
1527 0 : for (unsigned Delta : {-2, -1, 1, 2}) {
1528 0 : const SCEV *PreStart = getConstant(StartAI - Delta);
1529 0 :
1530 : FoldingSetNodeID ID;
1531 : ID.AddInteger(scAddRecExpr);
1532 : ID.AddPointer(PreStart);
1533 0 : ID.AddPointer(Step);
1534 : ID.AddPointer(L);
1535 : void *IP = nullptr;
1536 : const auto *PreAR =
1537 : static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1538 0 :
1539 0 : // Give up if we don't already have the add recurrence we need because
1540 0 : // actually constructing an add recurrence is relatively expensive.
1541 : if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1542 : const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1543 : ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1544 : const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1545 0 : DeltaS, &Pred, this);
1546 : if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1547 : return true;
1548 : }
1549 : }
1550 :
1551 0 : return false;
1552 0 : }
1553 0 :
1554 : // Finds an integer D for an expression (C + x + y + ...) such that the top
1555 0 : // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1556 0 : // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1557 : // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1558 : // the (C + x + y + ...) expression is \p WholeAddExpr.
1559 : static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1560 : const SCEVConstant *ConstantTerm,
1561 : const SCEVAddExpr *WholeAddExpr) {
1562 : const APInt C = ConstantTerm->getAPInt();
1563 0 : const unsigned BitWidth = C.getBitWidth();
1564 0 : // Find number of trailing zeros of (x + y + ...) w/o the C first:
1565 0 : uint32_t TZ = BitWidth;
1566 : for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1567 : TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1568 : if (TZ) {
1569 : // Set D to be as many least significant bits of C as possible while still
1570 : // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1571 : return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1572 0 : }
1573 0 : return APInt(BitWidth, 0);
1574 0 : }
1575 0 :
1576 : // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1577 : // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1578 0 : // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1579 0 : // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1580 0 : static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1581 : const APInt &ConstantStart,
1582 : const SCEV *Step) {
1583 0 : const unsigned BitWidth = ConstantStart.getBitWidth();
1584 0 : const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1585 : if (TZ)
1586 : return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1587 : : ConstantStart;
1588 : return APInt(BitWidth, 0);
1589 : }
1590 0 :
1591 : const SCEV *
1592 : ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1593 : assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1594 : "This is not an extending conversion!");
1595 : assert(isSCEVable(Ty) &&
1596 : "This is not a conversion to a SCEVable type!");
1597 : Ty = getEffectiveSCEVType(Ty);
1598 0 :
1599 0 : // Fold if the operand is constant.
1600 0 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1601 : return getConstant(
1602 : cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1603 :
1604 : // zext(zext(x)) --> zext(x)
1605 : if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1606 : return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1607 33222 :
1608 : // Before doing any expensive analysis, check to see if we've already
1609 : // computed a SCEV for this Op and Ty.
1610 : FoldingSetNodeID ID;
1611 : ID.AddInteger(scZeroExtend);
1612 33222 : ID.AddPointer(Op);
1613 33222 : ID.AddPointer(Ty);
1614 65726 : void *IP = nullptr;
1615 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1616 : if (Depth > MaxExtDepth) {
1617 : SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1618 359 : Op, Ty);
1619 : UniqueSCEVs.InsertNode(S, IP);
1620 11231 : addToLoopUseLists(S);
1621 : return S;
1622 : }
1623 :
1624 : // zext(trunc(x)) --> zext(x) or x or trunc(x)
1625 11231 : if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1626 11231 : // It's possible the bits taken off by the truncate were all zero bits. If
1627 21866 : // so, we should be able to simplify this further.
1628 : const SCEV *X = ST->getOperand();
1629 : ConstantRange CR = getUnsignedRange(X);
1630 : unsigned TruncBits = getTypeSizeInBits(ST->getType());
1631 298 : unsigned NewBits = getTypeSizeInBits(Ty);
1632 : if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1633 21991 : CR.zextOrTrunc(NewBits)))
1634 : return getTruncateOrZeroExtend(X, Ty);
1635 : }
1636 :
1637 : // If the input value is a chrec scev, and we can prove that the value
1638 21991 : // did not overflow the old, smaller, value, we can zero extend all of the
1639 21991 : // operands (often constants). This allows analysis of something like
1640 43860 : // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1641 : if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1642 : if (AR->isAffine()) {
1643 : const SCEV *Start = AR->getStart();
1644 61 : const SCEV *Step = AR->getStepRecurrence(*this);
1645 : unsigned BitWidth = getTypeSizeInBits(AR->getType());
1646 : const Loop *L = AR->getLoop();
1647 :
1648 : if (!AR->hasNoUnsignedWrap()) {
1649 : auto NewFlags = proveNoWrapViaConstantRanges(AR);
1650 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1651 : }
1652 :
1653 : // If we have special knowledge that this addrec won't overflow,
1654 : // we don't need to do any further analysis.
1655 : if (AR->hasNoUnsignedWrap())
1656 : return getAddRecExpr(
1657 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1658 : getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1659 :
1660 : // Check whether the backedge-taken count is SCEVCouldNotCompute.
1661 : // Note that this serves two purposes: It filters out loops that are
1662 : // simply not analyzable, and it covers the case where this code is
1663 : // being called from within backedge-taken count analysis, such that
1664 : // attempting to ask for the backedge-taken count would likely result
1665 : // in infinite recursion. In the later case, the analysis code will
1666 : // cope with a conservative value, and it will take care to purge
1667 : // that value once it has finished.
1668 : const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
1669 : if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1670 : // Manually compute the final value for AR, checking for
1671 : // overflow.
1672 :
1673 : // Check whether the backedge-taken count can be losslessly casted to
1674 : // the addrec's type. The count is always unsigned.
1675 : const SCEV *CastedMaxBECount =
1676 : getTruncateOrZeroExtend(MaxBECount, Start->getType());
1677 : const SCEV *RecastedMaxBECount =
1678 : getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1679 : if (MaxBECount == RecastedMaxBECount) {
1680 19590 : Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1681 : // Check whether Start+Step*MaxBECount has no unsigned overflow.
1682 : const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1683 : SCEV::FlagAnyWrap, Depth + 1);
1684 : const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1685 : SCEV::FlagAnyWrap,
1686 : Depth + 1),
1687 : WideTy, Depth + 1);
1688 : const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1689 : const SCEV *WideMaxBECount =
1690 : getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1691 : const SCEV *OperandExtendedAdd =
1692 : getAddExpr(WideStart,
1693 : getMulExpr(WideMaxBECount,
1694 : getZeroExtendExpr(Step, WideTy, Depth + 1),
1695 32359 : SCEV::FlagAnyWrap, Depth + 1),
1696 77664 : SCEV::FlagAnyWrap, Depth + 1);
1697 : if (ZAdd == OperandExtendedAdd) {
1698 : // Cache knowledge of AR NUW, which is propagated to this AddRec.
1699 25888 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1700 25888 : // Return the expression with the addrec on the outside.
1701 25888 : return getAddRecExpr(
1702 25888 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1703 25888 : Depth + 1),
1704 : getZeroExtendExpr(Step, Ty, Depth + 1), L,
1705 : AR->getNoWrapFlags());
1706 : }
1707 : // Similar to above, only this time treat the step value as signed.
1708 : // This covers loops that count down.
1709 25888 : OperandExtendedAdd =
1710 460 : getAddExpr(WideStart,
1711 230 : getMulExpr(WideMaxBECount,
1712 201 : getSignExtendExpr(Step, WideTy, Depth + 1),
1713 : SCEV::FlagAnyWrap, Depth + 1),
1714 230 : SCEV::FlagAnyWrap, Depth + 1);
1715 1 : if (ZAdd == OperandExtendedAdd) {
1716 : // Cache knowledge of AR NW, which is propagated to this AddRec.
1717 : // Negative step causes unsigned wrap, but it still can't self-wrap.
1718 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1719 : // Return the expression with the addrec on the outside.
1720 : return getAddRecExpr(
1721 10653 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1722 : Depth + 1),
1723 : getSignExtendExpr(Step, Ty, Depth + 1), L,
1724 : AR->getNoWrapFlags());
1725 : }
1726 : }
1727 : }
1728 :
1729 : // Normally, in the cases we can prove no-overflow via a
1730 : // backedge guarding condition, we can also compute a backedge
1731 : // taken count for the loop. The exceptions are assumptions and
1732 : // guards present in the loop -- SCEV is not great at exploiting
1733 : // these to compute max backedge taken counts, but can still use
1734 : // these to prove lack of overflow. Use this fact to avoid
1735 : // doing extra work that may not pay off.
1736 16555 : if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1737 39732 : !AC.assumptions().empty()) {
1738 : // If the backedge is guarded by a comparison with the pre-inc
1739 : // value the addrec is safe. Also, if the entry is guarded by
1740 13244 : // a comparison with the start value and the backedge is
1741 13244 : // guarded by a comparison with the post-inc value, the addrec
1742 13244 : // is safe.
1743 13244 : if (isKnownPositive(Step)) {
1744 13244 : const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1745 : getUnsignedRangeMax(Step));
1746 : if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1747 : isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1748 : // Cache knowledge of AR NUW, which is propagated to this
1749 : // AddRec.
1750 13244 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1751 58 : // Return the expression with the addrec on the outside.
1752 29 : return getAddRecExpr(
1753 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1754 : Depth + 1),
1755 29 : getZeroExtendExpr(Step, Ty, Depth + 1), L,
1756 0 : AR->getNoWrapFlags());
1757 : }
1758 : } else if (isKnownNegative(Step)) {
1759 : const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1760 : getSignedRangeMin(Step));
1761 : if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1762 8937 : isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1763 : // Cache knowledge of AR NW, which is propagated to this
1764 : // AddRec. Negative step causes unsigned wrap, but it
1765 : // still can't self-wrap.
1766 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1767 : // Return the expression with the addrec on the outside.
1768 : return getAddRecExpr(
1769 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1770 : Depth + 1),
1771 : getSignExtendExpr(Step, Ty, Depth + 1), L,
1772 : AR->getNoWrapFlags());
1773 : }
1774 : }
1775 : }
1776 :
1777 15804 : // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1778 37932 : // if D + (C - D + Step * n) could be proven to not unsigned wrap
1779 : // where D maximizes the number of trailing zeros of (C - D + Step * n)
1780 : if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1781 12644 : const APInt &C = SC->getAPInt();
1782 12644 : const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1783 12644 : if (D != 0) {
1784 12644 : const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1785 12644 : const SCEV *SResidual =
1786 : getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1787 : const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1788 : return getAddExpr(SZExtD, SZExtR,
1789 : (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1790 : Depth + 1);
1791 12644 : }
1792 402 : }
1793 201 :
1794 201 : if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1795 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1796 201 : return getAddRecExpr(
1797 1 : getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1798 : getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1799 : }
1800 : }
1801 :
1802 : // zext(A % B) --> zext(A) % zext(B)
1803 : {
1804 : const SCEV *LHS;
1805 : const SCEV *RHS;
1806 : if (matchURem(Op, LHS, RHS))
1807 : return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1808 : getZeroExtendExpr(RHS, Ty, Depth + 1));
1809 13695 : }
1810 :
1811 : // zext(A / B) --> zext(A) / zext(B).
1812 : if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1813 13695 : return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1814 : getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1815 13695 :
1816 27820 : if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1817 42165 : // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1818 13695 : if (SA->hasNoUnsignedWrap()) {
1819 : // If the addition does not unsign overflow then we can, by definition,
1820 : // commute the zero extension with the addition operation.
1821 5052 : SmallVector<const SCEV *, 4> Ops;
1822 : for (const auto *Op : SA->operands())
1823 : Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1824 : return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1825 : }
1826 :
1827 : // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1828 : // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1829 : // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1830 9342 : //
1831 : // Often address arithmetics contain expressions like
1832 : // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1833 9342 : // This transformation is useful while proving that such expressions are
1834 9342 : // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1835 9342 : if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1836 10234 : const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1837 10234 : if (D != 0) {
1838 : const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1839 : const SCEV *SResidual =
1840 : getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1841 : const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1842 289751 : return getAddExpr(SZExtD, SZExtR,
1843 : (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1844 : Depth + 1);
1845 : }
1846 : }
1847 289751 : }
1848 :
1849 : if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1850 : // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1851 143850 : if (SM->hasNoUnsignedWrap()) {
1852 287700 : // If the multiply does not unsign overflow then we can, by definition,
1853 : // commute the zero extension with the multiply operation.
1854 : SmallVector<const SCEV *, 4> Ops;
1855 : for (const auto *Op : SM->operands())
1856 8878 : Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1857 : return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1858 : }
1859 :
1860 : // zext(2^K * (trunc X to iN)) to iM ->
1861 137023 : // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1862 137023 : //
1863 137023 : // Proof:
1864 137023 : //
1865 137023 : // zext(2^K * (trunc X to iN)) to iM
1866 78755 : // = zext((trunc X to iN) << K) to iM
1867 12 : // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1868 12 : // (because shl removes the top K bits)
1869 12 : // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1870 12 : // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1871 12 : //
1872 : if (SM->getNumOperands() == 2)
1873 : if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1874 : if (MulLHS->getAPInt().isPowerOf2())
1875 : if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1876 : int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1877 : MulLHS->getAPInt().logBase2();
1878 2527 : Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1879 4650 : return getMulExpr(
1880 2527 : getZeroExtendExpr(MulLHS, Ty),
1881 2527 : getZeroExtendExpr(
1882 7581 : getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1883 5054 : SCEV::FlagNUW, Depth + 1);
1884 404 : }
1885 : }
1886 :
1887 : // The cast wasn't folded; create an explicit cast node.
1888 : // Recompute the insert position, as it may have been invalidated.
1889 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1890 : SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1891 : Op, Ty);
1892 32596 : UniqueSCEVs.InsertNode(S, IP);
1893 32517 : addToLoopUseLists(S);
1894 32517 : return S;
1895 32517 : }
1896 32517 :
1897 : const SCEV *
1898 32517 : ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1899 25399 : assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1900 : "This is not an extending conversion!");
1901 : assert(isSCEVable(Ty) &&
1902 : "This is not a conversion to a SCEVable type!");
1903 : Ty = getEffectiveSCEVType(Ty);
1904 :
1905 32517 : // Fold if the operand is constant.
1906 9545 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1907 : return getConstant(
1908 9545 : cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1909 :
1910 : // sext(sext(x)) --> sext(x)
1911 : if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1912 : return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1913 :
1914 : // sext(zext(x)) --> zext(x)
1915 : if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1916 : return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1917 :
1918 22972 : // Before doing any expensive analysis, check to see if we've already
1919 22972 : // computed a SCEV for this Op and Ty.
1920 : FoldingSetNodeID ID;
1921 : ID.AddInteger(scSignExtend);
1922 : ID.AddPointer(Op);
1923 : ID.AddPointer(Ty);
1924 : void *IP = nullptr;
1925 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1926 18510 : // Limit recursion depth.
1927 : if (Depth > MaxExtDepth) {
1928 18510 : SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1929 18510 : Op, Ty);
1930 17396 : UniqueSCEVs.InsertNode(S, IP);
1931 : addToLoopUseLists(S);
1932 17396 : return S;
1933 : }
1934 17396 :
1935 : // sext(trunc(x)) --> sext(x) or x or trunc(x)
1936 : if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1937 : // It's possible the bits taken off by the truncate were all sign bits. If
1938 17396 : // so, we should be able to simplify this further.
1939 : const SCEV *X = ST->getOperand();
1940 17396 : ConstantRange CR = getSignedRange(X);
1941 : unsigned TruncBits = getTypeSizeInBits(ST->getType());
1942 17396 : unsigned NewBits = getTypeSizeInBits(Ty);
1943 : if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1944 : CR.sextOrTrunc(NewBits)))
1945 : return getTruncateOrSignExtend(X, Ty);
1946 : }
1947 17396 :
1948 : if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1949 : // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1950 : if (SA->hasNoSignedWrap()) {
1951 906 : // If the addition does not sign overflow then we can, by definition,
1952 : // commute the sign extension with the addition operation.
1953 : SmallVector<const SCEV *, 4> Ops;
1954 : for (const auto *Op : SA->operands())
1955 906 : Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1956 : return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1957 : }
1958 :
1959 : // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1960 16490 : // if D + (C - D + x + y + ...) could be proven to not signed wrap
1961 : // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1962 : //
1963 : // For instance, this will bring two seemingly different expressions:
1964 : // 1 + sext(5 + 20 * %x + 24 * %y) and
1965 16490 : // sext(6 + 20 * %x + 24 * %y)
1966 : // to the same form:
1967 : // 2 + sext(4 + 20 * %x + 24 * %y)
1968 : if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1969 : const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1970 1083 : if (D != 0) {
1971 : const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1972 : const SCEV *SResidual =
1973 : getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1974 1083 : const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1975 : return getAddExpr(SSExtD, SSExtR,
1976 : (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1977 : Depth + 1);
1978 : }
1979 : }
1980 : }
1981 : // If the input value is a chrec scev, and we can prove that the value
1982 : // did not overflow the old, smaller, value, we can sign extend all of the
1983 : // operands (often constants). This allows analysis of something like
1984 : // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1985 : if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1986 25436 : if (AR->isAffine()) {
1987 4453 : const SCEV *Start = AR->getStart();
1988 : const SCEV *Step = AR->getStepRecurrence(*this);
1989 : unsigned BitWidth = getTypeSizeInBits(AR->getType());
1990 : const Loop *L = AR->getLoop();
1991 :
1992 : if (!AR->hasNoSignedWrap()) {
1993 16563 : auto NewFlags = proveNoWrapViaConstantRanges(AR);
1994 6946 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1995 3473 : }
1996 6900 :
1997 3427 : // If we have special knowledge that this addrec won't overflow,
1998 : // we don't need to do any further analysis.
1999 : if (AR->hasNoSignedWrap())
2000 : return getAddRecExpr(
2001 : getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2002 82 : getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2003 :
2004 : // Check whether the backedge-taken count is SCEVCouldNotCompute.
2005 : // Note that this serves two purposes: It filters out loops that are
2006 82 : // simply not analyzable, and it covers the case where this code is
2007 : // being called from within backedge-taken count analysis, such that
2008 13090 : // attempting to ask for the backedge-taken count would likely result
2009 25872 : // in infinite recursion. In the later case, the analysis code will
2010 12936 : // cope with a conservative value, and it will take care to purge
2011 15659 : // that value once it has finished.
2012 2723 : const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
2013 : if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2014 : // Manually compute the final value for AR, checking for
2015 : // overflow.
2016 :
2017 : // Check whether the backedge-taken count can be losslessly casted to
2018 10374 : // the addrec's type. The count is always unsigned.
2019 : const SCEV *CastedMaxBECount =
2020 : getTruncateOrZeroExtend(MaxBECount, Start->getType());
2021 : const SCEV *RecastedMaxBECount =
2022 10374 : getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
2023 : if (MaxBECount == RecastedMaxBECount) {
2024 : Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2025 : // Check whether Start+Step*MaxBECount has no signed overflow.
2026 : const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2027 : SCEV::FlagAnyWrap, Depth + 1);
2028 : const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2029 : SCEV::FlagAnyWrap,
2030 : Depth + 1),
2031 : WideTy, Depth + 1);
2032 4751 : const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2033 4751 : const SCEV *WideMaxBECount =
2034 1590 : getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2035 : const SCEV *OperandExtendedAdd =
2036 4770 : getAddExpr(WideStart,
2037 1590 : getMulExpr(WideMaxBECount,
2038 1590 : getSignExtendExpr(Step, WideTy, Depth + 1),
2039 : SCEV::FlagAnyWrap, Depth + 1),
2040 : SCEV::FlagAnyWrap, Depth + 1);
2041 : if (SAdd == OperandExtendedAdd) {
2042 : // Cache knowledge of AR NSW, which is propagated to this AddRec.
2043 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2044 8937 : // Return the expression with the addrec on the outside.
2045 : return getAddRecExpr(
2046 1 : getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2047 : Depth + 1),
2048 1 : getSignExtendExpr(Step, Ty, Depth + 1), L,
2049 : AR->getNoWrapFlags());
2050 : }
2051 : // Similar to above, only this time treat the step value as unsigned.
2052 : // This covers loops that count up with an unsigned step.
2053 : OperandExtendedAdd =
2054 : getAddExpr(WideStart,
2055 : getMulExpr(WideMaxBECount,
2056 54758 : getZeroExtendExpr(Step, WideTy, Depth + 1),
2057 41 : SCEV::FlagAnyWrap, Depth + 1),
2058 41 : SCEV::FlagAnyWrap, Depth + 1);
2059 : if (SAdd == OperandExtendedAdd) {
2060 : // If AR wraps around then
2061 : //
2062 : // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2063 6460 : // => SAdd != OperandExtendedAdd
2064 6460 : //
2065 : // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2066 : // (SAdd == OperandExtendedAdd => AR is NW)
2067 :
2068 11436 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2069 :
2070 : // Return the expression with the addrec on the outside.
2071 : return getAddRecExpr(
2072 2103 : getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2073 1402 : Depth + 1),
2074 701 : getZeroExtendExpr(Step, Ty, Depth + 1), L,
2075 : AR->getNoWrapFlags());
2076 : }
2077 : }
2078 : }
2079 :
2080 : // Normally, in the cases we can prove no-overflow via a
2081 : // backedge guarding condition, we can also compute a backedge
2082 : // taken count for the loop. The exceptions are assumptions and
2083 : // guards present in the loop -- SCEV is not great at exploiting
2084 : // these to compute max backedge taken counts, but can still use
2085 10735 : // these to prove lack of overflow. Use this fact to avoid
2086 8303 : // doing extra work that may not pay off.
2087 8303 :
2088 412 : if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2089 : !AC.assumptions().empty()) {
2090 824 : // If the backedge is guarded by a comparison with the pre-inc
2091 412 : // value the addrec is safe. Also, if the entry is guarded by
2092 412 : // a comparison with the start value and the backedge is
2093 : // guarded by a comparison with the post-inc value, the addrec
2094 : // is safe.
2095 : ICmpInst::Predicate Pred;
2096 : const SCEV *OverflowLimit =
2097 : getSignedOverflowLimitForStep(Step, &Pred, this);
2098 : if (OverflowLimit &&
2099 : (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2100 : isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2101 6061 : // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2102 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2103 : return getAddRecExpr(
2104 : getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2105 4563 : getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2106 3042 : }
2107 1521 : }
2108 :
2109 : // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2110 : // if D + (C - D + Step * n) could be proven to not signed wrap
2111 : // where D maximizes the number of trailing zeros of (C - D + Step * n)
2112 : if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2113 : const APInt &C = SC->getAPInt();
2114 : const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2115 : if (D != 0) {
2116 : const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2117 : const SCEV *SResidual =
2118 : getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2119 : const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2120 : return getAddExpr(SSExtD, SSExtR,
2121 : (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2122 4540 : Depth + 1);
2123 4513 : }
2124 2973 : }
2125 :
2126 10 : if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2127 : const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2128 10 : return getAddRecExpr(
2129 10 : getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2130 : getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2131 : }
2132 : }
2133 10 :
2134 : // If the input value is provably positive and we could not simplify
2135 : // away the sext build a zext instead.
2136 : if (isKnownNonNegative(Op))
2137 : return getZeroExtendExpr(Op, Ty, Depth + 1);
2138 :
2139 45613 : // The cast wasn't folded; create an explicit cast node.
2140 44730 : // Recompute the insert position, as it may have been invalidated.
2141 44730 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2142 44730 : SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2143 44730 : Op, Ty);
2144 44730 : UniqueSCEVs.InsertNode(S, IP);
2145 : addToLoopUseLists(S);
2146 : return S;
2147 : }
2148 168293 :
2149 : /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2150 : /// unspecified bits out to the given type.
2151 : const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2152 : Type *Ty) {
2153 168293 : assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2154 : "This is not an extending conversion!");
2155 : assert(isSCEVable(Ty) &&
2156 : "This is not a conversion to a SCEVable type!");
2157 103167 : Ty = getEffectiveSCEVType(Ty);
2158 206334 :
2159 : // Sign-extend negative constants.
2160 : if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2161 : if (SC->getAPInt().isNegative())
2162 278 : return getSignExtendExpr(Op, Ty);
2163 :
2164 : // Peel off a truncate cast.
2165 : if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2166 250 : const SCEV *NewOp = T->getOperand();
2167 : if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2168 : return getAnyExtendExpr(NewOp, Ty);
2169 : return getTruncateOrNoop(NewOp, Ty);
2170 : }
2171 64598 :
2172 64598 : // Next try a zext cast. If the cast is folded, use it.
2173 64598 : const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2174 64598 : if (!isa<SCEVZeroExtendExpr>(ZExt))
2175 64598 : return ZExt;
2176 :
2177 48412 : // Next try a sext cast. If the cast is folded, use it.
2178 4 : const SCEV *SExt = getSignExtendExpr(Op, Ty);
2179 4 : if (!isa<SCEVSignExtendExpr>(SExt))
2180 4 : return SExt;
2181 4 :
2182 4 : // Force the cast to be folded into the operands of an addrec.
2183 : if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2184 : SmallVector<const SCEV *, 4> Ops;
2185 : for (const SCEV *Op : AR->operands())
2186 : Ops.push_back(getAnyExtendExpr(Op, Ty));
2187 : return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2188 : }
2189 426 :
2190 847 : // If the expression is obviously signed, use the sext cast value.
2191 426 : if (isa<SCEVSMaxExpr>(Op))
2192 426 : return SExt;
2193 1278 :
2194 852 : // Absent any other information, use the zext cast value.
2195 5 : return ZExt;
2196 : }
2197 :
2198 : /// Process the given Ops list, which is a list of operands to be added under
2199 : /// the given scale, update the given map. This is a helper function for
2200 7350 : /// getAddRecExpr. As an example of what it does, given a sequence of operands
2201 : /// that would form an add expression like this:
2202 : ///
2203 : /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2204 1983 : ///
2205 1322 : /// where A and B are constants, update the map with these values:
2206 661 : ///
2207 : /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2208 : ///
2209 : /// and add 13 + A*B*29 to AccumulatedConstant.
2210 : /// This will allow getAddRecExpr to produce this:
2211 : ///
2212 : /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2213 : ///
2214 : /// This form often exposes folding opportunities that are hidden in
2215 : /// the original operand list.
2216 : ///
2217 : /// Return true iff it appears that any interesting folding opportunities
2218 6689 : /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2219 5392 : /// the common case where no interesting opportunities are present, and
2220 5392 : /// is also used as a check to avoid infinite recursion.
2221 197 : static bool
2222 : CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2223 394 : SmallVectorImpl<const SCEV *> &NewOps,
2224 197 : APInt &AccumulatedConstant,
2225 197 : const SCEV *const *Ops, size_t NumOperands,
2226 : const APInt &Scale,
2227 : ScalarEvolution &SE) {
2228 : bool Interesting = false;
2229 :
2230 : // Iterate over the add operands. They are sorted, with constants first.
2231 : unsigned i = 0;
2232 : while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2233 : ++i;
2234 : // Pull a buried constant out to the outside.
2235 : if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2236 23225 : Interesting = true;
2237 23164 : AccumulatedConstant += Scale * C->getAPInt();
2238 23164 : }
2239 23164 :
2240 23164 : // Next comes everything else. We're especially interested in multiplies
2241 : // here, but they're in the middle, so just visit the rest with one loop.
2242 23164 : for (; i != NumOperands; ++i) {
2243 15153 : const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2244 : if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2245 : APInt NewScale =
2246 : Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2247 : if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2248 : // A multiplication of a constant with another add; recurse.
2249 23164 : const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2250 10757 : Interesting |=
2251 : CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2252 10757 : Add->op_begin(), Add->getNumOperands(),
2253 : NewScale, SE);
2254 : } else {
2255 : // A multiplication of a constant with some other value. Update
2256 : // the map.
2257 : SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2258 : const SCEV *Key = SE.getMulExpr(MulOps);
2259 : auto Pair = M.insert({Key, NewScale});
2260 : if (Pair.second) {
2261 : NewOps.push_back(Pair.first->first);
2262 12407 : } else {
2263 12407 : Pair.first->second += NewScale;
2264 : // The map already had an entry for this value, which may indicate
2265 : // a folding opportunity.
2266 : Interesting = true;
2267 : }
2268 : }
2269 : } else {
2270 6505 : // An ordinary operand. Update the map.
2271 : std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2272 6505 : M.insert({Ops[i], Scale});
2273 6505 : if (Pair.second) {
2274 5990 : NewOps.push_back(Pair.first->first);
2275 : } else {
2276 5990 : Pair.first->second += Scale;
2277 : // The map already had an entry for this value, which may indicate
2278 5990 : // a folding opportunity.
2279 : Interesting = true;
2280 : }
2281 : }
2282 5990 : }
2283 :
2284 5990 : return Interesting;
2285 : }
2286 5990 :
2287 : // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2288 : // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2289 : // can't-overflow flags for the operation if possible.
2290 : static SCEV::NoWrapFlags
2291 5990 : StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2292 : const SmallVectorImpl<const SCEV *> &Ops,
2293 : SCEV::NoWrapFlags Flags) {
2294 : using namespace std::placeholders;
2295 327 :
2296 : using OBO = OverflowingBinaryOperator;
2297 :
2298 : bool CanAnalyze =
2299 327 : Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2300 : (void)CanAnalyze;
2301 : assert(CanAnalyze && "don't call from other places!");
2302 :
2303 : int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2304 5663 : SCEV::NoWrapFlags SignOrUnsignWrap =
2305 : ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2306 :
2307 : // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2308 : auto IsKnownNonNegative = [&](const SCEV *S) {
2309 5663 : return SE->isKnownNonNegative(S);
2310 : };
2311 :
2312 : if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2313 : Flags =
2314 : ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2315 :
2316 : SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2317 :
2318 : if (SignOrUnsignWrap != SignOrUnsignMask &&
2319 : (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2320 : isa<SCEVConstant>(Ops[0])) {
2321 1 :
2322 : auto Opcode = [&] {
2323 : switch (Type) {
2324 : case scAddExpr:
2325 1 : return Instruction::Add;
2326 : case scMulExpr:
2327 : return Instruction::Mul;
2328 : default:
2329 : llvm_unreachable("Unexpected SCEV op.");
2330 : }
2331 : }();
2332 :
2333 : const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2334 :
2335 : // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2336 : if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2337 : auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2338 17972 : Opcode, C, OBO::NoSignedWrap);
2339 5893 : if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2340 : Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2341 : }
2342 :
2343 : // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2344 : if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2345 : auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2346 : Opcode, C, OBO::NoUnsignedWrap);
2347 6195 : if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2348 12264 : Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2349 12045 : }
2350 5976 : }
2351 :
2352 : return Flags;
2353 146 : }
2354 :
2355 146 : bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2356 : return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2357 : }
2358 :
2359 : /// Get a canonical add expression, or something simpler if possible.
2360 : const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2361 : SCEV::NoWrapFlags Flags,
2362 : unsigned Depth) {
2363 : assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2364 4591 : "only nuw or nsw allowed");
2365 4591 : assert(!Ops.empty() && "Cannot get empty add!");
2366 1280 : if (Ops.size() == 1) return Ops[0];
2367 : #ifndef NDEBUG
2368 3840 : Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2369 1280 : for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2370 1280 : assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2371 : "SCEVAddExpr operand types don't match!");
2372 : #endif
2373 :
2374 : // Sort by complexity, this groups all similar expression types together.
2375 : GroupByComplexity(Ops, &LI, DT);
2376 10653 :
2377 : Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2378 0 :
2379 : // If there are any constants, fold them together.
2380 0 : unsigned Idx = 0;
2381 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2382 : ++Idx;
2383 : assert(Idx < Ops.size());
2384 : while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2385 : // We found two constants, fold them together!
2386 35034 : Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2387 8875 : if (Ops.size() == 2) return Ops[0];
2388 : Ops.erase(Ops.begin()+1); // Erase the folded element
2389 : LHSC = cast<SCEVConstant>(Ops[0]);
2390 : }
2391 26159 :
2392 25831 : // If we are left with a constant zero being added, strip it off.
2393 25831 : if (LHSC->getValue()->isZero()) {
2394 25831 : Ops.erase(Ops.begin());
2395 25831 : --Idx;
2396 25831 : }
2397 :
2398 : if (Ops.size() == 1) return Ops[0];
2399 : }
2400 :
2401 11199 : // Limit recursion calls depth.
2402 : if (Depth > MaxArithDepth)
2403 : return getOrCreateAddExpr(Ops, Flags);
2404 :
2405 : // Okay, check to see if the same value occurs in the operand list more than
2406 : // once. If so, merge them together into an multiply expression. Since we
2407 11199 : // sorted the list, these values are required to be adjacent.
2408 : Type *Ty = Ops[0]->getType();
2409 : bool FoundMatch = false;
2410 : for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2411 8171 : if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2412 5630 : // Scan ahead to count how many equal operands there are.
2413 : unsigned Count = 2;
2414 : while (i+Count != e && Ops[i+Count] == Ops[i])
2415 : ++Count;
2416 112 : // Merge the values into a multiply.
2417 112 : const SCEV *Scale = getConstant(Ty, Count);
2418 0 : const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2419 112 : if (Ops.size() == Count)
2420 : return Mul;
2421 : Ops[i] = Mul;
2422 : Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2423 5457 : --i; e -= Count - 1;
2424 5457 : FoundMatch = true;
2425 : }
2426 : if (FoundMatch)
2427 : return getAddExpr(Ops, Flags, Depth + 1);
2428 2157 :
2429 2157 : // Check for truncates. If all the operands are truncated from the same
2430 : // type, see if factoring out the truncate would permit the result to be
2431 : // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2432 : // if the contents of the resulting outer trunc fold to something simple.
2433 : auto FindTruncSrcType = [&]() -> Type * {
2434 : // We're ultimately looking to fold an addrec of truncs and muls of only
2435 2181 : // constants and truncs, so if we find any other types of SCEV
2436 1454 : // as operands of the addrec then we bail and return nullptr here.
2437 727 : // Otherwise, we return the type of the operand of a trunc that we find.
2438 : if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2439 : return T->getOperand()->getType();
2440 : if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2441 1259 : const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2442 0 : if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2443 : return T->getOperand()->getType();
2444 : }
2445 : return nullptr;
2446 : };
2447 : if (auto *SrcType = FindTruncSrcType()) {
2448 : SmallVector<const SCEV *, 8> LargeOps;
2449 : bool Ok = true;
2450 : // Check all the operands to see if they can be represented in the
2451 : // source type of the truncate.
2452 : for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2453 : if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2454 : if (T->getOperand()->getType() != SrcType) {
2455 : Ok = false;
2456 : break;
2457 : }
2458 : LargeOps.push_back(T->getOperand());
2459 : } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2460 : LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2461 : } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2462 : SmallVector<const SCEV *, 8> LargeMulOps;
2463 : for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2464 : if (const SCEVTruncateExpr *T =
2465 : dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2466 : if (T->getOperand()->getType() != SrcType) {
2467 : Ok = false;
2468 : break;
2469 : }
2470 : LargeMulOps.push_back(T->getOperand());
2471 : } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2472 567368 : LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2473 : } else {
2474 : Ok = false;
2475 : break;
2476 : }
2477 : }
2478 : if (Ok)
2479 : LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2480 : } else {
2481 : Ok = false;
2482 996198 : break;
2483 428830 : }
2484 : }
2485 857134 : if (Ok) {
2486 : // Evaluate the expression in the larger type.
2487 428830 : const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2488 428830 : // If it folds to something simple, use it. Otherwise, don't.
2489 : if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2490 : return getTruncateExpr(Fold, Ty);
2491 : }
2492 2195228 : }
2493 1627860 :
2494 1794828 : // Skip past any other cast SCEVs.
2495 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2496 859883 : ++Idx;
2497 859883 :
2498 : // If there are add operands they would be next.
2499 : if (Idx < Ops.size()) {
2500 6093 : bool DeletedAdd = false;
2501 6093 : while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2502 : if (Ops.size() > AddOpsInlineThreshold ||
2503 : Add->getNumOperands() > AddOpsInlineThreshold)
2504 : break;
2505 : // If we have an add, expand the add operands onto the end of the operands
2506 : // list.
2507 1707580 : Ops.erase(Ops.begin()+Idx);
2508 853790 : Ops.append(Add->op_begin(), Add->op_end());
2509 853790 : DeletedAdd = true;
2510 853790 : }
2511 850074 :
2512 : // If we deleted at least one add, we added operands to the end of the list,
2513 3716 : // and they are not necessarily sorted. Recurse to resort and resimplify
2514 : // any operands we just acquired.
2515 : if (DeletedAdd)
2516 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2517 : }
2518 :
2519 : // Skip over the add expression until we get to a multiply.
2520 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2521 : ++Idx;
2522 767977 :
2523 767977 : // Check to see if there are any folding opportunities present with
2524 490010 : // operands multiplied by constant values.
2525 : if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2526 277967 : uint64_t BitWidth = getTypeSizeInBits(Ty);
2527 : DenseMap<const SCEV *, APInt> M;
2528 : SmallVector<const SCEV *, 8> NewOps;
2529 : APInt AccumulatedConstant(BitWidth, 0);
2530 : if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2531 : Ops.data(), Ops.size(),
2532 : APInt(BitWidth, 1), *this)) {
2533 : struct APIntCompare {
2534 567368 : bool operator()(const APInt &LHS, const APInt &RHS) const {
2535 : return LHS.ult(RHS);
2536 : }
2537 : };
2538 :
2539 : // Some interesting folding opportunity is present, so its worthwhile to
2540 : // re-generate the operands list. Group the operands by constant scale,
2541 5093509 : // to avoid multiplying by the same constant scale multiple times.
2542 : std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2543 : for (const SCEV *NewOp : NewOps)
2544 : MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2545 : // Re-generate the operands list.
2546 : Ops.clear();
2547 : if (AccumulatedConstant != 0)
2548 : Ops.push_back(getConstant(AccumulatedConstant));
2549 : for (auto &MulOp : MulOpLists)
2550 : if (MulOp.first != 0)
2551 : Ops.push_back(getMulExpr(
2552 : getConstant(MulOp.first),
2553 : getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2554 : SCEV::FlagAnyWrap, Depth + 1));
2555 : if (Ops.empty())
2556 : return getZero(Ty);
2557 : if (Ops.size() == 1)
2558 : return Ops[0];
2559 0 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2560 : }
2561 : }
2562 5874390 :
2563 : // If we are adding something to a multiply expression, make sure the
2564 : // something is not already an operand of the multiply. If so, merge it into
2565 : // the multiply.
2566 : for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2567 : const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2568 4684800 : for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2569 5093509 : const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2570 3479599 : if (isa<SCEVConstant>(MulOpSCEV))
2571 : continue;
2572 : for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2573 2975552 : if (MulOpSCEV == Ops[AddOp]) {
2574 : // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2575 : const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2576 1114788 : if (Mul->getNumOperands() != 2) {
2577 : // If the multiply has more than two operands, we must get the
2578 0 : // Y*Z term.
2579 0 : SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2580 : Mul->op_begin()+MulOp);
2581 : MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2582 : InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2583 : }
2584 : SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2585 : const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2586 2975552 : const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2587 : SCEV::FlagAnyWrap, Depth + 1);
2588 7728312 : if (Ops.size() == 2) return OuterMul;
2589 7728312 : if (AddOp < Idx) {
2590 : Ops.erase(Ops.begin()+AddOp);
2591 : Ops.erase(Ops.begin()+Idx-1);
2592 : } else {
2593 : Ops.erase(Ops.begin()+Idx);
2594 2975552 : Ops.erase(Ops.begin()+AddOp-1);
2595 : }
2596 8876352 : Ops.push_back(OuterMul);
2597 8876352 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2598 : }
2599 :
2600 : // Check this multiply against other multiplies being added together.
2601 : for (unsigned OtherMulIdx = Idx+1;
2602 5093509 : OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2603 : ++OtherMulIdx) {
2604 : const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2605 831735 : // If MulOp occurs in OtherMul, we can fold the two multiplies
2606 831735 : // together.
2607 : for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2608 : OMulOp != e; ++OMulOp)
2609 : if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2610 2919946 : // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2611 : const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2612 : if (Mul->getNumOperands() != 2) {
2613 : SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2614 : Mul->op_begin()+MulOp);
2615 : MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2616 2919946 : InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2617 : }
2618 : const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2619 : if (OtherMul->getNumOperands() != 2) {
2620 : SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2621 : OtherMul->op_begin()+OMulOp);
2622 : MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2623 : InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2624 : }
2625 2785206 : SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2626 : const SCEV *InnerMulSum =
2627 2785206 : getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2628 : const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2629 : SCEV::FlagAnyWrap, Depth + 1);
2630 2785206 : if (Ops.size() == 2) return OuterMul;
2631 2785206 : Ops.erase(Ops.begin()+Idx);
2632 2296136 : Ops.erase(Ops.begin()+OtherMulIdx-1);
2633 : Ops.push_back(OuterMul);
2634 4829216 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2635 : }
2636 1095637 : }
2637 1086948 : }
2638 118472 : }
2639 118472 :
2640 118472 : // If there are any add recurrences in the operands list, see if any other
2641 : // added values are loop invariant. If so, we can fold them into the
2642 : // recurrence.
2643 2655320 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2644 282936 : ++Idx;
2645 282936 :
2646 : // Scan over all recurrences, trying to fold loop invariants into them.
2647 : for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2648 1327660 : // Scan all of the other operands to this add and add them to the vector if
2649 : // they are loop invariant w.r.t. the recurrence.
2650 : SmallVector<const SCEV *, 8> LIOps;
2651 : const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2652 1543934 : const Loop *AddRecLoop = AddRec->getLoop();
2653 3169 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2654 : if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2655 : LIOps.push_back(Ops[i]);
2656 : Ops.erase(Ops.begin()+i);
2657 : --i; --e;
2658 1540765 : }
2659 :
2660 4019066 : // If we found some loop invariants, fold them into the recurrence.
2661 7436316 : if (!LIOps.empty()) {
2662 : // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2663 : LIOps.push_back(AddRec->getStart());
2664 1427 :
2665 126 : SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2666 : AddRec->op_end());
2667 1301 : // This follows from the fact that the no-wrap flags on the outer add
2668 2602 : // expression are applicable on the 0th iteration, when the add recurrence
2669 1301 : // will be equal to its start value.
2670 471 : AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2671 830 :
2672 830 : // Build the new addrec. Propagate the NUW and NSW flags if both the
2673 830 : // outer add and the inner addrec are guaranteed to have no overflow.
2674 : // Always propagate NW.
2675 : Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2676 1540294 : const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2677 761 :
2678 : // If all of the other operands were loop invariant, we are done.
2679 : if (Ops.size() == 1) return NewRec;
2680 :
2681 : // Otherwise, add the folded AddRec by the non-invariant parts.
2682 : for (unsigned i = 0;; ++i)
2683 : if (Ops[i] == AddRec) {
2684 : Ops[i] = NewRec;
2685 : break;
2686 : }
2687 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2688 : }
2689 :
2690 : // Okay, if there weren't any loop invariants to be folded, check to see if
2691 : // there are multiple AddRec's with the same loop induction variable being
2692 : // added together. If so, we can fold them.
2693 : for (unsigned OtherIdx = Idx+1;
2694 : OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2695 : ++OtherIdx) {
2696 : // We expect the AddRecExpr's to be sorted in reverse dominance order,
2697 1539533 : // so that the 1st found AddRecExpr is dominated by all others.
2698 : assert(DT.dominates(
2699 : cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2700 : AddRec->getLoop()->getHeader()) &&
2701 : "AddRecExprs are not sorted in reverse dominance order?");
2702 15680 : if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2703 24870 : // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2704 2864 : SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2705 : AddRec->op_end());
2706 : for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2707 : ++OtherIdx) {
2708 2843 : const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2709 : if (OtherAddRec->getLoop() == AddRecLoop) {
2710 3019 : for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2711 : i != e; ++i) {
2712 : if (i >= AddRecOps.size()) {
2713 12134 : AddRecOps.append(OtherAddRec->op_begin()+i,
2714 : OtherAddRec->op_end());
2715 8497 : break;
2716 3608 : }
2717 : SmallVector<const SCEV *, 2> TwoOps = {
2718 : AddRecOps[i], OtherAddRec->getOperand(i)};
2719 : AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2720 3602 : }
2721 : Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2722 3978 : }
2723 : }
2724 : // Step size has changed, so we cannot guarantee no self-wraparound.
2725 : Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2726 : return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2727 : }
2728 4554 : }
2729 3514 :
2730 : // Otherwise couldn't fold anything into this recurrence. Move onto the
2731 : // next one.
2732 : }
2733 :
2734 : // Okay, it looks like we really DO need an add expr. Check to see if we
2735 5264 : // already have one, otherwise create a new one.
2736 : return getOrCreateAddExpr(Ops, Flags);
2737 2383 : }
2738 :
2739 2383 : const SCEV *
2740 7 : ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2741 : SCEV::NoWrapFlags Flags) {
2742 : FoldingSetNodeID ID;
2743 : ID.AddInteger(scAddExpr);
2744 : for (const SCEV *Op : Ops)
2745 1615679 : ID.AddPointer(Op);
2746 76153 : void *IP = nullptr;
2747 : SCEVAddExpr *S =
2748 : static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2749 1539526 : if (!S) {
2750 : const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2751 3784474 : std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2752 825086 : S = new (SCEVAllocator)
2753 412542 : SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2754 : UniqueSCEVs.InsertNode(S, IP);
2755 : addToLoopUseLists(S);
2756 : }
2757 412542 : S->setNoWrapFlags(Flags);
2758 825084 : return S;
2759 : }
2760 412542 :
2761 : const SCEV *
2762 : ScalarEvolution::getOrCreateAddRecExpr(SmallVectorImpl<const SCEV *> &Ops,
2763 : const Loop *L, SCEV::NoWrapFlags Flags) {
2764 : FoldingSetNodeID ID;
2765 1479695 : ID.AddInteger(scAddRecExpr);
2766 375137 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2767 : ID.AddPointer(Ops[i]);
2768 : ID.AddPointer(L);
2769 : void *IP = nullptr;
2770 1164390 : SCEVAddRecExpr *S =
2771 1 : static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2772 : if (!S) {
2773 : const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2774 : std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2775 1164389 : S = new (SCEVAllocator)
2776 561275 : SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2777 : UniqueSCEVs.InsertNode(S, IP);
2778 : addToLoopUseLists(S);
2779 561275 : }
2780 561275 : S->setNoWrapFlags(Flags);
2781 561275 : return S;
2782 561275 : }
2783 :
2784 0 : const SCEV *
2785 0 : ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2786 : SCEV::NoWrapFlags Flags) {
2787 : FoldingSetNodeID ID;
2788 : ID.AddInteger(scMulExpr);
2789 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2790 : ID.AddPointer(Ops[i]);
2791 : void *IP = nullptr;
2792 : SCEVMulExpr *S =
2793 572569 : static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2794 292987 : if (!S) {
2795 : const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2796 : std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2797 279582 : S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2798 259385 : O, Ops.size());
2799 569361 : UniqueSCEVs.InsertNode(S, IP);
2800 579558 : addToLoopUseLists(S);
2801 12135 : }
2802 : S->setNoWrapFlags(Flags);
2803 : return S;
2804 : }
2805 279582 :
2806 12971 : static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2807 266611 : uint64_t k = i*j;
2808 262796 : if (j > 1 && k / j != i) Overflow = true;
2809 3815 : return k;
2810 : }
2811 :
2812 : /// Compute the result of "n choose k", the binomial coefficient. If an
2813 : /// intermediate computation overflows, Overflow will be set and the return will
2814 : /// be garbage. Overflow is not cleared on absence of overflow.
2815 : static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2816 1471944 : // We use the multiplicative formula:
2817 : // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2818 1800788 : // At each iteration, we take the n-th term of the numeral and divide by the
2819 1213651 : // (k-n)th term of the denominator. This division will always produce an
2820 1213651 : // integral result, and helps reduce the chance of overflow in the
2821 : // intermediate computations. However, we can still overflow even when the
2822 25024862 : // final result would fit.
2823 48746246 :
2824 : if (n == 0 || n == k) return 1;
2825 219 : if (k > n) return 0;
2826 219 :
2827 : if (k > n/2)
2828 : k = n-k;
2829 :
2830 : uint64_t r = 1;
2831 200 : for (uint64_t i = 1; i <= k; ++i) {
2832 100 : r = umul_ov(r, n-(i-1), Overflow);
2833 : r /= i;
2834 219 : }
2835 219 : return r;
2836 219 : }
2837 219 :
2838 219 : /// Determine if any of the operands in this SCEV are a constant or if
2839 138 : /// any of the add or multiply expressions in this SCEV contain a constant.
2840 4 : static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2841 4 : struct FindConstantInAddMulChain {
2842 : bool FoundConstant = false;
2843 134 :
2844 134 : bool follow(const SCEV *S) {
2845 : FoundConstant |= isa<SCEVConstant>(S);
2846 138 : return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2847 138 : }
2848 :
2849 : bool isDone() const {
2850 : return FoundConstant;
2851 6267781 : }
2852 6267781 : };
2853 :
2854 : FindConstantInAddMulChain F;
2855 : SCEVTraversal<FindConstantInAddMulChain> ST(F);
2856 : ST.visitAll(StartExpr);
2857 16934389 : return F.FoundConstant;
2858 16934389 : }
2859 22636694 :
2860 : /// Get a canonical multiply expression, or something simpler if possible.
2861 5710 : const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2862 5710 : SCEV::NoWrapFlags Flags,
2863 : unsigned Depth) {
2864 : assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2865 6476 : "only nuw or nsw allowed");
2866 3238 : assert(!Ops.empty() && "Cannot get empty mul!");
2867 : if (Ops.size() == 1) return Ops[0];
2868 5710 : #ifndef NDEBUG
2869 5710 : Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2870 : for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2871 5114 : assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2872 10228 : "SCEVMulExpr operand types don't match!");
2873 5114 : #endif
2874 :
2875 5710 : // Sort by complexity, this groups all similar expression types together.
2876 : GroupByComplexity(Ops, &LI, DT);
2877 5710 :
2878 5710 : Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2879 5710 :
2880 5710 : // Limit recursion calls depth.
2881 1981 : if (Depth > MaxArithDepth)
2882 1981 : return getOrCreateMulExpr(Ops, Flags);
2883 1981 :
2884 1981 : // If there are any constants, fold them together.
2885 : unsigned Idx = 0;
2886 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2887 :
2888 : if (Ops.size() == 2)
2889 : // C1*(C2+V) -> C1*C2 + C1*V
2890 : if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2891 : // If any of Add's ops are Adds or Muls with a constant, apply this
2892 : // transformation as well.
2893 891361 : //
2894 12483 : // TODO: There are some cases where this transformation is not
2895 : // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2896 : // this transformation should be narrowed down.
2897 884685 : if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2898 : return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2899 : SCEV::FlagAnyWrap, Depth + 1),
2900 : getMulExpr(LHSC, Add->getOperand(1),
2901 353998 : SCEV::FlagAnyWrap, Depth + 1),
2902 353998 : SCEV::FlagAnyWrap, Depth + 1);
2903 1073791 :
2904 1439586 : ++Idx;
2905 346732 : while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2906 346732 : // We found two constants, fold them together!
2907 346732 : ConstantInt *Fold =
2908 : ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2909 : Ops[0] = getConstant(Fold);
2910 : Ops.erase(Ops.begin()+1); // Erase the folded element
2911 353998 : if (Ops.size() == 1) return Ops[0];
2912 : LHSC = cast<SCEVConstant>(Ops[0]);
2913 675846 : }
2914 :
2915 : // If we are left with a constant one being multiplied, strip it off.
2916 337923 : if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2917 : Ops.erase(Ops.begin());
2918 : --Idx;
2919 : } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2920 675846 : // If we have a multiply of zero, it will always be zero.
2921 : return Ops[0];
2922 : } else if (Ops[0]->isAllOnesValue()) {
2923 : // If we have a mul by -1 of an add, try distributing the -1 among the
2924 : // add operands.
2925 337923 : if (Ops.size() == 2) {
2926 337923 : if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2927 : SmallVector<const SCEV *, 4> NewOps;
2928 : bool AnyFolded = false;
2929 337923 : for (const SCEV *AddOp : Add->operands()) {
2930 : const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2931 : Depth + 1);
2932 911 : if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2933 3185 : NewOps.push_back(Mul);
2934 1137 : }
2935 : if (AnyFolded)
2936 : return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2937 1137 : } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2938 : // Negation preserves a recurrence's no self-wrap property.
2939 : SmallVector<const SCEV *, 4> Operands;
2940 : for (const SCEV *AddRecOp : AddRec->operands())
2941 : Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2942 : Depth + 1));
2943 16075 :
2944 16075 : return getAddRecExpr(Operands, AddRec->getLoop(),
2945 : AddRec->getNoWrapFlags(SCEV::FlagNW));
2946 : }
2947 : }
2948 : }
2949 :
2950 : if (Ops.size() == 1)
2951 : return Ops[0];
2952 10268 : }
2953 :
2954 : // Skip over the add expression until we get to a multiply.
2955 10268 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2956 20541 : ++Idx;
2957 :
2958 : // If there are mul operands inline them all into this expression.
2959 10273 : if (Idx < Ops.size()) {
2960 31706 : bool DeletedMul = false;
2961 31706 : while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2962 21827 : if (Ops.size() > MulOpsInlineThreshold)
2963 788 : break;
2964 : // If we have an mul, expand the mul operands onto the end of the
2965 394 : // operands list.
2966 : Ops.erase(Ops.begin()+Idx);
2967 : Ops.append(Mul->op_begin(), Mul->op_end());
2968 42866 : DeletedMul = true;
2969 42866 : }
2970 :
2971 10273 : // If we deleted at least one mul, we added operands to the end of the
2972 : // list, and they are not necessarily sorted. Recurse to resort and
2973 : // resimplify any operands we just acquired.
2974 : if (DeletedMul)
2975 20536 : return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2976 10268 : }
2977 :
2978 : // If there are any add recurrences in the operands list, see if any other
2979 : // added values are loop invariant. If so, we can fold them into the
2980 : // recurrence.
2981 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2982 : ++Idx;
2983 :
2984 : // Scan over all recurrences, trying to fold loop invariants into them.
2985 : for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2986 530687 : // Scan all of the other operands to this mul and add them to the vector
2987 : // if they are loop invariant w.r.t. the recurrence.
2988 : SmallVector<const SCEV *, 8> LIOps;
2989 : const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2990 533856 : const Loop *AddRecLoop = AddRec->getLoop();
2991 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2992 : if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2993 533856 : LIOps.push_back(Ops[i]);
2994 2249139 : Ops.erase(Ops.begin()+i);
2995 1715283 : --i; --e;
2996 533856 : }
2997 :
2998 : // If we found some loop invariants, fold them into the recurrence.
2999 533856 : if (!LIOps.empty()) {
3000 286037 : // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3001 : SmallVector<const SCEV *, 4> NewOps;
3002 : NewOps.reserve(AddRec->getNumOperands());
3003 286037 : const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3004 286037 : for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3005 286037 : NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3006 : SCEV::FlagAnyWrap, Depth + 1));
3007 :
3008 533856 : // Build the new addrec. Propagate the NUW and NSW flags if both the
3009 : // outer mul and the inner addrec are guaranteed to have no overflow.
3010 : //
3011 : // No self-wrap cannot be guaranteed after changing the step size, but
3012 773795 : // will be inferred if either NUW or NSW is true.
3013 : Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3014 : const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3015 773795 :
3016 2335318 : // If all of the other operands were loop invariant, we are done.
3017 3123046 : if (Ops.size() == 1) return NewRec;
3018 773795 :
3019 773795 : // Otherwise, multiply the folded AddRec by the non-invariant parts.
3020 : for (unsigned i = 0;; ++i)
3021 : if (Ops[i] == AddRec) {
3022 773795 : Ops[i] = NewRec;
3023 190206 : break;
3024 : }
3025 : return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3026 190206 : }
3027 190206 :
3028 190206 : // Okay, if there weren't any loop invariants to be folded, check to see
3029 : // if there are multiple AddRec's with the same loop induction variable
3030 : // being multiplied together. If so, we can fold them.
3031 773795 :
3032 : // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3033 : // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3034 : // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3035 555244 : // ]]],+,...up to x=2n}.
3036 : // Note that the arguments to choose() are always integers with values
3037 : // known at compile time, never SCEV objects.
3038 555244 : //
3039 1745500 : // The implementation avoids pointless extra computations when the two
3040 2380512 : // addrec's are of different length (mathematically, it's equivalent to
3041 555244 : // an infinite stream of zeros on the right).
3042 : bool OpsModified = false;
3043 : for (unsigned OtherIdx = Idx+1;
3044 555244 : OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3045 128500 : ++OtherIdx) {
3046 : const SCEVAddRecExpr *OtherAddRec =
3047 128500 : dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3048 128500 : if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3049 128500 : continue;
3050 128500 :
3051 : // Limit max number of arguments to avoid creation of unreasonably big
3052 : // SCEVAddRecs with very complex operands.
3053 555244 : if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3054 : MaxAddRecSize)
3055 : continue;
3056 :
3057 3467 : bool Overflow = false;
3058 3467 : Type *Ty = AddRec->getType();
3059 : bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3060 : SmallVector<const SCEV*, 7> AddRecOps;
3061 : for (int x = 0, xe = AddRec->getNumOperands() +
3062 : OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3063 : const SCEV *Term = getZero(Ty);
3064 : for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3065 11562 : uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3066 : for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3067 : ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3068 : z < ze && !Overflow; ++z) {
3069 : uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3070 : uint64_t Coeff;
3071 : if (LargerThan64Bits)
3072 : Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3073 : else
3074 11562 : Coeff = Coeff1*Coeff2;
3075 6702 : const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3076 : const SCEV *Term1 = AddRec->getOperand(y-z);
3077 6702 : const SCEV *Term2 = OtherAddRec->getOperand(z);
3078 615 : Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
3079 : SCEV::FlagAnyWrap, Depth + 1),
3080 : SCEV::FlagAnyWrap, Depth + 1);
3081 10164 : }
3082 3462 : }
3083 3462 : AddRecOps.push_back(Term);
3084 : }
3085 : if (!Overflow) {
3086 : const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3087 : SCEV::FlagAnyWrap);
3088 : if (Ops.size() == 2) return NewAddRec;
3089 : Ops[Idx] = NewAddRec;
3090 80261 : Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3091 : OpsModified = true;
3092 : AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3093 : if (!AddRec)
3094 0 : break;
3095 272676 : }
3096 272676 : }
3097 : if (OpsModified)
3098 : return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3099 0 :
3100 0 : // Otherwise couldn't fold anything into this recurrence. Move onto the
3101 : // next one.
3102 : }
3103 :
3104 80261 : // Okay, it looks like we really DO need an mul expr. Check to see if we
3105 80261 : // already have one, otherwise create a new one.
3106 80261 : return getOrCreateMulExpr(Ops, Flags);
3107 80261 : }
3108 :
3109 : /// Represents an unsigned remainder expression based on unsigned division.
3110 : const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3111 2396245 : const SCEV *RHS) {
3112 : assert(getEffectiveSCEVType(LHS->getType()) ==
3113 : getEffectiveSCEVType(RHS->getType()) &&
3114 : "SCEVURemExpr operand types don't match!");
3115 :
3116 : // Short-circuit easy cases
3117 2396245 : if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3118 : // If constant is one, the result is trivial
3119 : if (RHSC->getValue()->isOne())
3120 : return getZero(LHS->getType()); // X urem 1 --> 0
3121 :
3122 : // If constant is a power of two, fold into a zext(trunc(LHS)).
3123 : if (RHSC->getAPInt().isPowerOf2()) {
3124 : Type *FullTy = LHS->getType();
3125 : Type *TruncTy =
3126 1534508 : IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3127 : return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3128 1534508 : }
3129 : }
3130 :
3131 1534508 : // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3132 17274 : const SCEV *UDiv = getUDivExpr(LHS, RHS);
3133 : const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3134 : return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3135 : }
3136 1517234 :
3137 : /// Get a canonical unsigned division expression, or something simpler if
3138 1456652 : /// possible.
3139 : const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3140 1376371 : const SCEV *RHS) {
3141 : assert(getEffectiveSCEVType(LHS->getType()) ==
3142 : getEffectiveSCEVType(RHS->getType()) &&
3143 : "SCEVUDivExpr operand types don't match!");
3144 :
3145 : if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3146 : if (RHSC->getValue()->isOne())
3147 92851 : return LHS; // X udiv 1 --> x
3148 154436 : // If the denominator is zero, the result of the udiv is undefined. Don't
3149 : // try to analyze it, because the resolution chosen here may differ from
3150 : // the resolution chosen in other parts of the compiler.
3151 : if (!RHSC->getValue()->isZero()) {
3152 77218 : // Determine if the division can be folded into the operands of
3153 : // its operands.
3154 : // TODO: Generalize this to non-constants by using known-bits information.
3155 1437883 : Type *Ty = LHS->getType();
3156 : unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3157 : unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3158 1418558 : // For non-power-of-two values, effectively round the value up to the
3159 709279 : // nearest power of two.
3160 709279 : if (!RHSC->getAPInt().isPowerOf2())
3161 709279 : ++MaxShiftAmt;
3162 58449 : IntegerType *ExtTy =
3163 58449 : IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3164 : if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3165 : if (const SCEVConstant *Step =
3166 1457208 : dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3167 57185 : // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3168 : const APInt &StepInt = Step->getAPInt();
3169 671419 : const APInt &DivInt = RHSC->getAPInt();
3170 : if (!StepInt.urem(DivInt) &&
3171 : getZeroExtendExpr(AR, ExtTy) ==
3172 665438 : getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3173 : getZeroExtendExpr(Step, ExtTy),
3174 : AR->getLoop(), SCEV::FlagAnyWrap)) {
3175 533488 : SmallVector<const SCEV *, 4> Operands;
3176 528057 : for (const SCEV *Op : AR->operands())
3177 : Operands.push_back(getUDivExpr(Op, RHS));
3178 : return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3179 43779 : }
3180 65278 : /// Get a canonical UDivExpr for a recurrence.
3181 32639 : /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3182 32639 : // We can currently only fold X%N if X is constant.
3183 32639 : const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3184 : if (StartC && !DivInt.urem(StepInt) &&
3185 11140 : getZeroExtendExpr(AR, ExtTy) ==
3186 9138 : getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3187 : getZeroExtendExpr(Step, ExtTy),
3188 : AR->getLoop(), SCEV::FlagAnyWrap)) {
3189 : const APInt &StartInt = StartC->getAPInt();
3190 254117 : const APInt &StartRem = StartInt.urem(StepInt);
3191 341774 : if (StartRem != 0)
3192 : LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3193 : AR->getLoop(), SCEV::FlagNW);
3194 166460 : }
3195 : }
3196 : // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3197 : if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3198 : SmallVector<const SCEV *, 4> Operands;
3199 : for (const SCEV *Op : M->operands())
3200 630255 : Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3201 50378 : if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3202 : // Find an operand that's safely divisible.
3203 : for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3204 : const SCEV *Op = M->getOperand(i);
3205 812214 : const SCEV *Div = getUDivExpr(Op, RHSC);
3206 171755 : if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3207 : Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3208 : M->op_end());
3209 640459 : Operands[i] = Div;
3210 : return getMulExpr(Operands);
3211 634567 : }
3212 145152 : }
3213 : }
3214 :
3215 : // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3216 72208 : if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3217 144416 : if (auto *DivisorConstant =
3218 : dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3219 72208 : bool Overflow = false;
3220 : APInt NewRHS =
3221 : DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3222 : if (Overflow) {
3223 : return getConstant(RHSC->getType(), 0, false);
3224 562359 : }
3225 70374 : return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3226 : }
3227 : }
3228 :
3229 : // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3230 : if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3231 617900 : SmallVector<const SCEV *, 4> Operands;
3232 47815 : for (const SCEV *Op : A->operands())
3233 : Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3234 : if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3235 573213 : Operands.clear();
3236 : for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3237 : const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3238 : if (isa<SCEVUDivExpr>(Op) ||
3239 35243 : getMulExpr(Op, RHS) != A->getOperand(i))
3240 35243 : break;
3241 117758 : Operands.push_back(Op);
3242 165030 : }
3243 31800 : if (Operands.size() == A->getNumOperands())
3244 31800 : return getAddExpr(Operands);
3245 31800 : }
3246 : }
3247 :
3248 : // Fold if both operands are constant.
3249 35243 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3250 : Constant *LHSCV = LHSC->getValue();
3251 : Constant *RHSCV = RHSC->getValue();
3252 31446 : return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3253 31446 : RHSCV)));
3254 96491 : }
3255 130090 : }
3256 : }
3257 :
3258 : FoldingSetNodeID ID;
3259 : ID.AddInteger(scUDivExpr);
3260 : ID.AddPointer(LHS);
3261 : ID.AddPointer(RHS);
3262 : void *IP = nullptr;
3263 31446 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3264 31446 : SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3265 : LHS, RHS);
3266 : UniqueSCEVs.InsertNode(S, IP);
3267 31446 : addToLoopUseLists(S);
3268 : return S;
3269 : }
3270 73 :
3271 2507 : static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3272 1217 : APInt A = C1->getAPInt().abs();
3273 : APInt B = C2->getAPInt().abs();
3274 : uint32_t ABW = A.getBitWidth();
3275 1217 : uint32_t BBW = B.getBitWidth();
3276 :
3277 : if (ABW > BBW)
3278 : B = B.zext(ABW);
3279 : else if (ABW < BBW)
3280 : A = A.zext(BBW);
3281 :
3282 : return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3283 : }
3284 :
3285 : /// Get a canonical unsigned division expression, or something simpler if
3286 : /// possible. There is no representation for an exact udiv in SCEV IR, but we
3287 : /// can attempt to remove factors from the LHS and RHS. We can't do this when
3288 : /// it's not exact because the udiv may be clearing bits.
3289 : const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3290 : const SCEV *RHS) {
3291 : // TODO: we could try to find factors in all sorts of things, but for now we
3292 : // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3293 6336 : // end of this file for inspiration.
3294 6336 :
3295 : const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3296 : if (!Mul || !Mul->hasNoUnsignedWrap())
3297 : return getUDivExpr(LHS, RHS);
3298 3075 :
3299 2363 : if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3300 : // If the mulexpr multiplies by a constant, then that constant must be the
3301 : // first element of the mulexpr.
3302 : if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3303 3075 : if (LHSCst == RHSCst) {
3304 3075 : SmallVector<const SCEV *, 2> Operands;
3305 : Operands.append(Mul->op_begin() + 1, Mul->op_end());
3306 : return getMulExpr(Operands);
3307 712 : }
3308 :
3309 712 : // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3310 : // that there's a factor provided by one of the other terms. We need to
3311 2621 : // check.
3312 3333 : APInt Factor = gcd(LHSCst, RHSCst);
3313 2621 : if (!Factor.isIntN(1)) {
3314 9033 : LHSCst =
3315 6412 : cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3316 6412 : RHSCst =
3317 9198 : cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3318 11562 : SmallVector<const SCEV *, 2> Operands;
3319 5150 : Operands.push_back(LHSCst);
3320 : Operands.append(Mul->op_begin() + 1, Mul->op_end());
3321 5150 : LHS = getMulExpr(Operands);
3322 : RHS = RHSCst;
3323 : Mul = dyn_cast<SCEVMulExpr>(LHS);
3324 5145 : if (!Mul)
3325 5150 : return getUDivExactExpr(LHS, RHS);
3326 5150 : }
3327 5150 : }
3328 5150 : }
3329 :
3330 : for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3331 : if (Mul->getOperand(i) == RHS) {
3332 : SmallVector<const SCEV *, 2> Operands;
3333 2621 : Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3334 : Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3335 712 : return getMulExpr(Operands);
3336 712 : }
3337 : }
3338 712 :
3339 179 : return getUDivExpr(LHS, RHS);
3340 179 : }
3341 :
3342 : /// Get an add recurrence expression for the specified loop. Simplify the
3343 : /// expression as much as possible.
3344 : const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3345 : const Loop *L,
3346 : SCEV::NoWrapFlags Flags) {
3347 3261 : SmallVector<const SCEV *, 4> Operands;
3348 136 : Operands.push_back(Start);
3349 : if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3350 : if (StepChrec->getLoop() == L) {
3351 : Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3352 : return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3353 : }
3354 :
3355 : Operands.push_back(Step);
3356 537970 : return getAddRecExpr(Operands, L, Flags);
3357 : }
3358 :
3359 : /// Get an add recurrence expression for the specified loop. Simplify the
3360 5471 : /// expression as much as possible.
3361 : const SCEV *
3362 : ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3363 : const Loop *L, SCEV::NoWrapFlags Flags) {
3364 : if (Operands.size() == 1) return Operands[0];
3365 : #ifndef NDEBUG
3366 : Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3367 : for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3368 : assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3369 5002 : "SCEVAddRecExpr operand types don't match!");
3370 1852 : for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3371 : assert(isLoopInvariant(Operands[i], L) &&
3372 : "SCEVAddRecExpr operand is not loop-invariant!");
3373 1575 : #endif
3374 181 :
3375 : if (Operands.back()->isZero()) {
3376 181 : Operands.pop_back();
3377 181 : return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3378 : }
3379 :
3380 : // It's tempting to want to call getMaxBackedgeTakenCount count here and
3381 : // use that information to infer NUW and NSW flags. However, computing a
3382 4364 : // BE count requires calling getAddRecExpr, so we may not yet have a
3383 4364 : // meaningful BE count at this point (and if we don't, we'd be stuck
3384 4364 : // with a SCEVCouldNotCompute as the cached BE count).
3385 :
3386 : Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3387 :
3388 : // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3389 42008 : if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3390 : const Loop *NestedLoop = NestedAR->getLoop();
3391 : if (L->contains(NestedLoop)
3392 : ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3393 : : (!NestedLoop->contains(L) &&
3394 : DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3395 : SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3396 76920 : NestedAR->op_end());
3397 : Operands[0] = NestedAR->getStart();
3398 : // AddRecs require their operands be loop-invariant with respect to their
3399 : // loops. Don't perform this transformation if it would break this
3400 : // requirement.
3401 26814 : bool AllInvariant = all_of(
3402 : Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3403 :
3404 : if (AllInvariant) {
3405 26813 : // Create a recurrence for the outer loop with the same step size.
3406 26813 : //
3407 26813 : // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3408 : // inner recurrence has the same property.
3409 : SCEV::NoWrapFlags OuterFlags =
3410 26813 : maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3411 :
3412 : NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3413 26813 : AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3414 : return isLoopInvariant(Op, NestedLoop);
3415 : });
3416 721 :
3417 : if (AllInvariant) {
3418 : // Ok, both add recurrences are valid after the transformation.
3419 : //
3420 2158 : // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3421 103 : // the outer recurrence has the same property.
3422 103 : SCEV::NoWrapFlags InnerFlags =
3423 : maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3424 : return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3425 : }
3426 60 : }
3427 40 : // Reset Operands to its original state.
3428 20 : Operands[0] = NestedAR;
3429 : }
3430 : }
3431 :
3432 : // Okay, it looks like we really DO need an addrec expr. Check to see if we
3433 665 : // already have one, otherwise create a new one.
3434 2439 : return getOrCreateAddRecExpr(Operands, L, Flags);
3435 526 : }
3436 526 :
3437 : const SCEV *
3438 : ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3439 : const SmallVectorImpl<const SCEV *> &IndexExprs) {
3440 323 : const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3441 323 : // getSCEV(Base)->getType() has the same address space as Base->getType()
3442 36 : // because SCEV::getType() preserves the address space.
3443 : Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3444 : // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3445 : // instruction to its SCEV, because the Instruction may be guarded by control
3446 : // flow and the no-overflow bits may not be valid for the expression in any
3447 : // context. This can be fixed similarly to how these flags are handled for
3448 : // adds.
3449 10616 : SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3450 7202 : : SCEV::FlagAnyWrap;
3451 3414 :
3452 : const SCEV *TotalOffset = getZero(IntPtrTy);
3453 4 : // The array size is unimportant. The first thing we do on CurTy is getting
3454 4 : // its element type.
3455 4 : Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3456 4 : for (const SCEV *IndexExpr : IndexExprs) {
3457 8 : // Compute the (potentially symbolic) offset in bytes for this index.
3458 : if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3459 4 : // For a struct, add the member offset.
3460 4 : ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3461 : unsigned FieldNo = Index->getZExtValue();
3462 : const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3463 :
3464 : // Add the field offset to the running total offset.
3465 : TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3466 :
3467 : // Update CurTy to the type of the field at Index.
3468 21 : CurTy = STy->getTypeAtIndex(Index);
3469 21 : } else {
3470 : // Update CurTy to its element type.
3471 21 : CurTy = cast<SequentialType>(CurTy)->getElementType();
3472 21 : // For an array, add the element offset, explicitly scaled.
3473 6 : const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3474 : // Getelementptr indices are signed.
3475 18 : IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3476 :
3477 : // Multiply the index by the element size to compute the element offset.
3478 : const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3479 :
3480 : // Add the element offset to the running total offset.
3481 : TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3482 9930 : }
3483 6916 : }
3484 3014 :
3485 : // Add the total offset from all the GEP indices to the base.
3486 273 : return getAddExpr(BaseExpr, TotalOffset, Wrap);
3487 546 : }
3488 545 :
3489 272 : const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3490 : const SCEV *RHS) {
3491 1 : SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3492 : return getSMaxExpr(Ops);
3493 544 : }
3494 0 :
3495 : const SCEV *
3496 : ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3497 : assert(!Ops.empty() && "Cannot get empty smax!");
3498 : if (Ops.size() == 1) return Ops[0];
3499 : #ifndef NDEBUG
3500 10266 : Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3501 10266 : for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3502 10266 : assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3503 10266 : "SCEVSMaxExpr operand types don't match!");
3504 : #endif
3505 :
3506 : // Sort by complexity, this groups all similar expression types together.
3507 : GroupByComplexity(Ops, &LI, DT);
3508 :
3509 20051 : // If there are any constants, fold them together.
3510 20051 : unsigned Idx = 0;
3511 20051 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3512 20051 : ++Idx;
3513 20051 : assert(Idx < Ops.size());
3514 11464 : while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3515 : // We found two constants, fold them together!
3516 11464 : ConstantInt *Fold = ConstantInt::get(
3517 11464 : getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
3518 11464 : Ops[0] = getConstant(Fold);
3519 : Ops.erase(Ops.begin()+1); // Erase the folded element
3520 : if (Ops.size() == 1) return Ops[0];
3521 0 : LHSC = cast<SCEVConstant>(Ops[0]);
3522 0 : }
3523 0 :
3524 0 : // If we are left with a constant minimum-int, strip it off.
3525 0 : if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3526 : Ops.erase(Ops.begin());
3527 0 : --Idx;
3528 0 : } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3529 0 : // If we have an smax with a constant maximum-int, it will always be
3530 0 : // maximum-int.
3531 : return Ops[0];
3532 0 : }
3533 :
3534 : if (Ops.size() == 1) return Ops[0];
3535 : }
3536 :
3537 : // Find the first SMax
3538 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3539 488 : ++Idx;
3540 :
3541 : // Check to see if one of the operands is an SMax. If so, expand its operands
3542 : // onto our operand list, and recurse to simplify.
3543 : if (Idx < Ops.size()) {
3544 : bool DeletedSMax = false;
3545 : while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
3546 32 : Ops.erase(Ops.begin()+Idx);
3547 488 : Ops.append(SMax->op_begin(), SMax->op_end());
3548 : DeletedSMax = true;
3549 : }
3550 :
3551 : if (DeletedSMax)
3552 0 : return getSMaxExpr(Ops);
3553 0 : }
3554 :
3555 0 : // Okay, check to see if the same value occurs in the operand list twice. If
3556 0 : // so, delete one. Since we sorted the list, these values are required to
3557 : // be adjacent.
3558 : for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3559 : // X smax Y smax Y --> X smax Y
3560 : // X smax Y --> X, if X is always greater than Y
3561 : if (Ops[i] == Ops[i+1] ||
3562 0 : isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3563 0 : Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3564 : --i; --e;
3565 0 : } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
3566 : Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3567 0 : --i; --e;
3568 : }
3569 0 :
3570 0 : if (Ops.size() == 1) return Ops[0];
3571 0 :
3572 : assert(!Ops.empty() && "Reduced smax down to nothing!");
3573 :
3574 : // Okay, it looks like we really DO need an smax expr. Check to see if we
3575 0 : // already have one, otherwise create a new one.
3576 : FoldingSetNodeID ID;
3577 : ID.AddInteger(scSMaxExpr);
3578 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3579 : ID.AddPointer(Ops[i]);
3580 0 : void *IP = nullptr;
3581 0 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3582 : const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3583 0 : std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3584 0 : SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3585 0 : O, Ops.size());
3586 : UniqueSCEVs.InsertNode(S, IP);
3587 : addToLoopUseLists(S);
3588 : return S;
3589 0 : }
3590 :
3591 : const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3592 : const SCEV *RHS) {
3593 : SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3594 178554 : return getUMaxExpr(Ops);
3595 : }
3596 :
3597 : const SCEV *
3598 178554 : ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3599 178554 : assert(!Ops.empty() && "Cannot get empty umax!");
3600 222 : if (Ops.size() == 1) return Ops[0];
3601 162 : #ifndef NDEBUG
3602 81 : Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3603 : for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3604 : assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3605 178473 : "SCEVUMaxExpr operand types don't match!");
3606 178473 : #endif
3607 :
3608 : // Sort by complexity, this groups all similar expression types together.
3609 : GroupByComplexity(Ops, &LI, DT);
3610 :
3611 : // If there are any constants, fold them together.
3612 815329 : unsigned Idx = 0;
3613 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3614 1630658 : ++Idx;
3615 : assert(Idx < Ops.size());
3616 : while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3617 : // We found two constants, fold them together!
3618 : ConstantInt *Fold = ConstantInt::get(
3619 : getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
3620 : Ops[0] = getConstant(Fold);
3621 : Ops.erase(Ops.begin()+1); // Erase the folded element
3622 : if (Ops.size() == 1) return Ops[0];
3623 : LHSC = cast<SCEVConstant>(Ops[0]);
3624 : }
3625 795592 :
3626 : // If we are left with a constant minimum-int, strip it off.
3627 21797 : if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3628 : Ops.erase(Ops.begin());
3629 : --Idx;
3630 : } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3631 : // If we have an umax with a constant maximum-int, it will always be
3632 : // maximum-int.
3633 : return Ops[0];
3634 : }
3635 :
3636 773795 : if (Ops.size() == 1) return Ops[0];
3637 : }
3638 :
3639 773795 : // Find the first UMax
3640 142129 : while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3641 142129 : ++Idx;
3642 142129 :
3643 404071 : // Check to see if one of the operands is a UMax. If so, expand its operands
3644 239626 : // onto our operand list, and recurse to simplify.
3645 : if (Idx < Ops.size()) {
3646 0 : bool DeletedUMax = false;
3647 0 : while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
3648 : Ops.erase(Ops.begin()+Idx);
3649 : Ops.append(UMax->op_begin(), UMax->op_end());
3650 : DeletedUMax = true;
3651 : }
3652 0 :
3653 : if (DeletedUMax)
3654 0 : return getUMaxExpr(Ops);
3655 : }
3656 :
3657 : // Okay, check to see if the same value occurs in the operand list twice. If
3658 : // so, delete one. Since we sorted the list, these values are required to
3659 : // be adjacent.
3660 0 : for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
3661 : // X umax Y umax Y --> X umax Y
3662 0 : // X umax Y --> X, if X is always greater than Y
3663 : if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
3664 0 : ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
3665 : Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3666 : --i; --e;
3667 0 : } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
3668 : Ops[i + 1])) {
3669 : Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3670 : --i; --e;
3671 : }
3672 :
3673 0 : if (Ops.size() == 1) return Ops[0];
3674 0 :
3675 : assert(!Ops.empty() && "Reduced umax down to nothing!");
3676 :
3677 : // Okay, it looks like we really DO need a umax expr. Check to see if we
3678 0 : // already have one, otherwise create a new one.
3679 : FoldingSetNodeID ID;
3680 : ID.AddInteger(scUMaxExpr);
3681 : for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3682 : ID.AddPointer(Ops[i]);
3683 : void *IP = nullptr;
3684 773795 : if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3685 : const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3686 : std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3687 : SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3688 207966 : O, Ops.size());
3689 : UniqueSCEVs.InsertNode(S, IP);
3690 207966 : addToLoopUseLists(S);
3691 : return S;
3692 : }
3693 207966 :
3694 : const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3695 : const SCEV *RHS) {
3696 : SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3697 : return getSMinExpr(Ops);
3698 : }
3699 207966 :
3700 : const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3701 : // ~smax(~x, ~y, ~z) == smin(x, y, z).
3702 : SmallVector<const SCEV *, 2> NotOps;
3703 : for (auto *S : Ops)
3704 : NotOps.push_back(getNotSCEV(S));
3705 207966 : return getNotSCEV(getSMaxExpr(NotOps));
3706 570829 : }
3707 :
3708 : const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3709 : const SCEV *RHS) {
3710 37646 : SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3711 37646 : return getUMinExpr(Ops);
3712 37646 : }
3713 :
3714 : const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3715 37646 : assert(!Ops.empty() && "At least one operand must be!");
3716 : // Trivial case.
3717 : if (Ops.size() == 1)
3718 37646 : return Ops[0];
3719 :
3720 : // ~umax(~x, ~y, ~z) == umin(x, y, z).
3721 325217 : SmallVector<const SCEV *, 2> NotOps;
3722 : for (auto *S : Ops)
3723 325217 : NotOps.push_back(getNotSCEV(S));
3724 : return getNotSCEV(getUMaxExpr(NotOps));
3725 325217 : }
3726 :
3727 : const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3728 325217 : // We can bypass creating a target-independent
3729 : // constant expression and then folding it back into a ConstantInt.
3730 : // This is just a compile-time optimization.
3731 325217 : return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3732 : }
3733 :
3734 : const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3735 : StructType *STy,
3736 207966 : unsigned FieldNo) {
3737 : // We can bypass creating a target-independent
3738 : // constant expression and then folding it back into a ConstantInt.
3739 4749 : // This is just a compile-time optimization.
3740 : return getConstant(
3741 4749 : IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3742 4749 : }
3743 :
3744 : const SCEV *ScalarEvolution::getUnknown(Value *V) {
3745 : // Don't attempt to do anything other than create a SCEVUnknown object
3746 22358 : // here. createSCEV only calls getUnknown after checking for all other
3747 : // interesting possibilities, and any other code that calls getUnknown
3748 22358 : // is doing so in order to hide a value from SCEV canonicalization.
3749 :
3750 : FoldingSetNodeID ID;
3751 : ID.AddInteger(scUnknown);
3752 : ID.AddPointer(V);
3753 : void *IP = nullptr;
3754 : if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3755 : assert(cast<SCEVUnknown>(S)->getValue() == V &&
3756 : "Stale SCEVUnknown in uniquing map!");
3757 22358 : return S;
3758 : }
3759 : SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3760 : FirstUnknown);
3761 22358 : FirstUnknown = cast<SCEVUnknown>(S);
3762 : UniqueSCEVs.InsertNode(S, IP);
3763 : return S;
3764 21769 : }
3765 :
3766 19226 : //===----------------------------------------------------------------------===//
3767 : // Basic SCEV Analysis and PHI Idiom Recognition Code
3768 19226 : //
3769 19226 :
3770 19226 : /// Test if values of the given type are analyzable within the SCEV
3771 2 : /// framework. This primarily includes integer types, and it can optionally
3772 2 : /// include pointer types if the ScalarEvolution class has access to
3773 : /// target-specific information.
3774 : bool ScalarEvolution::isSCEVable(Type *Ty) const {
3775 2543 : // Integers and pointers are always SCEVable.
3776 11 : return Ty->isIntOrPtrTy();
3777 : }
3778 2532 :
3779 : /// Return the size in bits of the specified type, for which isSCEVable must
3780 : /// return true.
3781 : uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3782 : assert(isSCEVable(Ty) && "Type is not SCEVable!");
3783 : if (Ty->isPointerTy())
3784 2539 : return getDataLayout().getIndexTypeSizeInBits(Ty);
3785 : return getDataLayout().getTypeSizeInBits(Ty);
3786 : }
3787 :
3788 5541 : /// Return a type with the same bitwidth as the given type and which represents
3789 2422 : /// how SCEV will treat the given type, for which isSCEVable must return
3790 : /// true. For pointer types, this is the pointer-sized integer type.
3791 : Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3792 : assert(isSCEVable(Ty) && "Type is not SCEVable!");
3793 3119 :
3794 : if (Ty->isIntegerTy())
3795 1318 : return Ty;
3796 92 :
3797 184 : // The only other support type is pointer.
3798 : assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3799 92 : return getDataLayout().getIntPtrType(Ty);
3800 : }
3801 1226 :
3802 92 : Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3803 : return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3804 : }
3805 :
3806 : const SCEV *ScalarEvolution::getCouldNotCompute() {
3807 : return CouldNotCompute.get();
3808 6486 : }
3809 :
3810 : bool ScalarEvolution::checkValidity(const SCEV *S) const {
3811 13831 : bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3812 3454 : auto *SU = dyn_cast<SCEVUnknown>(S);
3813 136 : return SU && SU->getValue() == nullptr;
3814 136 : });
3815 6646 :
3816 48 : return !ContainsNulls;
3817 48 : }
3818 :
3819 : bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3820 3027 : HasRecMapType::iterator I = HasRecMap.find(S);
3821 : if (I != HasRecMap.end())
3822 : return I->second;
3823 :
3824 : bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3825 : HasRecMap.insert({S, FoundAddRec});
3826 : return FoundAddRec;
3827 2843 : }
3828 8961 :
3829 12236 : /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3830 2843 : /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3831 2843 : /// offset I, then return {S', I}, else return {\p S, nullptr}.
3832 2382 : static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3833 : const auto *Add = dyn_cast<SCEVAddExpr>(S);
3834 2382 : if (!Add)
3835 2382 : return {S, nullptr};
3836 2382 :
3837 2382 : if (Add->getNumOperands() != 2)
3838 2382 : return {S, nullptr};
3839 :
3840 : auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3841 932 : if (!ConstOp)
3842 : return {S, nullptr};
3843 932 :
3844 932 : return {Add->getOperand(1), ConstOp->getValue()};
3845 : }
3846 :
3847 : /// Return the ValueOffsetPair set for \p S. \p S can be represented
3848 2062 : /// by the value and offset from any ValueOffsetPair in the set.
3849 : SetVector<ScalarEvolution::ValueOffsetPair> *
3850 2062 : ScalarEvolution::getSCEVValues(const SCEV *S) {
3851 : ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3852 : if (SI == ExprValueMap.end())
3853 : return nullptr;
3854 : #ifndef NDEBUG
3855 : if (VerifySCEVMap) {
3856 : // Check there is no dangling Value in the set returned.
3857 : for (const auto &VE : SI->second)
3858 : assert(ValueExprMap.count(VE.first));
3859 2062 : }
3860 : #endif
3861 : return &SI->second;
3862 : }
3863 2062 :
3864 : /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3865 : /// cannot be used separately. eraseValueFromMap should be used to remove
3866 1389 : /// V from ValueExprMap and ExprValueMap at the same time.
3867 : void ScalarEvolution::eraseValueFromMap(Value *V) {
3868 562 : ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3869 : if (I != ValueExprMap.end()) {
3870 562 : const SCEV *S = I->second;
3871 562 : // Remove {V, 0} from the set of ExprValueMap[S]
3872 562 : if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3873 25 : SV->remove({V, nullptr});
3874 25 :
3875 : // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3876 : const SCEV *Stripped;
3877 827 : ConstantInt *Offset;
3878 146 : std::tie(Stripped, Offset) = splitAddExpr(S);
3879 : if (Offset != nullptr) {
3880 681 : if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3881 : SV->remove({V, Offset});
3882 : }
3883 : ValueExprMap.erase(V);
3884 : }
3885 : }
3886 802 :
3887 : /// Check whether value has nuw/nsw/exact set but SCEV does not.
3888 : /// TODO: In reality it is better to check the poison recursevely
3889 : /// but this is better than nothing.
3890 2804 : static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3891 1450 : if (auto *I = dyn_cast<Instruction>(V)) {
3892 : if (isa<OverflowingBinaryOperator>(I)) {
3893 : if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3894 : if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3895 1354 : return true;
3896 : if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3897 582 : return true;
3898 30 : }
3899 60 : } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3900 : return true;
3901 30 : }
3902 : return false;
3903 552 : }
3904 30 :
3905 : /// Return an existing SCEV if it exists, otherwise analyze the expression and
3906 : /// create a new one.
3907 : const SCEV *ScalarEvolution::getSCEV(Value *V) {
3908 : assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3909 :
3910 2702 : const SCEV *S = getExistingSCEV(V);
3911 : if (S == nullptr) {
3912 : S = createSCEV(V);
3913 4134 : // During PHI resolution, it is possible to create two SCEVs for the same
3914 : // V, so it is needed to double check whether V->S is inserted into
3915 24 : // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3916 24 : std::pair<ValueExprMapType::iterator, bool> Pair =
3917 2708 : ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3918 : if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3919 41 : ExprValueMap[S].insert({V, nullptr});
3920 41 :
3921 : // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3922 : // ExprValueMap.
3923 1324 : const SCEV *Stripped = S;
3924 : ConstantInt *Offset = nullptr;
3925 : std::tie(Stripped, Offset) = splitAddExpr(S);
3926 : // If stripped is SCEVUnknown, don't bother to save
3927 : // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3928 : // increase the complexity of the expansion code.
3929 : // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3930 1261 : // because it may generate add/sub instead of GEP in SCEV expansion.
3931 3835 : if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3932 5148 : !isa<GetElementPtrInst>(V))
3933 1261 : ExprValueMap[Stripped].insert({V, Offset});
3934 1261 : }
3935 956 : }
3936 : return S;
3937 956 : }
3938 956 :
3939 956 : const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3940 956 : assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3941 956 :
3942 : ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3943 : if (I != ValueExprMap.end()) {
3944 17322 : const SCEV *S = I->second;
3945 : if (checkValidity(S))
3946 17322 : return S;
3947 17322 : eraseValueFromMap(V);
3948 : forgetMemoizedResults(S);
3949 : }
3950 17322 : return nullptr;
3951 : }
3952 :
3953 51966 : /// Return a SCEV corresponding to -V = -1*V
3954 34644 : const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3955 17322 : SCEV::NoWrapFlags Flags) {
3956 : if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3957 : return getConstant(
3958 358 : cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3959 :
3960 358 : Type *Ty = V->getType();
3961 358 : Ty = getEffectiveSCEVType(Ty);
3962 : return getMulExpr(
3963 : V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3964 1091 : }
3965 :
3966 : /// Return a SCEV corresponding to ~V = -1-V
3967 2182 : const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3968 0 : if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3969 : return getConstant(
3970 : cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3971 :
3972 3298 : Type *Ty = V->getType();
3973 2207 : Ty = getEffectiveSCEVType(Ty);
3974 1091 : const SCEV *AllOnes =
3975 : getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
3976 : return getMinusSCEV(AllOnes, V);
3977 369278 : }
3978 :
3979 : const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
3980 : SCEV::NoWrapFlags Flags,
3981 369278 : unsigned Depth) {
3982 : // Fast path: X - X --> 0.
3983 : if (LHS == RHS)
3984 37646 : return getZero(LHS->getType());
3985 :
3986 : // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3987 : // makes it so that we cannot make much use of NUW.
3988 : auto AddFlags = SCEV::FlagAnyWrap;
3989 : const bool RHSIsNotMinSigned =
3990 37646 : !getSignedRangeMin(RHS).isMinSignedValue();
3991 37646 : if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3992 : // Let M be the minimum representable signed value. Then (-1)*RHS
3993 : // signed-wraps if and only if RHS is M. That can happen even for
3994 282622 : // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3995 : // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3996 : // (-1)*RHS, we need to prove that RHS != M.
3997 : //
3998 : // If LHS is non-negative and we know that LHS - RHS does not
3999 : // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4000 : // either by proving that RHS > M or that LHS >= 0.
4001 282622 : if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4002 282622 : AddFlags = SCEV::FlagNSW;
4003 282622 : }
4004 282622 : }
4005 :
4006 : // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4007 : // RHS is NSW and LHS >= 0.
4008 : //
4009 227236 : // The difficulty here is that the NSW flag may have been proven
4010 227236 : // relative to a loop that is to be found in a recurrence in LHS and
4011 227236 : // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4012 227236 : // larger scope than intended.
4013 227236 : auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4014 :
4015 : return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4016 : }
4017 :
4018 : const SCEV *
4019 : ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
4020 : Type *SrcTy = V->getType();
4021 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4022 : "Cannot truncate or zero extend with non-integer arguments!");
4023 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4024 1632233 : return V; // No conversion
4025 : if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4026 1632233 : return getTruncateExpr(V, Ty);
4027 : return getZeroExtendExpr(V, Ty);
4028 : }
4029 :
4030 : const SCEV *
4031 3702970 : ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
4032 : Type *Ty) {
4033 3702970 : Type *SrcTy = V->getType();
4034 410570 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4035 3292400 : "Cannot truncate or zero extend with non-integer arguments!");
4036 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4037 : return V; // No conversion
4038 : if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4039 : return getTruncateExpr(V, Ty);
4040 : return getSignExtendExpr(V, Ty);
4041 2835674 : }
4042 :
4043 : const SCEV *
4044 2835674 : ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4045 : Type *SrcTy = V->getType();
4046 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4047 : "Cannot noop or zero extend with non-integer arguments!");
4048 : assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4049 829844 : "getNoopOrZeroExtend cannot truncate!");
4050 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4051 : return V; // No conversion
4052 841 : return getZeroExtendExpr(V, Ty);
4053 841 : }
4054 :
4055 : const SCEV *
4056 658341 : ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4057 658341 : Type *SrcTy = V->getType();
4058 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4059 : "Cannot noop or sign extend with non-integer arguments!");
4060 2016965 : assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4061 : "getNoopOrSignExtend cannot truncate!");
4062 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4063 1405841 : return V; // No conversion
4064 : return getSignExtendExpr(V, Ty);
4065 : }
4066 2016965 :
4067 : const SCEV *
4068 : ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4069 78043 : Type *SrcTy = V->getType();
4070 78043 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4071 78043 : "Cannot noop or any extend with non-integer arguments!");
4072 17392 : assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4073 : "getNoopOrAnyExtend cannot truncate!");
4074 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4075 60651 : return V; // No conversion
4076 60651 : return getAnyExtendExpr(V, Ty);
4077 : }
4078 :
4079 : const SCEV *
4080 : ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4081 : Type *SrcTy = V->getType();
4082 738514 : assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4083 : "Cannot truncate or noop with non-integer arguments!");
4084 : assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4085 583616 : "getTruncateOrNoop cannot extend!");
4086 : if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4087 154898 : return V; // No conversion
4088 8995 : return getTruncateExpr(V, Ty);
4089 : }
4090 145903 :
4091 : const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4092 23924 : const SCEV *RHS) {
4093 : const SCEV *PromotedLHS = LHS;
4094 121979 : const SCEV *PromotedRHS = RHS;
4095 :
4096 : if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4097 : PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4098 : else
4099 : PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4100 240805 :
4101 240805 : return getUMaxExpr(PromotedLHS, PromotedRHS);
4102 240805 : }
4103 :
4104 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4105 : const SCEV *RHS) {
4106 : SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4107 : return getUMinFromMismatchedTypes(Ops);
4108 : }
4109 :
4110 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4111 99447 : SmallVectorImpl<const SCEV *> &Ops) {
4112 : assert(!Ops.empty() && "At least one operand must be!");
4113 : // Trivial case.
4114 : if (Ops.size() == 1)
4115 : return Ops[0];
4116 :
4117 134807 : // Find the max type first.
4118 134807 : Type *MaxType = nullptr;
4119 134807 : for (auto *S : Ops)
4120 122909 : if (MaxType)
4121 : MaxType = getWiderType(MaxType, S->getType());
4122 122909 : else
4123 69611 : MaxType = S->getType();
4124 :
4125 : // Extend all ops to max type.
4126 : SmallVector<const SCEV *, 2> PromotedOps;
4127 : for (auto *S : Ops)
4128 122909 : PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4129 122909 :
4130 17556 : // Generate umin.
4131 977 : return getUMinExpr(PromotedOps);
4132 : }
4133 245818 :
4134 : const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4135 134807 : // A pointer operand may evaluate to a nonpointer expression, such as null.
4136 : if (!V->getType()->isPointerTy())
4137 : return V;
4138 :
4139 : if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4140 637589 : return getPointerBase(Cast->getOperand());
4141 : } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4142 : const SCEV *PtrOp = nullptr;
4143 : for (const SCEV *NAryOp : NAry->operands()) {
4144 78343 : if (NAryOp->getType()->isPointerTy()) {
4145 : // Cannot find the base of an expression with multiple pointer operands.
4146 60226 : if (PtrOp)
4147 2150 : return V;
4148 : PtrOp = NAryOp;
4149 7343 : }
4150 1717 : }
4151 : if (!PtrOp)
4152 : return V;
4153 : return getPointerBase(PtrOp);
4154 : }
4155 : return V;
4156 : }
4157 2711046 :
4158 : /// Push users of the given Instruction onto the given Worklist.
4159 : static void
4160 2711046 : PushDefUseChildren(Instruction *I,
4161 2711046 : SmallVectorImpl<Instruction *> &Worklist) {
4162 701261 : // Push the def-use children onto the Worklist stack.
4163 : for (User *U : I->users())
4164 : Worklist.push_back(cast<Instruction>(U));
4165 : }
4166 :
4167 1402522 : void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4168 701261 : SmallVector<Instruction *, 16> Worklist;
4169 615605 : PushDefUseChildren(PN, Worklist);
4170 :
4171 : SmallPtrSet<Instruction *, 8> Visited;
4172 : Visited.insert(PN);
4173 615605 : while (!Worklist.empty()) {
4174 : Instruction *I = Worklist.pop_back_val();
4175 615605 : if (!Visited.insert(I).second)
4176 : continue;
4177 :
4178 : auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4179 : if (It != ValueExprMap.end()) {
4180 : const SCEV *Old = It->second;
4181 615605 :
4182 : // Short-circuit the def-use traversal if the symbolic name
4183 3442 : // ceases to appear in expressions.
4184 : if (Old != SymName && !hasOperand(Old, SymName))
4185 : continue;
4186 2711046 :
4187 : // SCEVUnknown for a PHI either means that it has an unrecognized
4188 : // structure, it's a PHI that's in the progress of being computed
4189 2802907 : // by createNodeForPHI, or it's a single-value PHI. In the first case,
4190 : // additional loop trip count information isn't going to change anything.
4191 : // In the second case, createNodeForPHI will perform the necessary
4192 2802907 : // updates on its own when it gets to that point. In the third, we do
4193 2802907 : // want to forget the SCEVUnknown.
4194 2016965 : if (!isa<PHINode>(I) ||
4195 2016965 : !isa<SCEVUnknown>(Old) ||
4196 : (I != PN && Old == SymName)) {
4197 0 : eraseValueFromMap(It->first);
4198 0 : forgetMemoizedResults(Old);
4199 : }
4200 : }
4201 :
4202 : PushDefUseChildren(I, Worklist);
4203 : }
4204 894892 : }
4205 :
4206 : namespace {
4207 487301 :
4208 974602 : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4209 : /// expression in case its Loop is L. If it is not L then
4210 407591 : /// if IgnoreOtherLoops is true then use AddRec itself
4211 407591 : /// otherwise rewrite cannot be done.
4212 407591 : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4213 407591 : class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4214 : public:
4215 : static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4216 : bool IgnoreOtherLoops = true) {
4217 170709 : SCEVInitRewriter Rewriter(L, SE);
4218 : const SCEV *Result = Rewriter.visit(S);
4219 87407 : if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4220 174814 : return SE.getCouldNotCompute();
4221 : return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4222 83302 : ? SE.getCouldNotCompute()
4223 83302 : : Result;
4224 : }
4225 83302 :
4226 83302 : const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4227 : if (!SE.isLoopInvariant(Expr, L))
4228 : SeenLoopVariantSCEVUnknown = true;
4229 1028559 : return Expr;
4230 : }
4231 :
4232 : const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4233 1028559 : // Only re-write AddRecExprs for this loop.
4234 304478 : if (Expr->getLoop() == L)
4235 : return Expr->getStart();
4236 : SeenOtherLoops = true;
4237 : return Expr;
4238 : }
4239 :
4240 877629 : bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4241 876320 :
4242 : bool hasSeenOtherLoops() { return SeenOtherLoops; }
4243 :
4244 : private:
4245 : explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4246 : : SCEVRewriteVisitor(SE), L(L) {}
4247 :
4248 : const Loop *L;
4249 : bool SeenLoopVariantSCEVUnknown = false;
4250 : bool SeenOtherLoops = false;
4251 317 : };
4252 :
4253 : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4254 : /// increment expression in case its Loop is L. If it is not L then
4255 : /// use AddRec itself.
4256 : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4257 : class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4258 : public:
4259 : static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4260 : SCEVPostIncRewriter Rewriter(L, SE);
4261 : const SCEV *Result = Rewriter.visit(S);
4262 : return Rewriter.hasSeenLoopVariantSCEVUnknown()
4263 876320 : ? SE.getCouldNotCompute()
4264 : : Result;
4265 876320 : }
4266 :
4267 : const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4268 : if (!SE.isLoopInvariant(Expr, L))
4269 93333 : SeenLoopVariantSCEVUnknown = true;
4270 93333 : return Expr;
4271 : }
4272 :
4273 93333 : const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4274 : // Only re-write AddRecExprs for this loop.
4275 19243 : if (Expr->getLoop() == L)
4276 9405 : return Expr->getPostIncExpr(SE);
4277 9838 : SeenOtherLoops = true;
4278 : return Expr;
4279 : }
4280 :
4281 325501 : bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4282 :
4283 325501 : bool hasSeenOtherLoops() { return SeenOtherLoops; }
4284 :
4285 : private:
4286 325501 : explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4287 : : SCEVRewriteVisitor(SE), L(L) {}
4288 23113 :
4289 646 : const Loop *L;
4290 22467 : bool SeenLoopVariantSCEVUnknown = false;
4291 : bool SeenOtherLoops = false;
4292 : };
4293 :
4294 180126 : /// This class evaluates the compare condition by matching it against the
4295 180126 : /// condition of loop latch. If there is a match we assume a true value
4296 : /// for the condition while building SCEV nodes.
4297 : class SCEVBackedgeConditionFolder
4298 : : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4299 : public:
4300 180126 : static const SCEV *rewrite(const SCEV *S, const Loop *L,
4301 : ScalarEvolution &SE) {
4302 22956 : bool IsPosBECond = false;
4303 : Value *BECond = nullptr;
4304 : if (BasicBlock *Latch = L->getLoopLatch()) {
4305 : BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4306 3978 : if (BI && BI->isConditional()) {
4307 3978 : assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4308 : "Both outgoing branches should not target same header!");
4309 : BECond = BI->getCondition();
4310 : IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4311 : } else {
4312 3978 : return S;
4313 : }
4314 520 : }
4315 : SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4316 : return Rewriter.visit(S);
4317 : }
4318 84 :
4319 84 : const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4320 : const SCEV *Result = Expr;
4321 : bool InvariantF = SE.isLoopInvariant(Expr, L);
4322 :
4323 : if (!InvariantF) {
4324 84 : Instruction *I = cast<Instruction>(Expr->getValue());
4325 : switch (I->getOpcode()) {
4326 0 : case Instruction::Select: {
4327 : SelectInst *SI = cast<SelectInst>(I);
4328 : Optional<const SCEV *> Res =
4329 : compareWithBackedgeCondition(SI->getCondition());
4330 277 : if (Res.hasValue()) {
4331 277 : bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4332 : Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4333 : }
4334 : break;
4335 : }
4336 277 : default: {
4337 : Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4338 24 : if (Res.hasValue())
4339 : Result = Res.getValue();
4340 : break;
4341 0 : }
4342 : }
4343 : }
4344 : return Result;
4345 : }
4346 0 :
4347 0 : private:
4348 : explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4349 0 : bool IsPosBECond, ScalarEvolution &SE)
4350 : : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4351 0 : IsPositiveBECond(IsPosBECond) {}
4352 :
4353 : Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4354 419 :
4355 : const Loop *L;
4356 419 : /// Loop back condition.
4357 419 : Value *BackedgeCond = nullptr;
4358 : /// Set to true if loop back is on positive branch condition.
4359 : bool IsPositiveBECond;
4360 33779 : };
4361 :
4362 : Optional<const SCEV *>
4363 : SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4364 67558 :
4365 33046 : // If value matches the backedge condition for loop latch,
4366 : // then return a constant evolution node based on loopback
4367 : // branch taken.
4368 : if (BackedgeCond == IC)
4369 2224 : return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4370 1491 : : SE.getZero(Type::getInt1Ty(SE.getContext()));
4371 758 : return None;
4372 : }
4373 733 :
4374 : class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4375 : public:
4376 : static const SCEV *rewrite(const SCEV *S, const Loop *L,
4377 2224 : ScalarEvolution &SE) {
4378 1491 : SCEVShiftRewriter Rewriter(L, SE);
4379 : const SCEV *Result = Rewriter.visit(S);
4380 : return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4381 733 : }
4382 :
4383 : const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4384 56377 : // Only allow AddRecExprs for this loop.
4385 : if (!SE.isLoopInvariant(Expr, L))
4386 110471 : Valid = false;
4387 : return Expr;
4388 : }
4389 :
4390 0 : const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4391 : if (Expr->getLoop() == L && Expr->isAffine())
4392 : return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4393 163728 : Valid = false;
4394 109634 : return Expr;
4395 : }
4396 54094 :
4397 : bool isValid() { return Valid; }
4398 :
4399 : private:
4400 : explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4401 54094 : : SCEVRewriteVisitor(SE), L(L) {}
4402 :
4403 : const Loop *L;
4404 : bool Valid = true;
4405 : };
4406 :
4407 : } // end anonymous namespace
4408 :
4409 : SCEV::NoWrapFlags
4410 537992 : ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4411 : if (!AR->isAffine())
4412 : return SCEV::FlagAnyWrap;
4413 1146803 :
4414 608811 : using OBO = OverflowingBinaryOperator;
4415 537992 :
4416 : SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4417 12837 :
4418 : if (!AR->hasNoSignedWrap()) {
4419 12837 : ConstantRange AddRecRange = getSignedRange(AR);
4420 : ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4421 :
4422 12837 : auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4423 282945 : Instruction::Add, IncRange, OBO::NoSignedWrap);
4424 : if (NSWRegion.contains(AddRecRange))
4425 270108 : Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4426 45826 : }
4427 :
4428 230398 : if (!AR->hasNoUnsignedWrap()) {
4429 230398 : ConstantRange AddRecRange = getUnsignedRange(AR);
4430 22714 : ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4431 :
4432 : auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4433 : Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4434 22714 : if (NUWRegion.contains(AddRecRange))
4435 : Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4436 : }
4437 :
4438 : return Result;
4439 : }
4440 :
4441 : namespace {
4442 :
4443 : /// Represents an abstract binary operation. This may exist as a
4444 18 : /// normal instruction or constant expression, or may have been
4445 16603 : /// derived from an expression tree.
4446 5 : struct BinaryOp {
4447 16598 : unsigned Opcode;
4448 16598 : Value *LHS;
4449 : Value *RHS;
4450 : bool IsNSW = false;
4451 : bool IsNUW = false;
4452 224282 :
4453 : /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4454 12837 : /// constant expression.
4455 : Operator *Op = nullptr;
4456 :
4457 : explicit BinaryOp(Operator *Op)
4458 : : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4459 : Op(Op) {
4460 : if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4461 : IsNSW = OBO->hasNoSignedWrap();
4462 : IsNUW = OBO->hasNoUnsignedWrap();
4463 : }
4464 : }
4465 39118 :
4466 : explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4467 : bool IsNUW = false)
4468 39118 : : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4469 39118 : };
4470 1241 :
4471 244 : } // end anonymous namespace
4472 37877 :
4473 : /// Try to map \p V into a BinaryOp, and return \c None on failure.
4474 : static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4475 : auto *Op = dyn_cast<Operator>(V);
4476 : if (!Op)
4477 6532 : return None;
4478 1273 :
4479 : // Implementation detail: all the cleverness here should happen without
4480 : // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4481 : // SCEV expressions when possible, and we should not break that.
4482 0 :
4483 : switch (Op->getOpcode()) {
4484 16877 : case Instruction::Add:
4485 16629 : case Instruction::Sub:
4486 248 : case Instruction::Mul:
4487 0 : case Instruction::UDiv:
4488 : case Instruction::URem:
4489 : case Instruction::And:
4490 0 : case Instruction::Or:
4491 : case Instruction::AShr:
4492 0 : case Instruction::Shl:
4493 : return BinaryOp(Op);
4494 :
4495 : case Instruction::Xor:
4496 39118 : if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4497 : // If the RHS of the xor is a signmask, then this is just an add.
4498 : // Instcombine turns add of signmask into xor as a strength reduction step.
4499 : if (RHSC->getValue().isSignMask())
4500 : return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4501 : return BinaryOp(Op);
4502 :
4503 : case Instruction::LShr:
4504 : // Turn logical shift right of a constant into a unsigned divide.
4505 : if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4506 : uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4507 :
4508 : // If the shift count is not less than the bitwidth, the result of
4509 29965 : // the shift is undefined. Don't try to analyze it, because the
4510 : // resolution chosen here may differ from the resolution chosen in
4511 29965 : // other parts of the compiler.
4512 29965 : if (SA->getValue().ult(BitWidth)) {
4513 29965 : Constant *X =
4514 29965 : ConstantInt::get(SA->getContext(),
4515 : APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4516 : return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4517 : }
4518 5108 : }
4519 0 : return BinaryOp(Op);
4520 :
4521 : case Instruction::ExtractValue: {
4522 : auto *EVI = cast<ExtractValueInst>(Op);
4523 15877 : if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4524 : break;
4525 15877 :
4526 15633 : auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
4527 244 : if (!CI)
4528 244 : break;
4529 :
4530 : if (auto *F = CI->getCalledFunction())
4531 0 : switch (F->getIntrinsicID()) {
4532 : case Intrinsic::sadd_with_overflow:
4533 : case Intrinsic::uadd_with_overflow:
4534 : if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4535 : return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4536 : CI->getArgOperand(1));
4537 29965 :
4538 : // Now that we know that all uses of the arithmetic-result component of
4539 : // CI are guarded by the overflow check, we can go ahead and pretend
4540 : // that the arithmetic is non-overflowing.
4541 : if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
4542 : return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4543 : CI->getArgOperand(1), /* IsNSW = */ true,
4544 : /* IsNUW = */ false);
4545 : else
4546 : return BinaryOp(Instruction::Add, CI->getArgOperand(0),
4547 : CI->getArgOperand(1), /* IsNSW = */ false,
4548 : /* IsNUW*/ true);
4549 : case Intrinsic::ssub_with_overflow:
4550 13532 : case Intrinsic::usub_with_overflow:
4551 : if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
4552 : return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4553 : CI->getArgOperand(1));
4554 13532 :
4555 : // The same reasoning as sadd/uadd above.
4556 13466 : if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
4557 : return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4558 : CI->getArgOperand(1), /* IsNSW = */ true,
4559 : /* IsNUW = */ false);
4560 12628 : else
4561 : return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
4562 : CI->getArgOperand(1), /* IsNSW = */ false,
4563 : /* IsNUW = */ true);
4564 : case Intrinsic::smul_with_overflow:
4565 : case Intrinsic::umul_with_overflow:
4566 12639 : return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
4567 : CI->getArgOperand(1));
4568 : default:
4569 2115 : break;
4570 2115 : }
4571 2115 : break;
4572 : }
4573 2115 :
4574 : default:
4575 1748 : break;
4576 : }
4577 :
4578 : return None;
4579 114 : }
4580 114 :
4581 5 : /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4582 10 : /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4583 : /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4584 : /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4585 : /// follows one of the following patterns:
4586 1634 : /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4587 1634 : /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4588 1634 : /// If the SCEV expression of \p Op conforms with one of the expected patterns
4589 4 : /// we return the type of the truncation operation, and indicate whether the
4590 : /// truncated type should be treated as signed/unsigned by setting
4591 : /// \p Signed to true/false, respectively.
4592 : static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4593 : bool &Signed, ScalarEvolution &SE) {
4594 2115 : // The case where Op == SymbolicPHI (that is, with no type conversions on
4595 : // the way) is handled by the regular add recurrence creating logic and
4596 : // would have already been triggered in createAddRecForPHI. Reaching it here
4597 : // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4598 : // because one of the other operands of the SCEVAddExpr updating this PHI is
4599 : // not invariant).
4600 12639 : //
4601 12639 : // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4602 : // this case predicates that allow us to prove that Op == SymbolicPHI will
4603 : // be added.
4604 : if (Op == SymbolicPHI)
4605 : return nullptr;
4606 :
4607 : unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4608 : unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4609 : if (SourceBits != NewBits)
4610 : return nullptr;
4611 :
4612 : const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4613 1748 : const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4614 : if (!SExt && !ZExt)
4615 : return nullptr;
4616 : const SCEVTruncateExpr *Trunc =
4617 : SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4618 1748 : : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4619 9 : if (!Trunc)
4620 1 : return nullptr;
4621 : const SCEV *X = Trunc->getOperand();
4622 : if (X != SymbolicPHI)
4623 : return nullptr;
4624 : Signed = SExt != nullptr;
4625 : return Trunc->getType();
4626 7912 : }
4627 :
4628 : static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4629 7912 : if (!PN->getType()->isIntegerTy())
4630 7912 : return nullptr;
4631 : const Loop *L = LI.getLoopFor(PN->getParent());
4632 : if (!L || L->getHeader() != PN->getParent())
4633 : return nullptr;
4634 : return L;
4635 6881 : }
4636 6755 :
4637 : // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4638 : // computation that updates the phi follows the following pattern:
4639 : // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4640 1105 : // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4641 1105 : // If so, try to see if it can be rewritten as an AddRecExpr under some
4642 1027 : // Predicates. If successful, return them as a pair. Also cache the results
4643 78 : // of the analysis.
4644 78 : //
4645 : // Example usage scenario:
4646 : // Say the Rewriter is called for the following SCEV:
4647 0 : // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4648 : // where:
4649 : // %X = phi i64 (%Start, %BEValue)
4650 : // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4651 7912 : // and call this function with %SymbolicPHI = %X.
4652 : //
4653 : // The analysis will find that the value coming around the backedge has
4654 : // the following SCEV:
4655 : // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4656 : // Upon concluding that this matches the desired pattern, the function
4657 : // will return the pair {NewAddRec, SmallPredsVec} where:
4658 : // NewAddRec = {%Start,+,%Step}
4659 : // SmallPredsVec = {P1, P2, P3} as follows:
4660 40552 : // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4661 40552 : // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4662 : // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4663 : // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4664 : // under the predicates {P1,P2,P3}.
4665 : // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4666 : // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4667 : //
4668 40552 : // TODO's:
4669 29097 : //
4670 58194 : // 1) Extend the Induction descriptor to also support inductions that involve
4671 : // casts: When needed (namely, when we are called in the context of the
4672 : // vectorizer induction analysis), a Set of cast instructions will be
4673 58194 : // populated by this method, and provided back to isInductionPHI. This is
4674 29097 : // needed to allow the vectorizer to properly record them to be ignored by
4675 : // the cost model and to avoid vectorizing them (otherwise these casts,
4676 : // which are redundant under the runtime overflow checks, will be
4677 : // vectorized, which can be costly).
4678 40552 : //
4679 38989 : // 2) Support additional induction/PHISCEV patterns: We also want to support
4680 77978 : // inductions where the sext-trunc / zext-trunc operations (partly) occur
4681 : // after the induction update operation (the induction increment):
4682 : //
4683 77978 : // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4684 38989 : // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4685 : //
4686 : // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4687 : // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4688 : //
4689 : // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4690 : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4691 : ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4692 : SmallVector<const SCEVPredicate *, 3> Predicates;
4693 :
4694 : // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4695 : // return an AddRec expression under some predicate.
4696 :
4697 : auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4698 : const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4699 : assert(L && "Expecting an integer loop header phi");
4700 :
4701 : // The loop may have multiple entrances or multiple exits; we can analyze
4702 : // this phi as an addrec if it has a unique entry value and a unique
4703 : // backedge value.
4704 : Value *BEValueV = nullptr, *StartValueV = nullptr;
4705 : for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4706 : Value *V = PN->getIncomingValue(i);
4707 162486 : if (L->contains(PN->getIncomingBlock(i))) {
4708 162486 : if (!BEValueV) {
4709 487458 : BEValueV = V;
4710 : } else if (BEValueV != V) {
4711 152234 : BEValueV = nullptr;
4712 152234 : break;
4713 : }
4714 162486 : } else if (!StartValueV) {
4715 : StartValueV = V;
4716 : } else if (StartValueV != V) {
4717 : StartValueV = nullptr;
4718 : break;
4719 : }
4720 : }
4721 : if (!BEValueV || !StartValueV)
4722 : return None;
4723 :
4724 648645 : const SCEV *BEValue = getSCEV(BEValueV);
4725 :
4726 : // If the value coming around the backedge is an add with the symbolic
4727 : // value we just inserted, possibly with casts that we can ignore under
4728 : // an appropriate runtime guard, then we found a simple induction variable!
4729 : const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4730 : if (!Add)
4731 : return None;
4732 :
4733 644643 : // If there is a single occurrence of the symbolic value, possibly
4734 161154 : // casted, replace it with a recurrence.
4735 : unsigned FoundIndex = Add->getNumOperands();
4736 : Type *TruncTy = nullptr;
4737 : bool Signed;
4738 : for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4739 : if ((TruncTy =
4740 : isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4741 : if (FoundIndex == e) {
4742 : FoundIndex = i;
4743 161154 : break;
4744 : }
4745 1055 :
4746 1055 : if (FoundIndex == Add->getNumOperands())
4747 : return None;
4748 :
4749 445 : // Create an add with everything but the specified operand.
4750 : SmallVector<const SCEV *, 8> Ops;
4751 1023 : for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4752 : if (i != FoundIndex)
4753 6075 : Ops.push_back(Add->getOperand(i));
4754 : const SCEV *Accum = getAddExpr(Ops);
4755 6075 :
4756 5768 : // The runtime checks will not be valid if the step amount is
4757 : // varying inside the loop.
4758 : if (!isLoopInvariant(Accum, L))
4759 : return None;
4760 :
4761 : // *** Part2: Create the predicates
4762 5768 :
4763 : // Analysis was successful: we have a phi-with-cast pattern for which we
4764 5766 : // can return an AddRec expression under the following predicates:
4765 11532 : //
4766 : // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4767 : // fits within the truncated type (does not overflow) for i = 0 to n-1.
4768 : // P2: An Equal predicate that guarantees that
4769 309 : // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4770 : // P3: An Equal predicate that guarantees that
4771 : // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4772 : //
4773 1025 : // As we next prove, the above predicates guarantee that:
4774 : // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4775 : //
4776 : //
4777 : // More formally, we want to prove that:
4778 : // Expr(i+1) = Start + (i+1) * Accum
4779 : // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4780 : //
4781 189 : // Given that:
4782 : // 1) Expr(0) = Start
4783 : // 2) Expr(1) = Start + Accum
4784 93 : // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4785 30 : // 3) Induction hypothesis (step i):
4786 : // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4787 : //
4788 : // Proof:
4789 : // Expr(i+1) =
4790 : // = Start + (i+1)*Accum
4791 63 : // = (Start + i*Accum) + Accum
4792 56 : // = Expr(i) + Accum
4793 : // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4794 : // :: from step i
4795 : //
4796 7 : // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4797 : //
4798 : // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4799 : // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4800 : // + Accum :: from P3
4801 61 : //
4802 22 : // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4803 : // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4804 : //
4805 : // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4806 39 : // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4807 21 : //
4808 : // By induction, the same applies to all iterations 1<=i<n:
4809 : //
4810 :
4811 18 : // Create a truncated addrec for which we will add a no overflow check (P1).
4812 : const SCEV *StartVal = getSCEV(StartValueV);
4813 : const SCEV *PHISCEV =
4814 9 : getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4815 : getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4816 9 :
4817 : // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4818 : // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4819 : // will be constant.
4820 : //
4821 : // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4822 : // add P1.
4823 : if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4824 : SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4825 : Signed ? SCEVWrapPredicate::IncrementNSSW
4826 : : SCEVWrapPredicate::IncrementNUSW;
4827 : const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4828 : Predicates.push_back(AddRecPred);
4829 : }
4830 :
4831 : // Create the Equal Predicates P2,P3:
4832 :
4833 : // It is possible that the predicates P2 and/or P3 are computable at
4834 : // compile time due to StartVal and/or Accum being constants.
4835 : // If either one is, then we can check that now and escape if either P2
4836 : // or P3 is false.
4837 :
4838 : // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4839 : // for each of StartVal and Accum
4840 : auto getExtendedExpr = [&](const SCEV *Expr,
4841 : bool CreateSignExtend) -> const SCEV * {
4842 116 : assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4843 : const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4844 : const SCEV *ExtendedExpr =
4845 : CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4846 : : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4847 : return ExtendedExpr;
4848 : };
4849 :
4850 : // Given:
4851 : // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4852 : // = getExtendedExpr(Expr)
4853 : // Determine whether the predicate P: Expr == ExtendedExpr
4854 116 : // is known to be false at compile time
4855 : auto PredIsKnownFalse = [&](const SCEV *Expr,
4856 : const SCEV *ExtendedExpr) -> bool {
4857 96 : return Expr != ExtendedExpr &&
4858 96 : isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4859 96 : };
4860 :
4861 : const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4862 : if (PredIsKnownFalse(StartVal, StartExtended)) {
4863 : LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4864 96 : return None;
4865 : }
4866 :
4867 23 : // The Step is always Signed (because the overflow checks are either
4868 12 : // NSSW or NUSW)
4869 19 : const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4870 : if (PredIsKnownFalse(Accum, AccumExtended)) {
4871 19 : LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4872 19 : return None;
4873 : }
4874 19 :
4875 19 : auto AppendPredicate = [&](const SCEV *Expr,
4876 : const SCEV *ExtendedExpr) -> void {
4877 : if (Expr != ExtendedExpr &&
4878 1932 : !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4879 3864 : const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4880 : LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4881 1093 : Predicates.push_back(Pred);
4882 995 : }
4883 135 : };
4884 :
4885 : AppendPredicate(StartVal, StartExtended);
4886 : AppendPredicate(Accum, AccumExtended);
4887 :
4888 : // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4889 : // which the casts had been folded away. The caller can rewrite SymbolicPHI
4890 : // into NewAR if it will also add the runtime overflow checks specified in
4891 : // Predicates.
4892 : auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4893 :
4894 : std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4895 : std::make_pair(NewAR, Predicates);
4896 : // Remember the result of the analysis for this SCEV at this locayyytion.
4897 : PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4898 : return PredRewrite;
4899 : }
4900 :
4901 : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4902 : ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4903 : auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4904 : const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4905 : if (!L)
4906 : return None;
4907 :
4908 : // Check to see if we already analyzed this PHI.
4909 : auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4910 : if (I != PredicatedSCEVRewrites.end()) {
4911 : std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4912 : I->second;
4913 : // Analysis was done before and failed to create an AddRec:
4914 : if (Rewrite.first == SymbolicPHI)
4915 : return None;
4916 : // Analysis was done before and succeeded to create an AddRec under
4917 : // a predicate:
4918 : assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4919 : assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4920 : return Rewrite;
4921 : }
4922 :
4923 : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4924 : Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4925 :
4926 : // Record in the cache that the analysis failed
4927 : if (!Rewrite) {
4928 : SmallVector<const SCEVPredicate *, 3> Predicates;
4929 : PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4930 : return None;
4931 : }
4932 :
4933 : return Rewrite;
4934 : }
4935 :
4936 : // FIXME: This utility is currently required because the Rewriter currently
4937 : // does not rewrite this expression:
4938 : // {0, +, (sext ix (trunc iy to ix) to iy)}
4939 : // into {0, +, %step},
4940 : // even when the following Equal predicate exists:
4941 330 : // "%step == (sext ix (trunc iy to ix) to iy)".
4942 : bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4943 : const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4944 : if (AR1 == AR2)
4945 : return true;
4946 :
4947 : auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4948 330 : if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4949 : !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4950 : return false;
4951 : return true;
4952 : };
4953 :
4954 : if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4955 990 : !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4956 : return false;
4957 661 : return true;
4958 330 : }
4959 :
4960 0 : /// A helper function for createAddRecFromPHI to handle simple cases.
4961 : ///
4962 : /// This function tries to find an AddRec expression for the simplest (yet most
4963 : /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4964 331 : /// If it fails, createAddRecFromPHI will use a more general, but slow,
4965 : /// technique for finding the AddRec expression.
4966 1 : const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4967 : Value *BEValueV,
4968 : Value *StartValueV) {
4969 : const Loop *L = LI.getLoopFor(PN->getParent());
4970 : assert(L && L->getHeader() == PN->getParent());
4971 330 : assert(BEValueV && StartValueV);
4972 :
4973 : auto BO = MatchBinaryOp(BEValueV, DT);
4974 329 : if (!BO)
4975 : return nullptr;
4976 :
4977 : if (BO->Opcode != Instruction::Add)
4978 : return nullptr;
4979 :
4980 : const SCEV *Accum = nullptr;
4981 : if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4982 : Accum = getSCEV(BO->RHS);
4983 : else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4984 : Accum = getSCEV(BO->LHS);
4985 56 :
4986 56 : if (!Accum)
4987 : return nullptr;
4988 153 :
4989 116 : SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4990 232 : if (BO->IsNUW)
4991 : Flags = setFlags(Flags, SCEV::FlagNUW);
4992 : if (BO->IsNSW)
4993 : Flags = setFlags(Flags, SCEV::FlagNSW);
4994 :
4995 : const SCEV *StartVal = getSCEV(StartValueV);
4996 56 : const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4997 :
4998 : ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4999 :
5000 : // We can add Flags to the post-inc expression only if we
5001 57 : // know that it is *undefined behavior* for BEValueV to
5002 38 : // overflow.
5003 38 : if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5004 19 : if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5005 : (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5006 :
5007 : return PHISCEV;
5008 19 : }
5009 :
5010 : const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5011 : const Loop *L = LI.getLoopFor(PN->getParent());
5012 : if (!L || L->getHeader() != PN->getParent())
5013 : return nullptr;
5014 :
5015 : // The loop may have multiple entrances or multiple exits; we can analyze
5016 : // this phi as an addrec if it has a unique entry value and a unique
5017 : // backedge value.
5018 : Value *BEValueV = nullptr, *StartValueV = nullptr;
5019 : for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5020 : Value *V = PN->getIncomingValue(i);
5021 : if (L->contains(PN->getIncomingBlock(i))) {
5022 : if (!BEValueV) {
5023 : BEValueV = V;
5024 : } else if (BEValueV != V) {
5025 : BEValueV = nullptr;
5026 : break;
5027 : }
5028 : } else if (!StartValueV) {
5029 : StartValueV = V;
5030 : } else if (StartValueV != V) {
5031 : StartValueV = nullptr;
5032 : break;
5033 : }
5034 : }
5035 : if (!BEValueV || !StartValueV)
5036 : return nullptr;
5037 :
5038 : assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5039 : "PHI node already processed?");
5040 :
5041 : // First, try to find AddRec expression without creating a fictituos symbolic
5042 : // value for PN.
5043 : if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5044 : return S;
5045 :
5046 : // Handle PHI node value symbolically.
5047 : const SCEV *SymbolicName = getUnknown(PN);
5048 : ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5049 :
5050 : // Using this symbolic name for the PHI, analyze the value coming around
5051 : // the back-edge.
5052 : const SCEV *BEValue = getSCEV(BEValueV);
5053 :
5054 : // NOTE: If BEValue is loop invariant, we know that the PHI node just
5055 : // has a special value for the first iteration of the loop.
5056 :
5057 : // If the value coming around the backedge is an add with the symbolic
5058 : // value we just inserted, then we found a simple induction variable!
5059 : if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5060 : // If there is a single occurrence of the symbolic value, replace it
5061 : // with a recurrence.
5062 18 : unsigned FoundIndex = Add->getNumOperands();
5063 : for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5064 18 : if (Add->getOperand(i) == SymbolicName)
5065 : if (FoundIndex == e) {
5066 : FoundIndex = i;
5067 : break;
5068 : }
5069 :
5070 : if (FoundIndex != Add->getNumOperands()) {
5071 : // Create an add with everything but the specified operand.
5072 : SmallVector<const SCEV *, 8> Ops;
5073 : for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5074 : if (i != FoundIndex)
5075 16 : Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5076 : L, *this));
5077 16 : const SCEV *Accum = getAddExpr(Ops);
5078 16 :
5079 : // This is not a valid addrec if the step amount is varying each
5080 : // loop iteration, but is not itself an addrec in this loop.
5081 : if (isLoopInvariant(Accum, L) ||
5082 : (isa<SCEVAddRecExpr>(Accum) &&
5083 : cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5084 : SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5085 :
5086 : if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5087 : if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5088 : if (BO->IsNUW)
5089 : Flags = setFlags(Flags, SCEV::FlagNUW);
5090 : if (BO->IsNSW)
5091 : Flags = setFlags(Flags, SCEV::FlagNSW);
5092 : }
5093 : } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5094 : // If the increment is an inbounds GEP, then we know the address
5095 : // space cannot be wrapped around. We cannot make any guarantee
5096 : // about signed or unsigned overflow because pointers are
5097 : // unsigned but we may have a negative index from the base
5098 18 : // pointer. We can guarantee that no unsigned wrap occurs if the
5099 : // indices form a positive value.
5100 : if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5101 : Flags = setFlags(Flags, SCEV::FlagNW);
5102 :
5103 : const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5104 : if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5105 : Flags = setFlags(Flags, SCEV::FlagNUW);
5106 : }
5107 53 :
5108 18 : // We cannot transfer nuw and nsw flags from subtraction
5109 : // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5110 : // for instance.
5111 18 : }
5112 :
5113 : const SCEV *StartVal = getSCEV(StartValueV);
5114 : const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5115 :
5116 : // Okay, for the entire analysis of this edge we assumed the PHI
5117 : // to be symbolic. We now need to go back and purge all of the
5118 : // entries for the scalars that use the symbolic expression.
5119 17 : forgetSymbolicName(PN, SymbolicName);
5120 : ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5121 :
5122 : // We can add Flags to the post-inc expression only if we
5123 : // know that it is *undefined behavior* for BEValueV to
5124 : // overflow.
5125 : if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5126 : if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5127 : (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5128 :
5129 : return PHISCEV;
5130 : }
5131 : }
5132 : } else {
5133 13 : // Otherwise, this could be a loop like this:
5134 : // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5135 13 : // In this case, j = {1,+,1} and BEValue is j.
5136 13 : // Because the other in-value of i (0) fits the evolution of BEValue
5137 : // i really is an addrec evolution.
5138 : //
5139 : // We can generalize this saying that i is the shifted value of BEValue
5140 : // by one iteration:
5141 : // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5142 13 : const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5143 : const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5144 : if (Shifted != getCouldNotCompute() &&
5145 : Start != getCouldNotCompute()) {
5146 : const SCEV *StartVal = getSCEV(StartValueV);
5147 26 : if (Start == StartVal) {
5148 : // Okay, for the entire analysis of this edge we assumed the PHI
5149 : // to be symbolic. We now need to go back and purge all of the
5150 : // entries for the scalars that use the symbolic expression.
5151 : forgetSymbolicName(PN, SymbolicName);
5152 1602 : ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5153 : return Shifted;
5154 1602 : }
5155 1602 : }
5156 : }
5157 :
5158 : // Remove the temporary PHI node SCEV that has been inserted while intending
5159 1256 : // to create an AddRecExpr for this PHI node. We can not keep this temporary
5160 628 : // as it will prevent later (possibly simpler) SCEV expressions to be added
5161 : // to the ValueExprMap.
5162 : eraseValueFromMap(PN);
5163 :
5164 298 : return nullptr;
5165 : }
5166 :
5167 : // Checks if the SCEV S is available at BB. S is considered available at BB
5168 : // if S can be materialized at BB without introducing a fault.
5169 : static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5170 : BasicBlock *BB) {
5171 : struct CheckAvailable {
5172 : bool TraversalDone = false;
5173 : bool Available = true;
5174 330 :
5175 : const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5176 : BasicBlock *BB = nullptr;
5177 330 : DominatorTree &DT;
5178 :
5179 317 : CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5180 : : L(L), BB(BB), DT(DT) {}
5181 :
5182 : bool setUnavailable() {
5183 : TraversalDone = true;
5184 : Available = false;
5185 : return false;
5186 : }
5187 :
5188 : bool follow(const SCEV *S) {
5189 : switch (S->getSCEVType()) {
5190 : case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5191 : case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5192 28 : // These expressions are available if their operand(s) is/are.
5193 : return true;
5194 28 :
5195 : case scAddRecExpr: {
5196 : // We allow add recurrences that are on the loop BB is in, or some
5197 : // outer loop. This guarantees availability because the value of the
5198 : // add recurrence at BB is simply the "current" value of the induction
5199 : // variable. We can relax this in the future; for instance an add
5200 : // recurrence on a sibling dominating loop is also available at BB.
5201 : const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5202 25 : if (L && (ARLoop == L || ARLoop->contains(L)))
5203 : return true;
5204 89 :
5205 14 : return setUnavailable();
5206 17 : }
5207 :
5208 : case scUnknown: {
5209 : // For SCEVUnknown, we check for simple dominance.
5210 : const auto *SU = cast<SCEVUnknown>(S);
5211 : Value *V = SU->getValue();
5212 :
5213 : if (isa<Argument>(V))
5214 : return false;
5215 :
5216 60314 : if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5217 : return false;
5218 :
5219 60314 : return setUnavailable();
5220 : }
5221 :
5222 : case scUDivExpr:
5223 60314 : case scCouldNotCompute:
5224 60314 : // We do not try to smart about these at all.
5225 : return setUnavailable();
5226 : }
5227 42223 : llvm_unreachable("switch should be fully covered!");
5228 : }
5229 :
5230 : bool isDone() { return TraversalDone; }
5231 41115 : };
5232 38069 :
5233 3046 : CheckAvailable CA(L, BB, DT);
5234 57 : SCEVTraversal<CheckAvailable> ST(CA);
5235 :
5236 38126 : ST.visitAll(S);
5237 2989 : return CA.Available;
5238 : }
5239 :
5240 38126 : // Try to match a control flow sequence that branches out at BI and merges back
5241 : // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5242 38126 : // match.
5243 : static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5244 : Value *&C, Value *&LHS, Value *&RHS) {
5245 38126 : C = BI->getCondition();
5246 38126 :
5247 : BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5248 76252 : BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5249 :
5250 : if (!LeftEdge.isSingleEdge())
5251 : return false;
5252 :
5253 : assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5254 38126 :
5255 16012 : Use &LeftUse = Merge->getOperandUse(0);
5256 : Use &RightUse = Merge->getOperandUse(1);
5257 :
5258 : if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5259 : LHS = LeftUse;
5260 72000 : RHS = RightUse;
5261 72000 : return true;
5262 67983 : }
5263 11627 :
5264 : if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5265 : LHS = RightUse;
5266 : RHS = LeftUse;
5267 : return true;
5268 : }
5269 181244 :
5270 : return false;
5271 120930 : }
5272 60536 :
5273 : const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5274 163 : auto IsReachable =
5275 : [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5276 : if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5277 : const Loop *L = LI.getLoopFor(PN->getParent());
5278 60394 :
5279 : // We don't want to break LCSSA, even in a SCEV expression tree.
5280 28 : for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5281 : if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5282 : return nullptr;
5283 :
5284 : // Try to match
5285 60373 : //
5286 : // br %cond, label %left, label %right
5287 : // left:
5288 : // br label %merge
5289 : // right:
5290 : // br label %merge
5291 : // merge:
5292 : // V = phi [ %x, %left ], [ %y, %right ]
5293 60314 : //
5294 : // as "select %cond, %x, %y"
5295 :
5296 : BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5297 22188 : assert(IDom && "At least the entry block should dominate PN");
5298 66564 :
5299 : auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5300 : Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5301 :
5302 22188 : if (BI && BI->isConditional() &&
5303 : BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5304 : IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5305 : IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5306 : return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5307 : }
5308 :
5309 : return nullptr;
5310 : }
5311 :
5312 14276 : const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5313 30633 : if (const SCEV *S = createAddRecFromPHI(PN))
5314 58272 : return S;
5315 :
5316 : if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5317 : return S;
5318 :
5319 : // If the PHI has a single incoming value, follow that value, unless the
5320 14276 : // PHI's incoming blocks are in a different loop, in which case doing so
5321 : // risks breaking LCSSA form. Instcombine would normally zap these, but
5322 : // it doesn't have DominatorTree information, so it may miss cases.
5323 39090 : if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5324 26311 : if (LI.replacementPreservesLCSSAForm(PN, V))
5325 27064 : return getSCEV(V);
5326 :
5327 12779 : // If it's not a loop phi, we can't handle it yet.
5328 : return getUnknown(PN);
5329 : }
5330 :
5331 12779 : const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5332 81 : Value *Cond,
5333 81 : Value *TrueVal,
5334 : Value *FalseVal) {
5335 : // Handle "constant" branch or select. This can occur for instance when a
5336 11868 : // loop pass transforms an inner loop and moves on to process the outer loop.
5337 2102 : if (auto *CI = dyn_cast<ConstantInt>(Cond))
5338 58 : return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5339 :
5340 58 : // Try to match some simple smax or umax patterns.
5341 : auto *ICI = dyn_cast<ICmpInst>(Cond);
5342 : if (!ICI)
5343 : return getUnknown(I);
5344 :
5345 : Value *LHS = ICI->getOperand(0);
5346 : Value *RHS = ICI->getOperand(1);
5347 :
5348 : switch (ICI->getPredicate()) {
5349 : case ICmpInst::ICMP_SLT:
5350 17630 : case ICmpInst::ICMP_SLE:
5351 : std::swap(LHS, RHS);
5352 : LLVM_FALLTHROUGH;
5353 8184 : case ICmpInst::ICMP_SGT:
5354 8184 : case ICmpInst::ICMP_SGE:
5355 : // a >s b ? a+x : b+x -> smax(a, b)+x
5356 : // a >s b ? b+x : a+x -> smin(a, b)+x
5357 : if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5358 : const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5359 : const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5360 : const SCEV *LA = getSCEV(TrueVal);
5361 : const SCEV *RA = getSCEV(FalseVal);
5362 : const SCEV *LDiff = getMinusSCEV(LA, LS);
5363 11868 : const SCEV *RDiff = getMinusSCEV(RA, RS);
5364 11868 : if (LDiff == RDiff)
5365 : return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5366 : LDiff = getMinusSCEV(LA, RS);
5367 : RDiff = getMinusSCEV(RA, LS);
5368 : if (LDiff == RDiff)
5369 11868 : return getAddExpr(getSMinExpr(LS, RS), LDiff);
5370 35604 : }
5371 : break;
5372 : case ICmpInst::ICMP_ULT:
5373 : case ICmpInst::ICMP_ULE:
5374 : std::swap(LHS, RHS);
5375 : LLVM_FALLTHROUGH;
5376 11868 : case ICmpInst::ICMP_UGT:
5377 3530 : case ICmpInst::ICMP_UGE:
5378 : // a >u b ? a+x : b+x -> umax(a, b)+x
5379 : // a >u b ? b+x : a+x -> umin(a, b)+x
5380 : if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5381 : const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5382 : const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5383 : const SCEV *LA = getSCEV(TrueVal);
5384 : const SCEV *RA = getSCEV(FalseVal);
5385 : const SCEV *LDiff = getMinusSCEV(LA, LS);
5386 : const SCEV *RDiff = getMinusSCEV(RA, RS);
5387 : if (LDiff == RDiff)
5388 : return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5389 : LDiff = getMinusSCEV(LA, RS);
5390 : RDiff = getMinusSCEV(RA, LS);
5391 : if (LDiff == RDiff)
5392 7912 : return getAddExpr(getUMinExpr(LS, RS), LDiff);
5393 7912 : }
5394 9127 : break;
5395 1215 : case ICmpInst::ICMP_NE:
5396 1215 : // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5397 1215 : if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5398 : isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5399 : const SCEV *One = getOne(I->getType());
5400 : const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5401 969 : const SCEV *LA = getSCEV(TrueVal);
5402 1938 : const SCEV *RA = getSCEV(FalseVal);
5403 969 : const SCEV *LDiff = getMinusSCEV(LA, LS);
5404 : const SCEV *RDiff = getMinusSCEV(RA, One);
5405 : if (LDiff == RDiff)
5406 : return getAddExpr(getUMaxExpr(One, LS), LDiff);
5407 : }
5408 : break;
5409 : case ICmpInst::ICMP_EQ:
5410 : // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5411 : if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5412 9351 : isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5413 : const SCEV *One = getOne(I->getType());
5414 9351 : const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5415 : const SCEV *LA = getSCEV(TrueVal);
5416 : const SCEV *RA = getSCEV(FalseVal);
5417 : const SCEV *LDiff = getMinusSCEV(LA, One);
5418 : const SCEV *RDiff = getMinusSCEV(RA, LS);
5419 12111 : if (LDiff == RDiff)
5420 : return getAddExpr(getUMaxExpr(One, LS), LDiff);
5421 : }
5422 : break;
5423 : default:
5424 : break;
5425 : }
5426 :
5427 : return getUnknown(I);
5428 : }
5429 :
5430 12111 : /// Expand GEP instructions into add and multiply operations. This allows them
5431 : /// to be analyzed by regular SCEV code.
5432 0 : const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5433 4782 : // Don't attempt to analyze GEPs over unsized objects.
5434 4782 : if (!GEP->getSourceElementType()->isSized())
5435 0 : return getUnknown(GEP);
5436 :
5437 : SmallVector<const SCEV *, 4> IndexExprs;
5438 22396 : for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5439 44792 : IndexExprs.push_back(getSCEV(*Index));
5440 : return getGEPExpr(GEP, IndexExprs);
5441 : }
5442 :
5443 : uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5444 : if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5445 : return C->getAPInt().countTrailingZeros();
5446 :
5447 : if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5448 : return std::min(GetMinTrailingZeros(T->getOperand()),
5449 : (uint32_t)getTypeSizeInBits(T->getType()));
5450 :
5451 583 : if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5452 677 : uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5453 : return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5454 : ? getTypeSizeInBits(E->getType())
5455 400 : : OpRes;
5456 : }
5457 :
5458 : if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5459 : uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5460 : return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5461 : ? getTypeSizeInBits(E->getType())
5462 : : OpRes;
5463 9600 : }
5464 :
5465 : if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5466 8726 : // The result is the min of all operands results.
5467 : uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5468 : for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5469 3165 : MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5470 : return MinOpRes;
5471 : }
5472 1217 :
5473 : if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5474 : // The result is the sum of all operands results.
5475 1217 : uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5476 : uint32_t BitWidth = getTypeSizeInBits(M->getType());
5477 0 : for (unsigned i = 1, e = M->getNumOperands();
5478 : SumOpRes != BitWidth && i != e; ++i)
5479 : SumOpRes =
5480 0 : std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5481 : return SumOpRes;
5482 : }
5483 :
5484 12111 : if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5485 : // The result is the min of all operands results.
5486 12111 : uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5487 12111 : for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5488 : MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5489 : return MinOpRes;
5490 : }
5491 :
5492 : if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5493 7584 : // The result is the min of all operands results.
5494 : uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5495 7584 : for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5496 : MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5497 7584 : return MinOpRes;
5498 : }
5499 :
5500 7584 : if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5501 : // The result is the min of all operands results.
5502 : uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5503 : for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5504 : MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5505 7584 : return MinOpRes;
5506 : }
5507 :
5508 7584 : if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5509 3304 : // For a SCEVUnknown, ask ValueTracking.
5510 3304 : KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5511 3304 : return Known.countMinTrailingZeros();
5512 : }
5513 :
5514 4280 : // SCEVUDivExpr
5515 3896 : return 0;
5516 3896 : }
5517 3896 :
5518 : uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5519 : auto I = MinTrailingZerosCache.find(S);
5520 : if (I != MinTrailingZerosCache.end())
5521 : return I->second;
5522 :
5523 21037 : uint32_t Result = GetMinTrailingZerosImpl(S);
5524 : auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5525 0 : assert(InsertPair.second && "Should insert a new key");
5526 38253 : return InsertPair.first->second;
5527 17215 : }
5528 :
5529 : /// Helper method to assign a range to V from metadata present in the IR.
5530 36780 : static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5531 58216 : if (Instruction *I = dyn_cast<Instruction>(V))
5532 11967 : if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5533 : return getConstantRangeFromMetadata(*MD);
5534 :
5535 : return None;
5536 : }
5537 :
5538 : /// Determine the range for a particular SCEV. If SignHint is
5539 : /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5540 : /// with a "cleaner" unsigned (resp. signed) representation.
5541 : const ConstantRange &
5542 : ScalarEvolution::getRangeRef(const SCEV *S,
5543 : ScalarEvolution::RangeSignHint SignHint) {
5544 : DenseMap<const SCEV *, ConstantRange> &Cache =
5545 : SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5546 15344 : : SignedRanges;
5547 :
5548 : // See if we've computed this range already.
5549 : DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5550 7672 : if (I != Cache.end())
5551 : return I->second;
5552 15168 :
5553 14784 : if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5554 19783 : return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5555 4911 :
5556 2424 : unsigned BitWidth = getTypeSizeInBits(S->getType());
5557 : ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5558 :
5559 : // If the value has known zeros, the maximum value will have those known zeros
5560 : // as well.
5561 : uint32_t TZ = GetMinTrailingZeros(S);
5562 72000 : if (TZ != 0) {
5563 72000 : if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5564 : ConservativeResult =
5565 : ConstantRange(APInt::getMinValue(BitWidth),
5566 21037 : APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5567 : else
5568 : ConservativeResult = ConstantRange(
5569 : APInt::getSignedMinValue(BitWidth),
5570 : APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5571 : }
5572 :
5573 18613 : if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5574 1579 : ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5575 154 : for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5576 : X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5577 : return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
5578 18459 : }
5579 :
5580 : if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5581 5989 : ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5582 : for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5583 : X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5584 : return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
5585 : }
5586 :
5587 : if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5588 171 : ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5589 : for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5590 : X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5591 : return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
5592 : }
5593 467 :
5594 : if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5595 : ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5596 : for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5597 : X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5598 5431 : return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
5599 : }
5600 :
5601 : if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5602 : ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5603 1053 : ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5604 : return setRange(UDiv, SignHint,
5605 : ConservativeResult.intersectWith(X.udiv(Y)));
5606 : }
5607 1053 :
5608 1022 : if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5609 1022 : ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5610 1022 : return setRange(ZExt, SignHint,
5611 1022 : ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
5612 1022 : }
5613 1022 :
5614 1022 : if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5615 422 : ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5616 600 : return setRange(SExt, SignHint,
5617 600 : ConservativeResult.intersectWith(X.signExtend(BitWidth)));
5618 600 : }
5619 181 :
5620 : if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5621 : ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5622 : return setRange(Trunc, SignHint,
5623 : ConservativeResult.intersectWith(X.truncate(BitWidth)));
5624 : }
5625 :
5626 1595 : if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5627 : // If there's no unsigned wrap, the value will never be less than its
5628 : // initial value.
5629 : if (AddRec->hasNoUnsignedWrap())
5630 1595 : if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5631 1549 : if (!C->getValue()->isZero())
5632 1549 : ConservativeResult = ConservativeResult.intersectWith(
5633 1549 : ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
5634 1549 :
5635 1549 : // If there's no signed wrap, and all the operands have the same sign or
5636 1549 : // zero, the value won't ever change sign.
5637 1549 : if (AddRec->hasNoSignedWrap()) {
5638 262 : bool AllNonNeg = true;
5639 1287 : bool AllNonPos = true;
5640 1287 : for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5641 1287 : if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5642 250 : if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5643 : }
5644 : if (AllNonNeg)
5645 52 : ConservativeResult = ConservativeResult.intersectWith(
5646 : ConstantRange(APInt(BitWidth, 0),
5647 102 : APInt::getSignedMinValue(BitWidth)));
5648 98 : else if (AllNonPos)
5649 46 : ConservativeResult = ConservativeResult.intersectWith(
5650 46 : ConstantRange(APInt::getSignedMinValue(BitWidth),
5651 46 : APInt(BitWidth, 1)));
5652 46 : }
5653 46 :
5654 46 : // TODO: non-affine addrec
5655 46 : if (AddRec->isAffine()) {
5656 1 : const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
5657 : if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5658 : getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5659 2731 : auto RangeFromAffine = getRangeForAffineAR(
5660 : AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5661 5169 : BitWidth);
5662 4848 : if (!RangeFromAffine.isFullSet())
5663 1748 : ConservativeResult =
5664 1748 : ConservativeResult.intersectWith(RangeFromAffine);
5665 1748 :
5666 1748 : auto RangeFromFactoring = getRangeViaFactoring(
5667 1748 : AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5668 1748 : BitWidth);
5669 1748 : if (!RangeFromFactoring.isFullSet())
5670 54 : ConservativeResult =
5671 : ConservativeResult.intersectWith(RangeFromFactoring);
5672 : }
5673 : }
5674 :
5675 : return setRange(AddRec, SignHint, std::move(ConservativeResult));
5676 : }
5677 4261 :
5678 : if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5679 : // Check if the IR explicitly contains !range metadata.
5680 : Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5681 : if (MDRange.hasValue())
5682 191606 : ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
5683 :
5684 191606 : // Split here to avoid paying the compile-time cost of calling both
5685 0 : // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5686 : // if needed.
5687 : const DataLayout &DL = getDataLayout();
5688 533704 : if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5689 342098 : // For a SCEVUnknown, ask ValueTracking.
5690 191606 : KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5691 : if (Known.One != ~Known.Zero + 1)
5692 : ConservativeResult =
5693 602449 : ConservativeResult.intersectWith(ConstantRange(Known.One,
5694 : ~Known.Zero + 1));
5695 108988 : } else {
5696 : assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5697 : "generalize as needed!");
5698 3860 : unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5699 7720 : if (NS > 1)
5700 : ConservativeResult = ConservativeResult.intersectWith(
5701 : ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5702 20330 : APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
5703 20330 : }
5704 0 :
5705 20330 : // A range of Phi is a subset of union of all ranges of its input.
5706 : if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5707 : // Make sure that we do not run over cycled Phis.
5708 : if (PendingPhiRanges.insert(Phi).second) {
5709 10987 : ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5710 10987 : for (auto &Op : Phi->operands()) {
5711 0 : auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5712 10987 : RangeFromOps = RangeFromOps.unionWith(OpRange);
5713 : // No point to continue if we already have a full set.
5714 : if (RangeFromOps.isFullSet())
5715 : break;
5716 : }
5717 206220 : ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
5718 164445 : bool Erased = PendingPhiRanges.erase(Phi);
5719 162862 : assert(Erased && "Failed to erase Phi properly?");
5720 : (void) Erased;
5721 : }
5722 : }
5723 :
5724 : return setRange(U, SignHint, std::move(ConservativeResult));
5725 117434 : }
5726 58717 :
5727 58717 : return setRange(S, SignHint, std::move(ConservativeResult));
5728 125732 : }
5729 67015 :
5730 136866 : // Given a StartRange, Step and MaxBECount for an expression compute a range of
5731 : // values that the expression can take. Initially, the expression has a value
5732 : // from StartRange and then is changed by Step up to MaxBECount times. Signed
5733 : // argument defines if we treat Step as signed or unsigned.
5734 : static ConstantRange getRangeForAffineARHelper(APInt Step,
5735 : const ConstantRange &StartRange,
5736 278782 : const APInt &MaxBECount,
5737 219406 : unsigned BitWidth, bool Signed) {
5738 220023 : // If either Step or MaxBECount is 0, then the expression won't change, and we
5739 : // just need to return the initial range.
5740 : if (Step == 0 || MaxBECount == 0)
5741 : return StartRange;
5742 :
5743 : // If we don't know anything about the initial value (i.e. StartRange is
5744 4622 : // FullRange), then we don't know anything about the final range either.
5745 3443 : // Return FullRange.
5746 3388 : if (StartRange.isFullSet())
5747 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5748 :
5749 : // If Step is signed and negative, then we use its absolute value, but we also
5750 : // note that we're moving in the opposite direction.
5751 : bool Descending = Signed && Step.isNegative();
5752 1906 :
5753 1028 : if (Signed)
5754 225 : // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5755 : // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5756 : // This equations hold true due to the well-defined wrap-around behavior of
5757 : // APInt.
5758 144185 : Step = Step.abs();
5759 :
5760 288370 : // Check if Offset is more than full span of BitWidth. If it is, the
5761 : // expression is guaranteed to overflow.
5762 : if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5763 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5764 :
5765 : // Offset is by how much the expression can change. Checks above guarantee no
5766 : // overflow here.
5767 : APInt Offset = Step * MaxBECount;
5768 1507251 :
5769 1507251 : // Minimum value of the final range will match the minimal value of StartRange
5770 1507251 : // if the expression is increasing and will be decreased by Offset otherwise.
5771 904802 : // Maximum value of the final range will match the maximal value of StartRange
5772 : // if the expression is decreasing and will be increased by Offset otherwise.
5773 602449 : APInt StartLower = StartRange.getLower();
5774 602449 : APInt StartUpper = StartRange.getUpper() - 1;
5775 : APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5776 602449 : : (StartUpper + std::move(Offset));
5777 :
5778 : // It's possible that the new minimum/maximum value will fall into the initial
5779 : // range (due to wrap around). This means that the expression can take any
5780 288023 : // value in this bitwidth, and we have to return full range.
5781 : if (StartRange.contains(MovedBoundary))
5782 69218 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5783 12270 :
5784 : APInt NewLower =
5785 : Descending ? std::move(MovedBoundary) : std::move(StartLower);
5786 : APInt NewUpper =
5787 : Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5788 : NewUpper += 1;
5789 :
5790 : // If we end up with full range, return a proper full range.
5791 : if (NewLower == NewUpper)
5792 11108401 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5793 :
5794 11108401 : // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5795 : return ConstantRange(std::move(NewLower), std::move(NewUpper));
5796 : }
5797 :
5798 : ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5799 11108401 : const SCEV *Step,
5800 11108401 : const SCEV *MaxBECount,
5801 9645488 : unsigned BitWidth) {
5802 : assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5803 : getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5804 534337 : "Precondition!");
5805 :
5806 928576 : MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5807 1857152 : APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5808 :
5809 : // First, consider step signed.
5810 : ConstantRange StartSRange = getSignedRange(Start);
5811 928576 : ConstantRange StepSRange = getSignedRange(Step);
5812 928576 :
5813 253778 : // If Step can be both positive and negative, we need to find ranges for the
5814 : // maximum absolute step values in both directions and union them.
5815 244488 : ConstantRange SR =
5816 372662 : getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5817 : MaxBECountValue, BitWidth, /* Signed = */ true);
5818 263068 : SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5819 263068 : StartSRange, MaxBECountValue,
5820 401114 : BitWidth, /* Signed = */ true));
5821 :
5822 : // Next, consider step unsigned.
5823 : ConstantRange UR = getRangeForAffineARHelper(
5824 349994 : getUnsignedRangeMax(Step), getUnsignedRange(Start),
5825 933355 : MaxBECountValue, BitWidth, /* Signed = */ false);
5826 1516716 :
5827 174997 : // Finally, intersect signed and unsigned ranges.
5828 : return SR.intersectWith(UR);
5829 : }
5830 :
5831 222598 : ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5832 243761 : const SCEV *Step,
5833 264924 : const SCEV *MaxBECount,
5834 111299 : unsigned BitWidth) {
5835 : // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5836 : // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5837 :
5838 9244 : struct SelectPattern {
5839 10088 : Value *Condition = nullptr;
5840 10932 : APInt TrueValue;
5841 4622 : APInt FalseValue;
5842 :
5843 : explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5844 : const SCEV *S) {
5845 3812 : Optional<unsigned> CastOp;
5846 3868 : APInt Offset(BitWidth, 0);
5847 3924 :
5848 1906 : assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5849 : "Should be!");
5850 :
5851 : // Peel off a constant offset:
5852 38108 : if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5853 19054 : // In the future we could consider being smarter here and handle
5854 : // {Start+Step,+,Step} too.
5855 19054 : if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5856 : return;
5857 :
5858 : Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5859 39816 : S = SA->getOperand(1);
5860 : }
5861 39816 :
5862 : // Peel off a cast operation
5863 : if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5864 : CastOp = SCast->getSCEVType();
5865 21489 : S = SCast->getOperand();
5866 : }
5867 21489 :
5868 : using namespace llvm::PatternMatch;
5869 :
5870 : auto *SU = dyn_cast<SCEVUnknown>(S);
5871 7359 : const APInt *TrueVal, *FalseVal;
5872 : if (!SU ||
5873 7359 : !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5874 : m_APInt(FalseVal)))) {
5875 : Condition = nullptr;
5876 : return;
5877 : }
5878 :
5879 260011 : TrueValue = *TrueVal;
5880 82735 : FalseValue = *FalseVal;
5881 135626 :
5882 40432 : // Re-apply the cast we peeled off earlier
5883 60648 : if (CastOp.hasValue())
5884 : switch (*CastOp) {
5885 : default:
5886 : llvm_unreachable("Unknown SCEV cast type!");
5887 260011 :
5888 : case scTruncate:
5889 : TrueValue = TrueValue.trunc(BitWidth);
5890 220815 : FalseValue = FalseValue.trunc(BitWidth);
5891 294420 : break;
5892 294420 : case scZeroExtend:
5893 : TrueValue = TrueValue.zext(BitWidth);
5894 73605 : FalseValue = FalseValue.zext(BitWidth);
5895 116852 : break;
5896 116852 : case scSignExtend:
5897 175278 : TrueValue = TrueValue.sext(BitWidth);
5898 15179 : FalseValue = FalseValue.sext(BitWidth);
5899 810 : break;
5900 810 : }
5901 810 :
5902 : // Re-apply the constant offset we peeled off earlier
5903 : TrueValue += Offset;
5904 : FalseValue += Offset;
5905 260011 : }
5906 258061 :
5907 434593 : bool isRecognized() { return Condition != nullptr; }
5908 176532 : };
5909 :
5910 : SelectPattern StartPattern(*this, BitWidth, Start);
5911 345422 : if (!StartPattern.isRecognized())
5912 172711 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5913 :
5914 114932 : SelectPattern StepPattern(*this, BitWidth, Step);
5915 : if (!StepPattern.isRecognized())
5916 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5917 :
5918 345422 : if (StartPattern.Condition != StepPattern.Condition) {
5919 172711 : // We don't handle this case today; but we could, by considering four
5920 : // possibilities below instead of two. I'm not sure if there are cases where
5921 62 : // that will help over what getRange already does, though.
5922 : return ConstantRange(BitWidth, /* isFullSet = */ true);
5923 : }
5924 :
5925 260011 : // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5926 : // construct arbitrary general SCEV expressions here. This function is called
5927 : // from deep in the call stack, and calling getSCEV (on a sext instruction,
5928 288023 : // say) can end up caching a suboptimal value.
5929 :
5930 288023 : // FIXME: without the explicit `this` receiver below, MSVC errors out with
5931 288023 : // C2352 and C2512 (otherwise it isn't needed).
5932 12270 :
5933 : const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5934 : const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5935 : const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5936 : const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5937 288023 :
5938 288023 : ConstantRange TrueRange =
5939 : this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5940 412584 : ConstantRange FalseRange =
5941 137528 : this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5942 :
5943 105244 : return TrueRange.unionWith(FalseRange);
5944 105244 : }
5945 :
5946 : SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5947 : if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5948 300990 : const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5949 150495 :
5950 18724 : // Return early if there are no flags to propagate to the SCEV.
5951 18728 : SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5952 28090 : if (BinOp->hasNoUnsignedWrap())
5953 : Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5954 : if (BinOp->hasNoSignedWrap())
5955 : Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5956 : if (Flags == SCEV::FlagAnyWrap)
5957 : return SCEV::FlagAnyWrap;
5958 47673 :
5959 64046 : return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5960 74775 : }
5961 50040 :
5962 39311 : bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5963 : // Here we check that I is in the header of the innermost loop containing I,
5964 39311 : // since we only deal with instructions in the loop header. The actual loop we
5965 : // need to check later will come from an add recurrence, but getting that
5966 : // requires computing the SCEV of the operands, which can be expensive. This
5967 32023 : // check we can do cheaply to rule out some cases early.
5968 : Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5969 : if (InnermostContainingLoop == nullptr ||
5970 : InnermostContainingLoop->getHeader() != I->getParent())
5971 : return false;
5972 :
5973 : // Only proceed if we can prove that I does not yield poison.
5974 288023 : if (!programUndefinedIfFullPoison(I))
5975 : return false;
5976 :
5977 0 : // At this point we know that if I is executed, then it does not wrap
5978 : // according to at least one of NSW or NUW. If I is not executed, then we do
5979 : // not know if the calculation that I represents would wrap. Multiple
5980 : // instructions can map to the same SCEV. If we apply NSW or NUW from I to
5981 : // the SCEV, we must guarantee no wrapping for that SCEV also when it is
5982 : // derived from other instructions that map to the same SCEV. We cannot make
5983 : // that guarantee for cases where I is not executed. So we need to find the
5984 518505 : // loop that I is considered in relation to and prove that I is executed for
5985 : // every iteration of that loop. That implies that the value that I
5986 : // calculates does not wrap anywhere in the loop, so then we can apply the
5987 : // flags to the SCEV.
5988 : //
5989 : // We check isLoopInvariant to disambiguate in case we are adding recurrences
5990 518505 : // from different loops, so that we know which loop to prove that I is
5991 12208 : // executed in.
5992 : for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
5993 : // I could be an extractvalue from a call to an overflow intrinsic.
5994 : // TODO: We can do better here in some cases.
5995 : if (!isSCEVable(I->getOperand(OpIndex)->getType()))
5996 506297 : return false;
5997 106016 : const SCEV *Op = getSCEV(I->getOperand(OpIndex));
5998 : if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
5999 : bool AllOtherOpsLoopInvariant = true;
6000 : for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6001 409127 : ++OtherOpIndex) {
6002 : if (OtherOpIndex != OpIndex) {
6003 400281 : const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6004 : if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6005 : AllOtherOpsLoopInvariant = false;
6006 : break;
6007 : }
6008 534212 : }
6009 : }
6010 : if (AllOtherOpsLoopInvariant &&
6011 : isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6012 813831 : return true;
6013 65694 : }
6014 : }
6015 : return false;
6016 : }
6017 334587 :
6018 : bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6019 : // If we know that \c I can never be poison period, then that's enough.
6020 : if (isSCEVExprNeverPoison(I))
6021 : return true;
6022 :
6023 : // For an add recurrence specifically, we assume that infinite loops without
6024 334587 : // side effects are undefined behavior, and then reason as follows:
6025 : //
6026 334587 : // If the add recurrence is poison in any iteration, it is poison on all
6027 : // future iterations (since incrementing poison yields poison). If the result
6028 : // of the add recurrence is fed into the loop latch condition and the loop
6029 : // does not contain any throws or exiting blocks other than the latch, we now
6030 : // have the ability to "choose" whether the backedge is taken or not (by
6031 334587 : // choosing a sufficiently evil value for the poison feeding into the branch)
6032 16124 : // for every iteration including and after the one in which \p I first became
6033 : // poison. There are two possibilities (let's call the iteration in which \p
6034 : // I first became poison as K):
6035 318463 : //
6036 : // 1. In the set of iterations including and after K, the loop body executes
6037 318463 : // no side effects. In this case executing the backege an infinte number
6038 318463 : // of times will yield undefined behavior.
6039 : //
6040 : // 2. In the set of iterations including and after K, the loop body executes
6041 318463 : // at least one side effect. In this case, that specific instance of side
6042 13002 : // effect is control dependent on poison, which also yields undefined
6043 : // behavior.
6044 :
6045 610922 : auto *ExitingBB = L->getExitingBlock();
6046 : auto *LatchBB = L->getLoopLatch();
6047 : if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6048 172835 : return false;
6049 :
6050 : SmallPtrSet<const Instruction *, 16> Pushed;
6051 : SmallVector<const Instruction *, 8> PoisonStack;
6052 :
6053 : // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6054 : // things that are known to be fully poison under that assumption go on the
6055 : // PoisonStack.
6056 172835 : Pushed.insert(I);
6057 : PoisonStack.push_back(I);
6058 :
6059 : bool LatchControlDependentOnPoison = false;
6060 172835 : while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6061 172835 : const Instruction *Poison = PoisonStack.pop_back_val();
6062 :
6063 : for (auto *PoisonUser : Poison->users()) {
6064 : if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6065 : if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6066 172835 : PoisonStack.push_back(cast<Instruction>(PoisonUser));
6067 345670 : } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6068 350231 : assert(BI->isConditional() && "Only possibility!");
6069 : if (BI->getParent() == LatchBB) {
6070 172835 : LatchControlDependentOnPoison = true;
6071 : break;
6072 : }
6073 : }
6074 172835 : }
6075 345670 : }
6076 :
6077 : return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6078 172835 : }
6079 :
6080 : ScalarEvolution::LoopProperties
6081 172711 : ScalarEvolution::getLoopProperties(const Loop *L) {
6082 : using LoopProperties = ScalarEvolution::LoopProperties;
6083 :
6084 : auto Itr = LoopPropertiesCache.find(L);
6085 : if (Itr == LoopPropertiesCache.end()) {
6086 : auto HasSideEffects = [](Instruction *I) {
6087 : if (auto *SI = dyn_cast<StoreInst>(I))
6088 : return !SI->isSimple();
6089 :
6090 : return I->mayHaveSideEffects();
6091 : };
6092 :
6093 0 : LoopProperties LP = {/* HasNoAbnormalExits */ true,
6094 0 : /*HasNoSideEffects*/ true};
6095 :
6096 : for (auto *BB : L->getBlocks())
6097 : for (auto &I : *BB) {
6098 : if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6099 : LP.HasNoAbnormalExits = false;
6100 : if (HasSideEffects(&I))
6101 : LP.HasNoSideEffects = false;
6102 : if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6103 : break; // We're already as pessimistic as we can get.
6104 : }
6105 0 :
6106 0 : auto InsertPair = LoopPropertiesCache.insert({L, LP});
6107 : assert(InsertPair.second && "We just checked!");
6108 0 : Itr = InsertPair.first;
6109 0 : }
6110 :
6111 : return Itr->second;
6112 : }
6113 :
6114 : const SCEV *ScalarEvolution::createSCEV(Value *V) {
6115 0 : if (!isSCEVable(V->getType()))
6116 : return getUnknown(V);
6117 :
6118 : if (Instruction *I = dyn_cast<Instruction>(V)) {
6119 : // Don't attempt to analyze instructions in blocks that aren't
6120 : // reachable. Such instructions don't matter, and they aren't required
6121 : // to obey basic rules for definitions dominating uses which this
6122 0 : // analysis depends on.
6123 0 : if (!DT.isReachableFromEntry(I->getParent()))
6124 : return getUnknown(V);
6125 0 : } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6126 0 : return getConstant(CI);
6127 : else if (isa<ConstantPointerNull>(V))
6128 : return getZero(V->getType());
6129 0 : else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6130 0 : return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6131 : else if (!isa<ConstantExpr>(V))
6132 : return getUnknown(V);
6133 0 :
6134 0 : Operator *U = cast<Operator>(V);
6135 0 : if (auto BO = MatchBinaryOp(U, DT)) {
6136 0 : switch (BO->Opcode) {
6137 : case Instruction::Add: {
6138 0 : // The simple thing to do would be to just call getSCEV on both operands
6139 0 : // and call getAddExpr with the result. However if we're looking at a
6140 0 : // bunch of things all added together, this can be quite inefficient,
6141 0 : // because it leads to N-1 getAddExpr calls for N ultimate operands.
6142 0 : // Instead, gather up all the operands and make a single getAddExpr call.
6143 0 : // LLVM IR canonical form means we need only traverse the left operands.
6144 0 : SmallVector<const SCEV *, 4> AddOps;
6145 0 : do {
6146 0 : if (BO->Op) {
6147 0 : if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6148 0 : AddOps.push_back(OpSCEV);
6149 0 : break;
6150 : }
6151 :
6152 : // If a NUW or NSW flag can be applied to the SCEV for this
6153 0 : // addition, then compute the SCEV for this addition by itself
6154 0 : // with a separate call to getAddExpr. We need to do that
6155 : // instead of pushing the operands of the addition onto AddOps,
6156 : // since the flags are only known to apply to this particular
6157 0 : // addition - they may not apply to other additions that can be
6158 : // formed with operands from AddOps.
6159 : const SCEV *RHS = getSCEV(BO->RHS);
6160 345422 : SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6161 172711 : if (Flags != SCEV::FlagAnyWrap) {
6162 172644 : const SCEV *LHS = getSCEV(BO->LHS);
6163 : if (BO->Opcode == Instruction::Sub)
6164 134 : AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6165 67 : else
6166 5 : AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6167 : break;
6168 62 : }
6169 : }
6170 :
6171 : if (BO->Opcode == Instruction::Sub)
6172 0 : AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6173 : else
6174 : AddOps.push_back(getSCEV(BO->RHS));
6175 :
6176 : auto NewBO = MatchBinaryOp(BO->LHS, DT);
6177 : if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6178 : NewBO->Opcode != Instruction::Sub)) {
6179 : AddOps.push_back(getSCEV(BO->LHS));
6180 : break;
6181 : }
6182 : BO = NewBO;
6183 62 : } while (true);
6184 62 :
6185 62 : return getAddExpr(AddOps);
6186 62 : }
6187 :
6188 : case Instruction::Mul: {
6189 124 : SmallVector<const SCEV *, 4> MulOps;
6190 : do {
6191 124 : if (BO->Op) {
6192 : if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6193 62 : MulOps.push_back(OpSCEV);
6194 : break;
6195 : }
6196 95879 :
6197 95879 : SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6198 : if (Flags != SCEV::FlagAnyWrap) {
6199 : MulOps.push_back(
6200 : getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6201 : break;
6202 95876 : }
6203 : }
6204 95876 :
6205 : MulOps.push_back(getSCEV(BO->RHS));
6206 95876 : auto NewBO = MatchBinaryOp(BO->LHS, DT);
6207 : if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6208 : MulOps.push_back(getSCEV(BO->LHS));
6209 49070 : break;
6210 : }
6211 : BO = NewBO;
6212 98983 : } while (true);
6213 :
6214 : return getMulExpr(MulOps);
6215 : }
6216 : case Instruction::UDiv:
6217 : return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6218 98983 : case Instruction::URem:
6219 94818 : return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6220 94818 : case Instruction::Sub: {
6221 44252 : SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6222 : if (BO->Op)
6223 : Flags = getNoWrapFlagsFromUB(BO->Op);
6224 54731 : return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6225 : }
6226 : case Instruction::And:
6227 : // For an expression like x&255 that merely masks off the high bits,
6228 : // use zext(trunc(x)) as the SCEV expression.
6229 : if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6230 : if (CI->isZero())
6231 : return getSCEV(BO->RHS);
6232 : if (CI->isMinusOne())
6233 : return getSCEV(BO->LHS);
6234 : const APInt &A = CI->getValue();
6235 :
6236 : // Instcombine's ShrinkDemandedConstant may strip bits out of
6237 : // constants, obscuring what would otherwise be a low-bits mask.
6238 : // Use computeKnownBits to compute what ShrinkDemandedConstant
6239 : // knew about to reconstruct a low-bits mask value.
6240 : unsigned LZ = A.countLeadingZeros();
6241 : unsigned TZ = A.countTrailingZeros();
6242 21317 : unsigned BitWidth = A.getBitWidth();
6243 : KnownBits Known(BitWidth);
6244 : computeKnownBits(BO->LHS, Known, getDataLayout(),
6245 32928 : 0, &AC, nullptr, &DT);
6246 :
6247 16463 : APInt EffectiveMask =
6248 : APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6249 : if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6250 21316 : const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6251 : const SCEV *LHS = getSCEV(BO->LHS);
6252 14383 : const SCEV *ShiftedLHS = nullptr;
6253 7228 : if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6254 7228 : if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6255 : // For an expression like (x * 8) & 8, simplify the multiply.
6256 : unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6257 : unsigned GCD = std::min(MulZeros, TZ);
6258 : APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6259 : SmallVector<const SCEV*, 4> MulOps;
6260 14161 : MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6261 6933 : MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6262 : auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6263 : ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6264 : }
6265 : }
6266 : if (!ShiftedLHS)
6267 : ShiftedLHS = getUDivExpr(LHS, MulCount);
6268 49913 : return getMulExpr(
6269 : getZeroExtendExpr(
6270 49913 : getTruncateExpr(ShiftedLHS,
6271 : IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6272 : BO->LHS->getType()),
6273 : MulCount);
6274 : }
6275 : }
6276 : break;
6277 :
6278 : case Instruction::Or:
6279 : // If the RHS of the Or is a constant, we may have something like:
6280 : // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6281 : // optimizations will transparently handle this case.
6282 : //
6283 : // In order for this transformation to be safe, the LHS must be of the
6284 : // form X*(2^n) and the Or constant must be less than 2^n.
6285 : if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6286 : const SCEV *LHS = getSCEV(BO->LHS);
6287 : const APInt &CIVal = CI->getValue();
6288 : if (GetMinTrailingZeros(LHS) >=
6289 : (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6290 : // Build a plain add SCEV.
6291 : const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6292 : // If the LHS of the add was an addrec and it has no-wrap flags,
6293 : // transfer the no-wrap flags, since an or won't introduce a wrap.
6294 : if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6295 48405 : const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6296 48405 : const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6297 48405 : OldAR->getNoWrapFlags());
6298 : }
6299 : return S;
6300 : }
6301 : }
6302 : break;
6303 :
6304 : case Instruction::Xor:
6305 : if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6306 31644 : // If the RHS of xor is -1, then this is a not operation.
6307 31644 : if (CI->isMinusOne())
6308 : return getNotSCEV(getSCEV(BO->LHS));
6309 :
6310 89144 : // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6311 : // This is a variant of the check for xor with -1, and it handles
6312 : // the case where instcombine has trimmed non-demanded bits out
6313 119327 : // of an xor with -1.
6314 84423 : if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6315 25887 : if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6316 25883 : if (LBO->getOpcode() == Instruction::And &&
6317 : LCI->getValue() == CI->getValue())
6318 : if (const SCEVZeroExtendExpr *Z =
6319 22669 : dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6320 : Type *UTy = BO->LHS->getType();
6321 : const SCEV *Z0 = Z->getOperand();
6322 : Type *Z0Ty = Z0->getType();
6323 : unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6324 :
6325 : // If C is a low-bits mask, the zero extend is serving to
6326 : // mask off the high bits. Complement the operand and
6327 54240 : // re-apply the zext.
6328 : if (CI->getValue().isMask(Z0TySize))
6329 : return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6330 :
6331 24391 : // If C is a single bit, it may be in the sign-bit position
6332 : // before the zero-extend. In this case, represent the xor
6333 : // using an add, which is equivalent, and re-apply the zext.
6334 24391 : APInt Trunc = CI->getValue().trunc(Z0TySize);
6335 24391 : if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6336 : Trunc.isSignMask())
6337 : return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6338 : UTy);
6339 : }
6340 : }
6341 : break;
6342 :
6343 : case Instruction::Shl:
6344 : // Turn shift left of a constant amount into a multiply.
6345 : if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6346 39237 : uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6347 293854 :
6348 273480 : // If the shift count is not less than the bitwidth, the result of
6349 : // the shift is undefined. Don't try to analyze it, because the
6350 273480 : // resolution chosen here may differ from the resolution chosen in
6351 : // other parts of the compiler.
6352 273480 : if (SA->getValue().uge(BitWidth))
6353 : break;
6354 :
6355 : // It is currently not resolved how to interpret NSW for left
6356 12435 : // shift by BitWidth - 1, so we avoid applying flags in that
6357 : // case. Remove this check (or this comment) once the situation
6358 12435 : // is resolved. See
6359 : // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6360 : // and http://reviews.llvm.org/D8890 .
6361 24391 : auto Flags = SCEV::FlagAnyWrap;
6362 : if (BO->Op && SA->getValue().ult(BitWidth - 1))
6363 : Flags = getNoWrapFlagsFromUB(BO->Op);
6364 701261 :
6365 701261 : Constant *X = ConstantInt::get(
6366 0 : getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6367 : return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6368 : }
6369 : break;
6370 :
6371 : case Instruction::AShr: {
6372 : // AShr X, C, where C is a constant.
6373 386475 : ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6374 1 : if (!CI)
6375 : break;
6376 127730 :
6377 187056 : Type *OuterTy = BO->LHS->getType();
6378 1193 : uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6379 : // If the shift count is not less than the bitwidth, the result of
6380 0 : // the shift is undefined. Don't try to analyze it, because the
6381 185863 : // resolution chosen here may differ from the resolution chosen in
6382 86986 : // other parts of the compiler.
6383 : if (CI->getValue().uge(BitWidth))
6384 : break;
6385 485351 :
6386 96232 : if (CI->isZero())
6387 : return getSCEV(BO->LHS); // shift by zero --> noop
6388 :
6389 : uint64_t AShrAmt = CI->getZExtValue();
6390 : Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6391 :
6392 : Operator *L = dyn_cast<Operator>(BO->LHS);
6393 : if (L && L->getOpcode() == Instruction::Shl) {
6394 : // X = Shl A, n
6395 : // Y = AShr X, m
6396 81350 : // Both n and m are constant.
6397 81254 :
6398 6329 : const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6399 6329 : if (L->getOperand(1) == BO->RHS)
6400 : // For a two-shift sext-inreg, i.e. n = m,
6401 : // use sext(trunc(x)) as the SCEV expression.
6402 : return getSignExtendExpr(
6403 : getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6404 :
6405 : ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6406 : if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6407 : uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6408 : if (ShlAmt > AShrAmt) {
6409 74925 : // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6410 74925 : // expression. We already checked that ShlAmt < BitWidth, so
6411 74925 : // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6412 4692 : // ShlAmt - AShrAmt < Amt.
6413 4692 : APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6414 2 : ShlAmt - AShrAmt);
6415 : return getSignExtendExpr(
6416 4690 : getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6417 : getConstant(Mul)), OuterTy);
6418 : }
6419 : }
6420 : }
6421 70329 : break;
6422 346 : }
6423 : }
6424 69983 : }
6425 :
6426 70329 : switch (U->getOpcode()) {
6427 70329 : case Instruction::Trunc:
6428 : return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6429 51243 :
6430 : case Instruction::ZExt:
6431 : return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6432 :
6433 : case Instruction::SExt:
6434 : if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6435 62264 : // The NSW flag of a subtract does not always survive the conversion to
6436 : // A + (-1)*B. By pushing sign extension onto its operands we are much
6437 : // more likely to preserve NSW and allow later AddRec optimisations.
6438 : //
6439 : // NOTE: This is effectively duplicating this logic from getSignExtend:
6440 : // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6441 10169 : // but by that point the NSW information has potentially been lost.
6442 10163 : if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6443 407 : Type *Ty = U->getType();
6444 407 : auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6445 : auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6446 : return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6447 9756 : }
6448 9756 : }
6449 133 : return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6450 133 :
6451 133 : case Instruction::BitCast:
6452 : // BitCasts are no-op casts so we just eliminate the cast.
6453 : if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6454 : return getSCEV(U->getOperand(0));
6455 9629 : break;
6456 9629 :
6457 9629 : // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6458 8812 : // lead to pointer expressions which cannot safely be expanded to GEPs,
6459 : // because ScalarEvolution doesn't respect the GEP aliasing rules when
6460 : // simplifying integer expressions.
6461 :
6462 : case Instruction::GetElementPtr:
6463 : return createNodeForGEP(cast<GEPOperator>(U));
6464 9352 :
6465 : case Instruction::PHI:
6466 : return createNodeForPHI(cast<PHINode>(U));
6467 4934 :
6468 : case Instruction::Select:
6469 476 : // U can also be a select constant expr, which let fall through. Since
6470 8810 : // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6471 : // constant expressions cannot have instructions as operands, we'd have
6472 8810 : // returned getUnknown for a select constant expressions anyway.
6473 8777 : if (isa<Instruction>(U))
6474 8810 : return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6475 : U->getOperand(1), U->getOperand(2));
6476 : break;
6477 :
6478 : case Instruction::Call:
6479 3108 : case Instruction::Invoke:
6480 2777 : if (Value *RV = CallSite(U).getReturnedArgOperand())
6481 2708 : return getSCEV(RV);
6482 2775 : break;
6483 0 : }
6484 :
6485 : return getUnknown(V);
6486 : }
6487 :
6488 : //===----------------------------------------------------------------------===//
6489 : // Iteration Count Computation Code
6490 2775 : //
6491 2775 :
6492 : static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6493 2844 : if (!ExitCount)
6494 2775 : return 0;
6495 2775 :
6496 : ConstantInt *ExitConst = ExitCount->getValue();
6497 :
6498 2775 : // Guard against huge trip counts.
6499 22269 : if (ExitConst->getValue().getActiveBits() > 32)
6500 2706 : return 0;
6501 2706 :
6502 : // In case of integer overflow, this returns 0, which is correct.
6503 : return ((unsigned)ExitConst->getZExtValue()) + 1;
6504 67 : }
6505 :
6506 66 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6507 66 : if (BasicBlock *ExitingBB = L->getExitingBlock())
6508 66 : return getSmallConstantTripCount(L, ExitingBB);
6509 :
6510 66 : // No trip count information for multiple exits.
6511 132 : return 0;
6512 132 : }
6513 66 :
6514 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6515 : BasicBlock *ExitingBlock) {
6516 66 : assert(ExitingBlock && "Must pass a non-null exiting block!");
6517 2640 : assert(L->isLoopExiting(ExitingBlock) &&
6518 2706 : "Exiting block must actually branch out of the loop!");
6519 : const SCEVConstant *ExitCount =
6520 : dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6521 2706 : return getConstantTripCount(ExitCount);
6522 2706 : }
6523 :
6524 : unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6525 : const auto *MaxExitCount =
6526 : dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
6527 : return getConstantTripCount(MaxExitCount);
6528 : }
6529 :
6530 : unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6531 : if (BasicBlock *ExitingBB = L->getExitingBlock())
6532 : return getSmallConstantTripMultiple(L, ExitingBB);
6533 :
6534 : // No trip multiple information for multiple exits.
6535 1570 : return 0;
6536 1041 : }
6537 :
6538 1041 : /// Returns the largest constant divisor of the trip count of this loop as a
6539 1041 : /// normal unsigned value, if possible. This means that the actual trip count is
6540 : /// always a multiple of the returned value (don't forget the trip count could
6541 1005 : /// very well be zero as well!).
6542 : ///
6543 : /// Returns 1 if the trip count is unknown or not guaranteed to be the
6544 : /// multiple of a constant (which is also the case if the trip count is simply
6545 : /// constant, use getSmallConstantTripCount for that case), Will also return 1
6546 680 : /// if the trip count is very large (>= 2^32).
6547 : ///
6548 : /// As explained in the comments for getSmallConstantTripCount, this assumes
6549 1005 : /// that control exits the loop via ExitingBlock.
6550 : unsigned
6551 : ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6552 : BasicBlock *ExitingBlock) {
6553 : assert(ExitingBlock && "Must pass a non-null exiting block!");
6554 : assert(L->isLoopExiting(ExitingBlock) &&
6555 875 : "Exiting block must actually branch out of the loop!");
6556 : const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6557 382 : if (ExitCount == getCouldNotCompute())
6558 338 : return 1;
6559 :
6560 : // Get the trip count from the BE count by adding 1.
6561 : const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6562 :
6563 : const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6564 44 : if (!TC)
6565 : // Attempt to factor more general cases. Returns the greatest power of
6566 10 : // two divisor. If overflow happens, the trip count expression is still
6567 : // divisible by the greatest power of 2 divisor returned.
6568 : return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6569 4 :
6570 2 : ConstantInt *Result = TC->getValue();
6571 2 :
6572 2 : // Guard against huge trip counts (this requires checking
6573 2 : // for zero to handle the case where the trip count == -1 and the
6574 : // addition wraps).
6575 : if (!Result || Result->getValue().getActiveBits() > 32 ||
6576 : Result->getValue().getActiveBits() == 0)
6577 : return 1;
6578 2 :
6579 2 : return (unsigned)Result->getZExtValue();
6580 : }
6581 :
6582 : /// Get the expression for the number of loop iterations for which this loop is
6583 : /// guaranteed not to exit via ExitingBlock. Otherwise return
6584 0 : /// SCEVCouldNotCompute.
6585 0 : const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6586 : BasicBlock *ExitingBlock) {
6587 0 : return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6588 : }
6589 :
6590 : const SCEV *
6591 : ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6592 : SCEVUnionPredicate &Preds) {
6593 : return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6594 : }
6595 2789 :
6596 : const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6597 : return getBackedgeTakenInfo(L).getExact(L, this);
6598 : }
6599 :
6600 : /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6601 : /// known never to be less than the actual backedge taken count.
6602 4852 : const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
6603 : return getBackedgeTakenInfo(L).getMax(this);
6604 : }
6605 :
6606 : bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6607 : return getBackedgeTakenInfo(L).isMaxOrZero(this);
6608 : }
6609 :
6610 : /// Push PHI nodes in the header of the given loop onto the given Worklist.
6611 : static void
6612 2422 : PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6613 2421 : BasicBlock *Header = L->getHeader();
6614 :
6615 2422 : // Push all Loop-header PHIs onto the Worklist stack.
6616 2422 : for (PHINode &PN : Header->phis())
6617 2422 : Worklist.push_back(&PN);
6618 : }
6619 :
6620 : const ScalarEvolution::BackedgeTakenInfo &
6621 : ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6622 : auto &BTI = getBackedgeTakenInfo(L);
6623 1755 : if (BTI.hasFullInfo())
6624 : return BTI;
6625 :
6626 : auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6627 1751 :
6628 1751 : if (!Pair.second)
6629 : return Pair.first->second;
6630 :
6631 : BackedgeTakenInfo Result =
6632 : computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6633 1751 :
6634 : return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6635 : }
6636 1747 :
6637 1 : const ScalarEvolution::BackedgeTakenInfo &
6638 : ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6639 : // Initially insert an invalid entry for this loop. If the insertion
6640 1746 : // succeeds, proceed to actually compute a backedge-taken count and
6641 : // update the value. The temporary CouldNotCompute value tells SCEV
6642 1746 : // code elsewhere that it shouldn't attempt to request a new
6643 1674 : // backedge-taken count, which could result in infinite recursion.
6644 : std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6645 : BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6646 : if (!Pair.second)
6647 : return Pair.first->second;
6648 842 :
6649 421 : // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6650 : // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6651 : // must be cleared in this scope.
6652 395 : BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6653 395 :
6654 : // In product build, there are no usage of statistic.
6655 : (void)NumTripCountsComputed;
6656 26 : (void)NumTripCountsNotComputed;
6657 : #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6658 26 : const SCEV *BEExact = Result.getExact(L, this);
6659 : if (BEExact != getCouldNotCompute()) {
6660 : assert(isLoopInvariant(BEExact, L) &&
6661 : isLoopInvariant(Result.getMax(this), L) &&
6662 : "Computed backedge-taken count isn't loop invariant for loop!");
6663 : ++NumTripCountsComputed;
6664 2 : }
6665 2 : else if (Result.getMax(this) == getCouldNotCompute() &&
6666 : isa<PHINode>(L->getHeader()->begin())) {
6667 : // Only count loops that have phi nodes as not being computable.
6668 : ++NumTripCountsNotComputed;
6669 : }
6670 : #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6671 :
6672 : // Now that we know more about the trip count for this loop, forget any
6673 : // existing SCEV values for PHI nodes in this loop since they are only
6674 : // conservative estimates made without the benefit of trip count
6675 : // information. This is similar to the code in forgetLoop, except that
6676 392642 : // it handles SCEVUnknown PHI nodes specially.
6677 5362 : if (Result.hasAnyInfo()) {
6678 10724 : SmallVector<Instruction *, 16> Worklist;
6679 : PushLoopPHIs(L, Worklist);
6680 9320 :
6681 18640 : SmallPtrSet<Instruction *, 8> Discovered;
6682 : while (!Worklist.empty()) {
6683 11154 : Instruction *I = Worklist.pop_back_val();
6684 22308 :
6685 : ValueExprMapType::iterator It =
6686 : ValueExprMap.find_as(static_cast<Value *>(I));
6687 : if (It != ValueExprMap.end()) {
6688 : const SCEV *Old = It->second;
6689 :
6690 : // SCEVUnknown for a PHI either means that it has an unrecognized
6691 : // structure, or it's a PHI that's in the progress of being computed
6692 737 : // by createNodeForPHI. In the former case, additional loop trip
6693 18 : // count information isn't going to change anything. In the later
6694 18 : // case, createNodeForPHI will perform the necessary updates on its
6695 18 : // own when it gets to that point.
6696 18 : if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6697 : eraseValueFromMap(It->first);
6698 18 : forgetMemoizedResults(Old);
6699 22272 : }
6700 : if (PHINode *PN = dyn_cast<PHINode>(I))
6701 16020 : ConstantEvolutionLoopExitValue.erase(PN);
6702 : }
6703 32040 :
6704 15841 : // Since we don't need to invalidate anything for correctness and we're
6705 : // only invalidating to make SCEV's results more precise, we get to stop
6706 : // early to avoid invalidating too much. This is especially important in
6707 : // cases like:
6708 : //
6709 : // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6710 : // loop0:
6711 : // %pn0 = phi
6712 191606 : // ...
6713 191606 : // loop1:
6714 : // %pn1 = phi
6715 72000 : // ...
6716 72000 : //
6717 : // where both loop0 and loop1's backedge taken count uses the SCEV
6718 3567 : // expression for %v. If we don't have the early stop below then in cases
6719 : // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6720 : // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6721 : // count for loop1, effectively nullifying SCEV's trip count cache.
6722 : for (auto *U : I->users())
6723 3567 : if (auto *I = dyn_cast<Instruction>(U)) {
6724 7130 : auto *LoopForUser = LI.getLoopFor(I->getParent());
6725 3565 : if (LoopForUser && L->contains(LoopForUser) &&
6726 : Discovered.insert(I).second)
6727 : Worklist.push_back(I);
6728 11857 : }
6729 : }
6730 11857 : }
6731 11857 :
6732 : // Re-lookup the insert position, since the call to
6733 : // computeBackedgeTakenCount above could result in a
6734 : // recusive call to getBackedgeTakenInfo (on a different
6735 83787 : // loop), which would invalidate the iterator computed
6736 : // earlier.
6737 : return BackedgeTakenCounts.find(L)->second = std::move(Result);
6738 : }
6739 :
6740 : void ScalarEvolution::forgetLoop(const Loop *L) {
6741 : // Drop any stored trip count value.
6742 17501 : auto RemoveLoopFromBackedgeMap =
6743 17501 : [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6744 : auto BTCPos = Map.find(L);
6745 : if (BTCPos != Map.end()) {
6746 6691 : BTCPos->second.clear();
6747 : Map.erase(BTCPos);
6748 : }
6749 6691 : };
6750 :
6751 : SmallVector<const Loop *, 16> LoopWorklist(1, L);
6752 : SmallVector<Instruction *, 32> Worklist;
6753 4476 : SmallPtrSet<Instruction *, 16> Visited;
6754 :
6755 : // Iterate over all the loops and sub-loops to drop SCEV information.
6756 2295 : while (!LoopWorklist.empty()) {
6757 2295 : auto *CurrL = LoopWorklist.pop_back_val();
6758 2230 :
6759 : RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6760 : RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6761 :
6762 : // Drop information about predicated SCEV rewrites for this loop.
6763 : for (auto I = PredicatedSCEVRewrites.begin();
6764 10352 : I != PredicatedSCEVRewrites.end();) {
6765 : std::pair<const SCEV *, const Loop *> Entry = I->first;
6766 : if (Entry.second == CurrL)
6767 : PredicatedSCEVRewrites.erase(I++);
6768 : else
6769 : ++I;
6770 10352 : }
6771 10352 :
6772 : auto LoopUsersItr = LoopUsers.find(CurrL);
6773 : if (LoopUsersItr != LoopUsers.end()) {
6774 7149 : for (auto *S : LoopUsersItr->second)
6775 : forgetMemoizedResults(S);
6776 7149 : LoopUsers.erase(LoopUsersItr);
6777 7149 : }
6778 :
6779 : // Drop information about expressions based on loop-header PHIs.
6780 264 : PushLoopPHIs(CurrL, Worklist);
6781 264 :
6782 254 : while (!Worklist.empty()) {
6783 : Instruction *I = Worklist.pop_back_val();
6784 : if (!Visited.insert(I).second)
6785 : continue;
6786 :
6787 : ValueExprMapType::iterator It =
6788 : ValueExprMap.find_as(static_cast<Value *>(I));
6789 : if (It != ValueExprMap.end()) {
6790 : eraseValueFromMap(It->first);
6791 : forgetMemoizedResults(It->second);
6792 : if (PHINode *PN = dyn_cast<PHINode>(I))
6793 : ConstantEvolutionLoopExitValue.erase(PN);
6794 : }
6795 :
6796 : PushDefUseChildren(I, Worklist);
6797 : }
6798 :
6799 : LoopPropertiesCache.erase(CurrL);
6800 : // Forget all contained loops too, to avoid dangling entries in the
6801 8340 : // ValuesAtScopes map.
6802 : LoopWorklist.append(CurrL->begin(), CurrL->end());
6803 : }
6804 : }
6805 :
6806 8340 : void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6807 8340 : while (Loop *Parent = L->getParentLoop())
6808 : L = Parent;
6809 : forgetLoop(L);
6810 : }
6811 9220 :
6812 : void ScalarEvolution::forgetValue(Value *V) {
6813 : Instruction *I = dyn_cast<Instruction>(V);
6814 : if (!I) return;
6815 :
6816 : // Drop information about expressions based on loop-header PHIs.
6817 : SmallVector<Instruction *, 16> Worklist;
6818 4520 : Worklist.push_back(I);
6819 :
6820 2350 : SmallPtrSet<Instruction *, 8> Visited;
6821 : while (!Worklist.empty()) {
6822 : I = Worklist.pop_back_val();
6823 : if (!Visited.insert(I).second)
6824 : continue;
6825 2350 :
6826 : ValueExprMapType::iterator It =
6827 : ValueExprMap.find_as(static_cast<Value *>(I));
6828 : if (It != ValueExprMap.end()) {
6829 2348 : eraseValueFromMap(It->first);
6830 : forgetMemoizedResults(It->second);
6831 : if (PHINode *PN = dyn_cast<PHINode>(I))
6832 : ConstantEvolutionLoopExitValue.erase(PN);
6833 : }
6834 :
6835 19884 : PushDefUseChildren(I, Worklist);
6836 : }
6837 19884 : }
6838 :
6839 : /// Get the exact loop backedge taken count considering all loop exits. A
6840 : /// computable result can only be returned for loops with all exiting blocks
6841 4774 : /// dominating the latch. howFarToZero assumes that the limit of each loop test
6842 : /// is never skipped. This is a valid assumption as long as the loop exits via
6843 4774 : /// that test. For precise results, it is the caller's responsibility to specify
6844 : /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6845 : const SCEV *
6846 45398 : ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6847 45398 : SCEVUnionPredicate *Preds) const {
6848 : // If any exits were not computable, the loop is not computable.
6849 : if (!isComplete() || ExitNotTaken.empty())
6850 : return SE->getCouldNotCompute();
6851 :
6852 301549 : const BasicBlock *Latch = L->getLoopLatch();
6853 301549 : // All exiting blocks we have collected must dominate the only backedge.
6854 : if (!Latch)
6855 : return SE->getCouldNotCompute();
6856 6840 :
6857 6840 : // All exiting blocks we have gathered dominate loop's latch, so exact trip
6858 : // count is simply a minimum out of all these calculated exit counts.
6859 : SmallVector<const SCEV *, 2> Ops;
6860 : for (auto &ENT : ExitNotTaken) {
6861 : const SCEV *BECount = ENT.ExactNotTaken;
6862 28551 : assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6863 : assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6864 : "We should only have known counts for exiting blocks that dominate "
6865 : "latch!");
6866 101097 :
6867 43995 : Ops.push_back(BECount);
6868 28551 :
6869 : if (Preds && !ENT.hasAlwaysTruePredicate())
6870 : Preds->add(ENT.Predicate.get());
6871 4774 :
6872 4774 : assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6873 4774 : "Predicate should be always true!");
6874 : }
6875 :
6876 2494 : return SE->getUMinFromMismatchedTypes(Ops);
6877 : }
6878 1247 :
6879 12 : /// Get the exact not taken count for this loop exit.
6880 : const SCEV *
6881 : ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6882 1235 : ScalarEvolution *SE) const {
6883 : for (auto &ENT : ExitNotTaken)
6884 1235 : if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6885 : return ENT.ExactNotTaken;
6886 :
6887 : return SE->getCouldNotCompute();
6888 397606 : }
6889 :
6890 : /// getMax - Get the max backedge taken count for the loop.
6891 : const SCEV *
6892 : ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6893 : auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6894 : return !ENT.hasAlwaysTruePredicate();
6895 795212 : };
6896 397606 :
6897 372151 : if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6898 : return SE->getCouldNotCompute();
6899 :
6900 : assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6901 : "No point in having a non-constant max backedge taken count!");
6902 25455 : return getMax();
6903 : }
6904 :
6905 : bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6906 : auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6907 : return !ENT.hasAlwaysTruePredicate();
6908 : };
6909 : return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6910 : }
6911 :
6912 : bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6913 : ScalarEvolution *SE) const {
6914 : if (getMax() && getMax() != SE->getCouldNotCompute() &&
6915 : SE->hasOperand(getMax(), S))
6916 : return true;
6917 :
6918 : for (auto &ENT : ExitNotTaken)
6919 : if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6920 : SE->hasOperand(ENT.ExactNotTaken, S))
6921 : return true;
6922 :
6923 : return false;
6924 : }
6925 :
6926 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6927 : : ExactNotTaken(E), MaxNotTaken(E) {
6928 : assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6929 18350 : isa<SCEVConstant>(MaxNotTaken)) &&
6930 : "No point in having a non-constant max backedge taken count!");
6931 : }
6932 308741 :
6933 : ScalarEvolution::ExitLimit::ExitLimit(
6934 : const SCEV *E, const SCEV *M, bool MaxOrZero,
6935 : ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6936 290391 : : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6937 290391 : assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6938 47476 : !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6939 : "Exact is not allowed to be less precise than Max");
6940 : assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6941 : isa<SCEVConstant>(MaxNotTaken)) &&
6942 : "No point in having a non-constant max backedge taken count!");
6943 : for (auto *PredSet : PredSetList)
6944 : for (auto *P : *PredSet)
6945 : addPredicate(P);
6946 47476 : }
6947 44302 :
6948 44302 : ScalarEvolution::ExitLimit::ExitLimit(
6949 : const SCEV *E, const SCEV *M, bool MaxOrZero,
6950 47476 : const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6951 22664 : : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6952 : assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6953 : isa<SCEVConstant>(MaxNotTaken)) &&
6954 : "No point in having a non-constant max backedge taken count!");
6955 : }
6956 :
6957 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
6958 : bool MaxOrZero)
6959 : : ExitLimit(E, M, MaxOrZero, None) {
6960 : assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6961 : isa<SCEVConstant>(MaxNotTaken)) &&
6962 : "No point in having a non-constant max backedge taken count!");
6963 : }
6964 :
6965 : /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
6966 : /// computable exit into a persistent ExitNotTakenInfo array.
6967 : ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
6968 : SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
6969 : &&ExitCounts,
6970 : bool Complete, const SCEV *MaxCount, bool MaxOrZero)
6971 : : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
6972 669458 : using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
6973 379067 :
6974 379067 : ExitNotTaken.reserve(ExitCounts.size());
6975 737132 : std::transform(
6976 379067 : ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
6977 262528 : [&](const EdgeExitInfo &EEI) {
6978 : BasicBlock *ExitBB = EEI.first;
6979 : const ExitLimit &EL = EEI.second;
6980 : if (EL.Predicates.empty())
6981 : return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
6982 :
6983 : std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
6984 : for (auto *Pred : EL.Predicates)
6985 : Predicate->add(Pred);
6986 :
6987 25455 : return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
6988 : });
6989 : assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
6990 6682 : "No point in having a non-constant max backedge taken count!");
6991 : }
6992 :
6993 : /// Invalidate this result and free the ExitNotTakenInfo array.
6994 : void ScalarEvolution::BackedgeTakenInfo::clear() {
6995 : ExitNotTaken.clear();
6996 : }
6997 :
6998 : /// Compute the number of times the backedge of the specified loop will execute.
6999 : ScalarEvolution::BackedgeTakenInfo
7000 : ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7001 : bool AllowPredicates) {
7002 : SmallVector<BasicBlock *, 8> ExitingBlocks;
7003 : L->getExitingBlocks(ExitingBlocks);
7004 :
7005 : using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7006 16883 :
7007 10201 : SmallVector<EdgeExitInfo, 4> ExitCounts;
7008 : bool CouldComputeBECount = true;
7009 10201 : BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7010 10201 : const SCEV *MustExitMaxBECount = nullptr;
7011 : const SCEV *MayExitMaxBECount = nullptr;
7012 : bool MustExitMaxOrZero = false;
7013 10282 :
7014 10282 : // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7015 : // and compute maxBECount.
7016 81 : // Do a union of all the predicates here.
7017 : for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7018 : BasicBlock *ExitBB = ExitingBlocks[i];
7019 12 : ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7020 :
7021 : assert((AllowPredicates || EL.Predicates.empty()) &&
7022 10201 : "Predicated exit limit when predicates are not allowed!");
7023 10201 :
7024 17601 : // 1. For each exit that can be computed, add an entry to ExitCounts.
7025 15269 : // CouldComputeBECount is true only if all exits can be computed.
7026 : if (EL.ExactNotTaken == getCouldNotCompute())
7027 : // We couldn't compute an exact value for this exit, so
7028 : // we won't be able to compute an exact value for the loop.
7029 : CouldComputeBECount = false;
7030 10201 : else
7031 : ExitCounts.emplace_back(ExitBB, EL);
7032 212233 :
7033 : // 2. Derive the loop's MaxBECount from each exit's max number of
7034 202032 : // non-exiting iterations. Partition the loop exits into two kinds:
7035 43348 : // LoopMustExits and LoopMayExits.
7036 : //
7037 : // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7038 158684 : // is a LoopMayExit. If any computable LoopMustExit is found, then
7039 158684 : // MaxBECount is the minimum EL.MaxNotTaken of computable
7040 7145 : // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7041 7145 : // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7042 7145 : // computable EL.MaxNotTaken.
7043 2436 : if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7044 : DT.dominates(ExitBB, Latch)) {
7045 : if (!MustExitMaxBECount) {
7046 158684 : MustExitMaxBECount = EL.MaxNotTaken;
7047 : MustExitMaxOrZero = EL.MaxOrZero;
7048 : } else {
7049 10201 : MustExitMaxBECount =
7050 : getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7051 : }
7052 20402 : } else if (MayExitMaxBECount != getCouldNotCompute()) {
7053 : if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7054 6682 : MayExitMaxBECount = EL.MaxNotTaken;
7055 : else {
7056 4864 : MayExitMaxBECount =
7057 5760 : getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7058 : }
7059 4864 : }
7060 4864 : }
7061 : const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7062 12360 : (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7063 12360 : // The loop backedge will be taken the maximum or zero times if there's
7064 12360 : // a single exit that must be taken the maximum or zero times.
7065 : bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7066 : return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7067 : MaxBECount, MaxOrZero);
7068 12360 : }
7069 :
7070 : ScalarEvolution::ExitLimit
7071 177523 : ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7072 165163 : bool AllowPredicates) {
7073 165163 : assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7074 22974 : // If our exiting block does not dominate the latch, then its connection with
7075 : // loop's exit limit may be far from trivial.
7076 : const BasicBlock *Latch = L->getLoopLatch();
7077 142189 : if (!Latch || !DT.dominates(ExitingBlock, Latch))
7078 142189 : return getCouldNotCompute();
7079 20209 :
7080 20209 : bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7081 35652 : Instruction *Term = ExitingBlock->getTerminator();
7082 4766 : if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7083 : assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7084 : bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7085 142189 : assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7086 : "It should have one successor in loop and one exit block!");
7087 : // Proceed to the next level to examine the exit condition expression.
7088 : return computeExitLimitFromCond(
7089 : L, BI->getCondition(), ExitIfTrue,
7090 : /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7091 : }
7092 :
7093 : if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7094 : // For switch, make sure that there is a single exit from the loop.
7095 : BasicBlock *Exit = nullptr;
7096 50172 : for (auto *SBB : successors(ExitingBlock))
7097 : if (!L->contains(SBB)) {
7098 : if (Exit) // Multiple exit successors.
7099 50172 : return getCouldNotCompute();
7100 16812 : Exit = SBB;
7101 : }
7102 33360 : assert(Exit && "Exiting block must have at least one exit");
7103 : return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7104 33360 : /*ControlsExit=*/IsOnlyExit);
7105 0 : }
7106 :
7107 : return getCouldNotCompute();
7108 : }
7109 :
7110 67059 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7111 33699 : const Loop *L, Value *ExitCond, bool ExitIfTrue,
7112 : bool ControlsExit, bool AllowPredicates) {
7113 : ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7114 : return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7115 : ControlsExit, AllowPredicates);
7116 : }
7117 33699 :
7118 : Optional<ScalarEvolution::ExitLimit>
7119 33699 : ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7120 24 : bool ExitIfTrue, bool ControlsExit,
7121 : bool AllowPredicates) {
7122 : (void)this->L;
7123 : (void)this->ExitIfTrue;
7124 : (void)this->AllowPredicates;
7125 :
7126 33360 : assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7127 : this->AllowPredicates == AllowPredicates &&
7128 : "Variance in assumed invariant key components!");
7129 : auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7130 : if (Itr == TripCountMap.end())
7131 39045 : return None;
7132 : return Itr->second;
7133 41918 : }
7134 30980 :
7135 28107 : void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7136 : bool ExitIfTrue,
7137 10938 : bool ControlsExit,
7138 : bool AllowPredicates,
7139 : const ExitLimit &EL) {
7140 : assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7141 : this->AllowPredicates == AllowPredicates &&
7142 301549 : "Variance in assumed invariant key components!");
7143 :
7144 0 : auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7145 : assert(InsertResult.second && "Expected successful insertion!");
7146 : (void)InsertResult;
7147 301549 : (void)ExitIfTrue;
7148 41472 : }
7149 :
7150 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7151 : ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7152 : bool ControlsExit, bool AllowPredicates) {
7153 :
7154 : if (auto MaybeEL =
7155 6840 : Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7156 : return *MaybeEL;
7157 0 :
7158 : ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7159 6858 : ControlsExit, AllowPredicates);
7160 : Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7161 : return EL;
7162 193796 : }
7163 :
7164 290975 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7165 97179 : ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7166 : bool ControlsExit, bool AllowPredicates) {
7167 : // Check if the controlling expression for this loop is an And or Or.
7168 286124 : if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7169 184876 : if (BO->getOpcode() == Instruction::And) {
7170 92438 : // Recurse on the operands of the and.
7171 : bool EitherMayExit = !ExitIfTrue;
7172 : ExitLimit EL0 = computeExitLimitFromCondCached(
7173 : Cache, L, BO->getOperand(0), ExitIfTrue,
7174 : ControlsExit && !EitherMayExit, AllowPredicates);
7175 : ExitLimit EL1 = computeExitLimitFromCondCached(
7176 63194 : Cache, L, BO->getOperand(1), ExitIfTrue,
7177 63194 : ControlsExit && !EitherMayExit, AllowPredicates);
7178 : const SCEV *BECount = getCouldNotCompute();
7179 : const SCEV *MaxBECount = getCouldNotCompute();
7180 : if (EitherMayExit) {
7181 63194 : // Both conditions must be true for the loop to continue executing.
7182 : // Choose the less conservative count.
7183 12911 : if (EL0.ExactNotTaken == getCouldNotCompute() ||
7184 : EL1.ExactNotTaken == getCouldNotCompute())
7185 12911 : BECount = getCouldNotCompute();
7186 12911 : else
7187 : BECount =
7188 : getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7189 : if (EL0.MaxNotTaken == getCouldNotCompute())
7190 : MaxBECount = EL1.MaxNotTaken;
7191 : else if (EL1.MaxNotTaken == getCouldNotCompute())
7192 : MaxBECount = EL0.MaxNotTaken;
7193 26188 : else
7194 13290 : MaxBECount =
7195 : getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7196 12911 : } else {
7197 : // Both conditions must be true at the same time for the loop to exit.
7198 12447 : // For now, be conservative.
7199 : if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7200 12447 : MaxBECount = EL0.MaxNotTaken;
7201 24894 : if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7202 : BECount = EL0.ExactNotTaken;
7203 : }
7204 :
7205 12447 : // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7206 : // to be more aggressive when computing BECount than when computing
7207 49 : // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7208 49 : // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7209 49 : // to not.
7210 : if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7211 : !isa<SCEVCouldNotCompute>(BECount))
7212 : MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7213 49 :
7214 : return ExitLimit(BECount, MaxBECount, false,
7215 : {&EL0.Predicates, &EL1.Predicates});
7216 : }
7217 26690 : if (BO->getOpcode() == Instruction::Or) {
7218 : // Recurse on the operands of the or.
7219 : bool EitherMayExit = ExitIfTrue;
7220 26690 : ExitLimit EL0 = computeExitLimitFromCondCached(
7221 26690 : Cache, L, BO->getOperand(0), ExitIfTrue,
7222 : ControlsExit && !EitherMayExit, AllowPredicates);
7223 : ExitLimit EL1 = computeExitLimitFromCondCached(
7224 26690 : Cache, L, BO->getOperand(1), ExitIfTrue,
7225 : ControlsExit && !EitherMayExit, AllowPredicates);
7226 : const SCEV *BECount = getCouldNotCompute();
7227 : const SCEV *MaxBECount = getCouldNotCompute();
7228 : if (EitherMayExit) {
7229 : // Both conditions must be false for the loop to continue executing.
7230 : // Choose the less conservative count.
7231 : if (EL0.ExactNotTaken == getCouldNotCompute() ||
7232 : EL1.ExactNotTaken == getCouldNotCompute())
7233 : BECount = getCouldNotCompute();
7234 : else
7235 : BECount =
7236 : getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7237 : if (EL0.MaxNotTaken == getCouldNotCompute())
7238 26690 : MaxBECount = EL1.MaxNotTaken;
7239 : else if (EL1.MaxNotTaken == getCouldNotCompute())
7240 : MaxBECount = EL0.MaxNotTaken;
7241 26690 : else
7242 : MaxBECount =
7243 : getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7244 26594 : } else {
7245 : // Both conditions must be false at the same time for the loop to exit.
7246 26594 : // For now, be conservative.
7247 : if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7248 : MaxBECount = EL0.MaxNotTaken;
7249 : if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7250 26690 : BECount = EL0.ExactNotTaken;
7251 : }
7252 :
7253 26690 : return ExitLimit(BECount, MaxBECount, false,
7254 : {&EL0.Predicates, &EL1.Predicates});
7255 : }
7256 : }
7257 26690 :
7258 : // With an icmp, it may be feasible to compute an exact backedge-taken count.
7259 26690 : // Proceed to the next level to examine the icmp.
7260 : if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7261 : ExitLimit EL =
7262 : computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7263 : if (EL.hasFullInfo() || !AllowPredicates)
7264 : return EL;
7265 :
7266 : // Try again, but use SCEV predicates this time.
7267 86750 : return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7268 60060 : /*AllowPredicates=*/true);
7269 60060 : }
7270 :
7271 : // Check for a constant condition. These are normally stripped out by
7272 : // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7273 : // preserve the CFG and is temporarily leaving constant conditions
7274 : // in place.
7275 : if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7276 60060 : if (ExitIfTrue == !CI->getZExtValue())
7277 : // The backedge is always taken.
7278 : return getCouldNotCompute();
7279 : else
7280 : // The backedge is never taken.
7281 17813 : return getZero(CI->getType());
7282 : }
7283 :
7284 : // If it's not an integer or pointer comparison then compute it the hard way.
7285 : return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7286 : }
7287 :
7288 : ScalarEvolution::ExitLimit
7289 : ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7290 : ICmpInst *ExitCond,
7291 : bool ExitIfTrue,
7292 : bool ControlsExit,
7293 78939 : bool AllowPredicates) {
7294 18879 : // If the condition was exit on true, convert the condition to exit on false
7295 18879 : ICmpInst::Predicate Pred;
7296 18502 : if (!ExitIfTrue)
7297 18502 : Pred = ExitCond->getPredicate();
7298 : else
7299 : Pred = ExitCond->getInversePredicate();
7300 377 : const ICmpInst::Predicate OriginalPred = Pred;
7301 :
7302 41181 : // Handle common loops like: for (X = "string"; *X; ++X)
7303 12001 : if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7304 12001 : if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7305 : ExitLimit ItCnt =
7306 : computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7307 0 : if (ItCnt.hasAnyInfo())
7308 : return ItCnt;
7309 : }
7310 :
7311 26690 : const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7312 8188 : const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7313 :
7314 : // Try to evaluate any dependencies out of the loop.
7315 26690 : LHS = getSCEVAtScope(LHS, L);
7316 : RHS = getSCEVAtScope(RHS, L);
7317 26690 :
7318 : // At this point, we would like to compute how many iterations of the
7319 : // loop the predicate will return true for these inputs.
7320 : if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7321 60060 : // If there is a loop-invariant, force it into the RHS.
7322 : std::swap(LHS, RHS);
7323 : Pred = ICmpInst::getSwappedPredicate(Pred);
7324 : }
7325 :
7326 60060 : // Simplify the operands before analyzing them.
7327 60060 : (void)SimplifyICmpOperands(Pred, LHS, RHS);
7328 21445 :
7329 : // If we have a comparison of a chrec against a constant, try to use value
7330 38615 : // ranges to answer this query.
7331 : if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7332 : if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7333 : if (AddRec->getLoop() == L) {
7334 31158 : // Form the constant range.
7335 : ConstantRange CompRange =
7336 : ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7337 :
7338 : const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7339 : if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7340 62316 : }
7341 :
7342 : switch (Pred) {
7343 : case ICmpInst::ICMP_NE: { // while (X != Y)
7344 : // Convert to: while (X-Y != 0)
7345 : ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7346 1109 : AllowPredicates);
7347 783 : if (EL.hasAnyInfo()) return EL;
7348 415 : break;
7349 168 : }
7350 : case ICmpInst::ICMP_EQ: { // while (X == Y)
7351 : // Convert to: while (X-Y == 0)
7352 : ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7353 : if (EL.hasAnyInfo()) return EL;
7354 79 : break;
7355 : }
7356 : case ICmpInst::ICMP_SLT:
7357 7210 : case ICmpInst::ICMP_ULT: { // while (X < Y)
7358 : bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7359 : ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7360 31158 : AllowPredicates);
7361 : if (EL.hasAnyInfo()) return EL;
7362 : break;
7363 31158 : }
7364 : case ICmpInst::ICMP_SGT:
7365 31158 : case ICmpInst::ICMP_UGT: { // while (X > Y)
7366 : bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7367 : ExitLimit EL =
7368 : howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7369 31988 : AllowPredicates);
7370 : if (EL.hasAnyInfo()) return EL;
7371 : break;
7372 : }
7373 : default:
7374 : break;
7375 : }
7376 :
7377 : auto *ExhaustiveCount =
7378 : computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7379 63976 :
7380 31988 : if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7381 : return ExhaustiveCount;
7382 :
7383 : return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7384 : ExitCond->getOperand(1), L, OriginalPred);
7385 31928 : }
7386 :
7387 : ScalarEvolution::ExitLimit
7388 : ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7389 : SwitchInst *Switch,
7390 : BasicBlock *ExitingBlock,
7391 : bool ControlsExit) {
7392 : assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7393 :
7394 31928 : // Give up if the exit is the default dest of a switch.
7395 : if (Switch->getDefaultDest() == ExitingBlock)
7396 : return getCouldNotCompute();
7397 :
7398 31928 : assert(L->contains(Switch->getDefaultDest()) &&
7399 : "Default case must not exit the loop!");
7400 31988 : const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7401 : const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7402 :
7403 : // while (X != Y) --> while (X-Y != 0)
7404 31988 : ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7405 31988 : if (EL.hasAnyInfo())
7406 : return EL;
7407 :
7408 : return getCouldNotCompute();
7409 31928 : }
7410 31928 :
7411 : static ConstantInt *
7412 : EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7413 : ScalarEvolution &SE) {
7414 31928 : const SCEV *InVal = SE.getConstant(C);
7415 : const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7416 : assert(isa<SCEVConstant>(Val) &&
7417 : "Evaluation of SCEV at constant didn't fold correctly?");
7418 : return cast<SCEVConstant>(Val)->getValue();
7419 444 : }
7420 :
7421 : /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7422 : /// compute the backedge execution count.
7423 : ScalarEvolution::ExitLimit
7424 301 : ScalarEvolution::computeLoadConstantCompareExitLimit(
7425 : LoadInst *LI,
7426 : Constant *RHS,
7427 301 : const Loop *L,
7428 301 : ICmpInst::Predicate predicate) {
7429 301 : if (LI->isVolatile()) return getCouldNotCompute();
7430 301 :
7431 : // Check to see if the loaded pointer is a getelementptr of a global.
7432 : // TODO: Use SCEV instead of manually grubbing with GEPs.
7433 336 : GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7434 107 : if (!GEP) return getCouldNotCompute();
7435 211 :
7436 : // Make sure that it is really a constant global we are gepping, with an
7437 : // initializer, and make sure the first IDX is really 0.
7438 18 : GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7439 229 : if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7440 122 : GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7441 107 : !cast<Constant>(GEP->getOperand(1))->isNullValue())
7442 89 : return getCouldNotCompute();
7443 :
7444 : // Okay, we allow one non-constant index into the GEP instruction.
7445 18 : Value *VarIdx = nullptr;
7446 : std::vector<Constant*> Indexes;
7447 : unsigned VarIdxNum = 0;
7448 : for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7449 72 : if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7450 : Indexes.push_back(CI);
7451 72 : } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7452 : if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
7453 : VarIdx = GEP->getOperand(i);
7454 : VarIdxNum = i-2;
7455 : Indexes.push_back(nullptr);
7456 : }
7457 :
7458 : // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7459 : if (!VarIdx)
7460 393 : return getCouldNotCompute();
7461 :
7462 2 : // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7463 : // Check to see if X is a loop variant variable value now.
7464 : const SCEV *Idx = getSCEV(VarIdx);
7465 602 : Idx = getSCEVAtScope(Idx, L);
7466 :
7467 143 : // We can only recognize very limited forms of loop index expressions, in
7468 : // particular, only affine AddRec's like {C1,+,C2}.
7469 : const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7470 : if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7471 : !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7472 114 : !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7473 : return getCouldNotCompute();
7474 :
7475 114 : unsigned MaxSteps = MaxBruteForceIterations;
7476 114 : for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7477 114 : ConstantInt *ItCst = ConstantInt::get(
7478 114 : cast<IntegerType>(IdxExpr->getType()), IterationNum);
7479 : ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7480 :
7481 81 : // Form the GEP offset.
7482 7 : Indexes[VarIdxNum] = Val;
7483 71 :
7484 : Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7485 : Indexes);
7486 3 : if (!Result) break; // Cannot compute!
7487 74 :
7488 67 : // Evaluate the condition for this iteration.
7489 7 : Result = ConstantExpr::getICmp(predicate, Result, RHS);
7490 4 : if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
7491 : if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7492 : ++NumArrayLenItCounts;
7493 3 : return getConstant(ItCst); // Found terminating iteration!
7494 : }
7495 : }
7496 : return getCouldNotCompute();
7497 40 : }
7498 :
7499 40 : ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7500 : Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7501 : ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7502 : if (!RHS)
7503 : return getCouldNotCompute();
7504 228 :
7505 : const BasicBlock *Latch = L->getLoopLatch();
7506 : if (!Latch)
7507 : return getCouldNotCompute();
7508 :
7509 : const BasicBlock *Predecessor = L->getLoopPredecessor();
7510 : if (!Predecessor)
7511 : return getCouldNotCompute();
7512 29897 :
7513 29897 : // Return true if V is of the form "LHS `shift_op` <positive constant>".
7514 : // Return LHS in OutLHS and shift_opt in OutOpCode.
7515 : auto MatchPositiveShift =
7516 : [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7517 :
7518 1144 : using namespace PatternMatch;
7519 :
7520 : ConstantInt *ShiftAmt;
7521 : if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7522 : OutOpCode = Instruction::LShr;
7523 : else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7524 : OutOpCode = Instruction::AShr;
7525 : else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7526 682 : OutOpCode = Instruction::Shl;
7527 : else
7528 142 : return false;
7529 :
7530 : return ShiftAmt->getValue().isStrictlyPositive();
7531 540 : };
7532 :
7533 : // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7534 : //
7535 934 : // loop:
7536 : // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7537 : // %iv.shifted = lshr i32 %iv, <positive constant>
7538 : //
7539 31041 : // Return true on a successful match. Return the corresponding PHI node (%iv
7540 : // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7541 : auto MatchShiftRecurrence =
7542 : [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7543 : Optional<Instruction::BinaryOps> PostShiftOpCode;
7544 :
7545 : {
7546 31041 : Instruction::BinaryOps OpC;
7547 15487 : Value *V;
7548 :
7549 15554 : // If we encounter a shift instruction, "peel off" the shift operation,
7550 31041 : // and remember that we did so. Later when we inspect %iv's backedge
7551 : // value, we will make sure that the backedge value uses the same
7552 : // operation.
7553 : //
7554 : // Note: the peeled shift operation does not have to be the same
7555 : // instruction as the one feeding into the PHI's backedge value. We only
7556 2450 : // really care about it being the same *kind* of shift instruction --
7557 2450 : // that's all that is required for our later inferences to hold.
7558 : if (MatchPositiveShift(LHS, V, OpC)) {
7559 : PostShiftOpCode = OpC;
7560 : LHS = V;
7561 31041 : }
7562 31041 : }
7563 :
7564 : PNOut = dyn_cast<PHINode>(LHS);
7565 31041 : if (!PNOut || PNOut->getParent() != L->getHeader())
7566 31041 : return false;
7567 :
7568 : Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7569 : Value *OpLHS;
7570 31041 :
7571 : return
7572 : // The backedge value for the PHI node must be a shift by a positive
7573 978 : // amount
7574 : MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7575 :
7576 : // of the PHI node itself
7577 31041 : OpLHS == PNOut &&
7578 :
7579 : // and the kind of shift should be match the kind of shift we peeled
7580 : // off, if any.
7581 31041 : (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7582 16230 : };
7583 10545 :
7584 : PHINode *PN;
7585 : Instruction::BinaryOps OpCode;
7586 12991 : if (!MatchShiftRecurrence(LHS, PN, OpCode))
7587 : return getCouldNotCompute();
7588 10531 :
7589 10531 : const DataLayout &DL = getDataLayout();
7590 :
7591 : // The key rationale for this optimization is that for some kinds of shift
7592 22970 : // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7593 12641 : // within a finite number of iterations. If the condition guarding the
7594 : // backedge (in the sense that the backedge is taken if the condition is true)
7595 : // is false for the value the shift recurrence stabilizes to, then we know
7596 12641 : // that the backedge is taken only a finite number of times.
7597 12641 :
7598 : ConstantInt *StableValue = nullptr;
7599 : switch (OpCode) {
7600 1568 : default:
7601 : llvm_unreachable("Impossible case!");
7602 1568 :
7603 1568 : case Instruction::AShr: {
7604 : // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7605 : // bitwidth(K) iterations.
7606 5958 : Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7607 : KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7608 5958 : Predecessor->getTerminator(), &DT);
7609 : auto *Ty = cast<IntegerType>(RHS->getType());
7610 5958 : if (Known.isNonNegative())
7611 5958 : StableValue = ConstantInt::get(Ty, 0);
7612 : else if (Known.isNegative())
7613 : StableValue = ConstantInt::get(Ty, -1, true);
7614 1757 : else
7615 : return getCouldNotCompute();
7616 1757 :
7617 : break;
7618 : }
7619 1757 : case Instruction::LShr:
7620 1757 : case Instruction::Shl:
7621 : // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7622 : // stabilize to 0 in at most bitwidth(K) iterations.
7623 : StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7624 : break;
7625 : }
7626 :
7627 : auto *Result =
7628 12696 : ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7629 : assert(Result->getType()->isIntegerTy(1) &&
7630 12696 : "Otherwise cannot be an operand to a branch instruction");
7631 61 :
7632 : if (Result->isZeroValue()) {
7633 : unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7634 12635 : const SCEV *UpperBound =
7635 : getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7636 : return ExitLimit(getCouldNotCompute(), UpperBound, false);
7637 : }
7638 79 :
7639 : return getCouldNotCompute();
7640 : }
7641 :
7642 : /// Return true if we can constant fold an instruction of the specified type,
7643 : /// assuming that all operands were constants.
7644 : static bool CanConstantFold(const Instruction *I) {
7645 79 : if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7646 47 : isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7647 : isa<LoadInst>(I))
7648 : return true;
7649 :
7650 32 : if (const CallInst *CI = dyn_cast<CallInst>(I))
7651 32 : if (const Function *F = CI->getCalledFunction())
7652 : return canConstantFoldCallTo(CI, F);
7653 : return false;
7654 32 : }
7655 32 :
7656 : /// Determine whether this instruction can constant evolve within this loop
7657 : /// assuming its operands can all constant evolve.
7658 31 : static bool canConstantEvolve(Instruction *I, const Loop *L) {
7659 : // An instruction outside of the loop can't be derived from a loop PHI.
7660 : if (!L->contains(I)) return false;
7661 :
7662 8348 : if (isa<PHINode>(I)) {
7663 : // We don't currently keep track of the control flow needed to evaluate
7664 8348 : // PHIs, so we cannot handle PHIs inside of loops.
7665 8348 : return L->getHeader() == I->getParent();
7666 : }
7667 :
7668 8348 : // If we won't be able to constant fold this expression even if the operands
7669 : // are constants, bail early.
7670 : return CanConstantFold(I);
7671 : }
7672 :
7673 : /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7674 2450 : /// recursing through each instruction operand until reaching a loop header phi.
7675 : static PHINode *
7676 : getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7677 : DenseMap<Instruction *, PHINode *> &PHIMap,
7678 : unsigned Depth) {
7679 2450 : if (Depth > MaxConstantEvolvingDepth)
7680 : return nullptr;
7681 :
7682 : // Otherwise, we can evaluate this instruction if all of its operands are
7683 : // constant or derived from a PHI node themselves.
7684 937 : PHINode *PHI = nullptr;
7685 : for (Value *Op : UseInst->operands()) {
7686 : if (isa<Constant>(Op)) continue;
7687 :
7688 : Instruction *OpInst = dyn_cast<Instruction>(Op);
7689 18 : if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7690 0 :
7691 0 : PHINode *P = dyn_cast<PHINode>(OpInst);
7692 1449 : if (!P)
7693 : // If this operand is already visited, reuse the prior result.
7694 : // We may have P != PHI if this is the deepest point at which the
7695 : // inconsistent paths meet.
7696 : P = PHIMap.lookup(OpInst);
7697 : if (!P) {
7698 0 : // Recurse and memoize the results, whether a phi is found or not.
7699 : // This recursive call invalidates pointers into PHIMap.
7700 0 : P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7701 0 : PHIMap[OpInst] = P;
7702 0 : }
7703 : if (!P)
7704 0 : return nullptr; // Not evolving from PHI
7705 0 : if (PHI && PHI != P)
7706 : return nullptr; // Evolving from multiple different PHIs.
7707 : PHI = P;
7708 : }
7709 0 : // This is a expression evolving from a constant PHI!
7710 0 : return PHI;
7711 : }
7712 :
7713 : /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7714 0 : /// in the loop that V is derived from. We allow arbitrary operations along the
7715 0 : /// way, but the operands of an operation must either be constants or a value
7716 : /// derived from a constant PHI. If this expression does not fit with these
7717 : /// constraints, return null.
7718 : static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7719 : Instruction *I = dyn_cast<Instruction>(V);
7720 0 : if (!I || !canConstantEvolve(I, L)) return nullptr;
7721 0 :
7722 : if (PHINode *PN = dyn_cast<PHINode>(I))
7723 0 : return PN;
7724 :
7725 : // Record non-constant instructions contained by the loop.
7726 0 : DenseMap<Instruction *, PHINode *> PHIMap;
7727 0 : return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7728 : }
7729 0 :
7730 : /// EvaluateExpression - Given an expression that passes the
7731 : /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7732 0 : /// in the loop has the value PHIVal. If we can't fold this expression for some
7733 : /// reason, return null.
7734 0 : static Constant *EvaluateExpression(Value *V, const Loop *L,
7735 : DenseMap<Instruction *, Constant *> &Vals,
7736 0 : const DataLayout &DL,
7737 : const TargetLibraryInfo *TLI) {
7738 : // Convenient constant check, but redundant for recursive calls.
7739 0 : if (Constant *C = dyn_cast<Constant>(V)) return C;
7740 0 : Instruction *I = dyn_cast<Instruction>(V);
7741 0 : if (!I) return nullptr;
7742 :
7743 0 : if (Constant *C = Vals.lookup(I)) return C;
7744 :
7745 : // An instruction inside the loop depends on a value outside the loop that we
7746 0 : // weren't given a mapping for, or a value such as a call inside the loop.
7747 : if (!canConstantEvolve(I, L)) return nullptr;
7748 :
7749 12635 : // An unmapped PHI can be due to a branch or another loop inside this loop,
7750 : // or due to this not being the initial iteration through a loop where we
7751 : // couldn't compute the evolution of this particular PHI last time.
7752 : if (isa<PHINode>(I)) return nullptr;
7753 7395 :
7754 : std::vector<Constant*> Operands(I->getNumOperands());
7755 5240 :
7756 5240 : for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7757 0 : Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7758 : if (!Operand) {
7759 5240 : Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7760 5240 : if (!Operands[i]) return nullptr;
7761 3 : continue;
7762 : }
7763 : Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7764 : Vals[Operand] = C;
7765 : if (!C) return nullptr;
7766 : Operands[i] = C;
7767 : }
7768 :
7769 : if (CmpInst *CI = dyn_cast<CmpInst>(I))
7770 : return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7771 : Operands[1], DL, TLI);
7772 : if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7773 : if (!LI->isVolatile())
7774 : return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7775 : }
7776 : return ConstantFoldInstOperands(I, Operands, DL, TLI);
7777 : }
7778 :
7779 :
7780 : // If every incoming value to PN except the one for BB is a specific Constant,
7781 : // return that, else return nullptr.
7782 : static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7783 : Constant *IncomingVal = nullptr;
7784 :
7785 : for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7786 : if (PN->getIncomingBlock(i) == BB)
7787 : continue;
7788 :
7789 : auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7790 : if (!CurrentVal)
7791 : return nullptr;
7792 :
7793 : if (IncomingVal != CurrentVal) {
7794 : if (IncomingVal)
7795 : return nullptr;
7796 : IncomingVal = CurrentVal;
7797 : }
7798 : }
7799 :
7800 : return IncomingVal;
7801 : }
7802 :
7803 : /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7804 : /// in the header of its containing loop, we know the loop executes a
7805 : /// constant number of times, and the PHI node is just a recurrence
7806 : /// involving constants, fold it.
7807 : Constant *
7808 : ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7809 : const APInt &BEs,
7810 : const Loop *L) {
7811 : auto I = ConstantEvolutionLoopExitValue.find(PN);
7812 : if (I != ConstantEvolutionLoopExitValue.end())
7813 : return I->second;
7814 :
7815 : if (BEs.ugt(MaxBruteForceIterations))
7816 : return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
7817 :
7818 : Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7819 :
7820 : DenseMap<Instruction *, Constant *> CurrentIterVals;
7821 : BasicBlock *Header = L->getHeader();
7822 : assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7823 :
7824 : BasicBlock *Latch = L->getLoopLatch();
7825 : if (!Latch)
7826 : return nullptr;
7827 :
7828 : for (PHINode &PHI : Header->phis()) {
7829 : if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7830 : CurrentIterVals[&PHI] = StartCST;
7831 : }
7832 5237 : if (!CurrentIterVals.count(PN))
7833 : return RetVal = nullptr;
7834 :
7835 : Value *BEValue = PN->getIncomingValueForBlock(Latch);
7836 5237 :
7837 5177 : // Execute the loop symbolically to determine the exit value.
7838 : assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7839 60 : "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7840 :
7841 : unsigned NumIterations = BEs.getZExtValue(); // must be in range
7842 : unsigned IterationNum = 0;
7843 : const DataLayout &DL = getDataLayout();
7844 : for (; ; ++IterationNum) {
7845 : if (IterationNum == NumIterations)
7846 : return RetVal = CurrentIterVals[PN]; // Got exit value!
7847 :
7848 : // Compute the value of the PHIs for the next iteration.
7849 60 : // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7850 0 : DenseMap<Instruction *, Constant *> NextIterVals;
7851 0 : Constant *NextPHI =
7852 : EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7853 37 : if (!NextPHI)
7854 : return nullptr; // Couldn't evaluate!
7855 : NextIterVals[PN] = NextPHI;
7856 37 :
7857 : bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7858 37 :
7859 : // Also evaluate the other PHI nodes. However, we don't get to stop if we
7860 37 : // cease to be able to evaluate one of them or if they stop evolving,
7861 23 : // because that doesn't necessarily prevent us from computing PN.
7862 14 : SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7863 9 : for (const auto &I : CurrentIterVals) {
7864 : PHINode *PHI = dyn_cast<PHINode>(I.first);
7865 5 : if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7866 : PHIsToCompute.emplace_back(PHI, I.second);
7867 32 : }
7868 : // We use two distinct loops because EvaluateExpression may invalidate any
7869 : // iterators into CurrentIterVals.
7870 : for (const auto &I : PHIsToCompute) {
7871 : PHINode *PHI = I.first;
7872 : Constant *&NextPHI = NextIterVals[PHI];
7873 23 : if (!NextPHI) { // Not already computed.
7874 23 : Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7875 : NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7876 : }
7877 : if (NextPHI != I.second)
7878 55 : StoppedEvolving = false;
7879 : }
7880 :
7881 : // If all entries in CurrentIterVals == NextIterVals then we can stop
7882 55 : // iterating, the loop can't continue to change.
7883 49 : if (StoppedEvolving)
7884 : return RetVal = CurrentIterVals[PN];
7885 49 :
7886 49 : CurrentIterVals.swap(NextIterVals);
7887 : }
7888 : }
7889 6 :
7890 : const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7891 : Value *Cond,
7892 : bool ExitWhen) {
7893 : PHINode *PN = getConstantEvolvingPHI(Cond, L);
7894 105427 : if (!PN) return getCouldNotCompute();
7895 52777 :
7896 156306 : // If the loop is canonicalized, the PHI will have exactly two entries.
7897 : // That's the only form we support here.
7898 : if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7899 :
7900 : DenseMap<Instruction *, Constant *> CurrentIterVals;
7901 : BasicBlock *Header = L->getHeader();
7902 3918 : assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7903 :
7904 : BasicBlock *Latch = L->getLoopLatch();
7905 : assert(Latch && "Should follow from NumIncomingValues == 2!");
7906 :
7907 : for (PHINode &PHI : Header->phis()) {
7908 75135 : if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7909 : CurrentIterVals[&PHI] = StartCST;
7910 75135 : }
7911 : if (!CurrentIterVals.count(PN))
7912 69667 : return getCouldNotCompute();
7913 :
7914 : // Okay, we find a PHI node that defines the trip count of this loop. Execute
7915 7867 : // the loop symbolically to determine when the condition gets a value of
7916 : // "ExitWhen".
7917 : unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
7918 : const DataLayout &DL = getDataLayout();
7919 : for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7920 61800 : auto *CondVal = dyn_cast_or_null<ConstantInt>(
7921 : EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7922 :
7923 : // Couldn't symbolically evaluate.
7924 : if (!CondVal) return getCouldNotCompute();
7925 :
7926 30190 : if (CondVal->getValue() == uint64_t(ExitWhen)) {
7927 : ++NumBruteForceTripCountsComputed;
7928 : return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7929 30190 : }
7930 :
7931 : // Update all the PHI nodes for the next iteration.
7932 : DenseMap<Instruction *, Constant *> NextIterVals;
7933 :
7934 : // Create a list of which PHIs we need to compute. We want to do this before
7935 85130 : // calling EvaluateExpression on them because that may invalidate iterators
7936 43643 : // into CurrentIterVals.
7937 : SmallVector<PHINode *, 8> PHIsToCompute;
7938 34703 : for (const auto &I : CurrentIterVals) {
7939 42913 : PHINode *PHI = dyn_cast<PHINode>(I.first);
7940 : if (!PHI || PHI->getParent() != Header) continue;
7941 24036 : PHIsToCompute.push_back(PHI);
7942 : }
7943 : for (PHINode *PHI : PHIsToCompute) {
7944 : Constant *&NextPHI = NextIterVals[PHI];
7945 : if (NextPHI) continue; // Already computed!
7946 17692 :
7947 6676 : Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7948 : NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7949 : }
7950 17360 : CurrentIterVals.swap(NextIterVals);
7951 17360 : }
7952 :
7953 24036 : // Too many iterations were needed to evaluate.
7954 : return getCouldNotCompute();
7955 16104 : }
7956 :
7957 : const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
7958 : SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
7959 : ValuesAtScopes[V];
7960 : // Check to see if we've folded this expression at this loop before.
7961 : for (auto &LS : Values)
7962 : if (LS.first == L)
7963 : return LS.second ? LS.second : V;
7964 :
7965 : Values.emplace_back(L, nullptr);
7966 :
7967 : // Otherwise compute it.
7968 13630 : const SCEV *C = computeSCEVAtScope(V, L);
7969 : for (auto &LS : reverse(ValuesAtScopes[V]))
7970 13630 : if (LS.first == L) {
7971 : LS.second = C;
7972 : break;
7973 : }
7974 : return C;
7975 : }
7976 :
7977 12830 : /// This builds up a Constant using the ConstantExpr interface. That way, we
7978 : /// will return Constants for objects which aren't represented by a
7979 : /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
7980 : /// Returns NULL if the SCEV isn't representable as a Constant.
7981 : static Constant *BuildConstantFromSCEV(const SCEV *V) {
7982 : switch (static_cast<SCEVTypes>(V->getSCEVType())) {
7983 : case scCouldNotCompute:
7984 54794 : case scAddRecExpr:
7985 : break;
7986 : case scConstant:
7987 : return cast<SCEVConstant>(V)->getValue();
7988 : case scUnknown:
7989 : return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
7990 : case scSignExtend: {
7991 : const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
7992 : if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
7993 54685 : return ConstantExpr::getSExt(CastOp, SS->getType());
7994 : break;
7995 : }
7996 : case scZeroExtend: {
7997 28811 : const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
7998 : if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
7999 : return ConstantExpr::getZExt(CastOp, SZ->getType());
8000 : break;
8001 : }
8002 28782 : case scTruncate: {
8003 : const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8004 28742 : if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8005 : return ConstantExpr::getTrunc(CastOp, ST->getType());
8006 85685 : break;
8007 57100 : }
8008 57100 : case scAddExpr: {
8009 17734 : const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8010 17886 : if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8011 17729 : if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8012 : unsigned AS = PTy->getAddressSpace();
8013 39366 : Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8014 39366 : C = ConstantExpr::getBitCast(C, DestPtrTy);
8015 39366 : }
8016 78428 : for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8017 : Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8018 : if (!C2) return nullptr;
8019 :
8020 7417 : // First pointer!
8021 7417 : if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8022 : unsigned AS = C2->getType()->getPointerAddressSpace();
8023 202 : std::swap(C, C2);
8024 202 : Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8025 : // The offsets have been converted to bytes. We can add bytes to an
8026 20966 : // i8* by GEP with the byte count in the first index.
8027 : C = ConstantExpr::getBitCast(C, DestPtrTy);
8028 : }
8029 :
8030 : // Don't bother trying to sum two pointers. We probably can't
8031 : // statically compute a load that results from it anyway.
8032 3854 : if (C2->getType()->isPointerTy())
8033 : return nullptr;
8034 :
8035 7698 : if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8036 6481 : if (PTy->getElementType()->isStructTy())
8037 : C2 = ConstantExpr::getIntegerCast(
8038 : C2, Type::getInt32Ty(C->getContext()), true);
8039 : C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8040 : } else
8041 : C = ConstantExpr::getAdd(C, C2);
8042 : }
8043 1219 : return C;
8044 1217 : }
8045 : break;
8046 : }
8047 : case scMulExpr: {
8048 : const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8049 : if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8050 : // Don't bother with pointers at all.
8051 : if (C->getType()->isPointerTy()) return nullptr;
8052 : for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8053 : Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8054 : if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8055 : C = ConstantExpr::getMul(C, C2);
8056 : }
8057 : return C;
8058 123 : }
8059 : break;
8060 : }
8061 123 : case scUDivExpr: {
8062 123 : const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8063 0 : if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8064 : if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8065 123 : if (LHS->getType() == RHS->getType())
8066 11 : return ConstantExpr::getUDiv(LHS, RHS);
8067 : break;
8068 : }
8069 : case scSMaxExpr:
8070 : case scUMaxExpr:
8071 : break; // TODO: smax, umax.
8072 : }
8073 : return nullptr;
8074 112 : }
8075 112 :
8076 : const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8077 : if (isa<SCEVConstant>(V)) return V;
8078 592 :
8079 368 : // If this instruction is evolved from a constant-evolving PHI, compute the
8080 217 : // exit value from the loop without using SCEVs.
8081 : if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8082 112 : if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8083 19 : const Loop *LI = this->LI[I->getParent()];
8084 : if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
8085 93 : if (PHINode *PN = dyn_cast<PHINode>(I))
8086 : if (PN->getParent() == LI->getHeader()) {
8087 : // Okay, there is no closed form solution for the PHI node. Check
8088 : // to see if the loop that contains it has a known backedge-taken
8089 : // count. If so, we may be able to force computation of the exit
8090 : // value.
8091 93 : const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8092 : if (const SCEVConstant *BTCC =
8093 93 : dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8094 443 :
8095 536 : // This trivial case can show up in some degenerate cases where
8096 65 : // the incoming IR has not yet been fully simplified.
8097 : if (BTCC->getValue()->isZero()) {
8098 : Value *InitValue = nullptr;
8099 : bool MultipleInitValues = false;
8100 : for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8101 : if (!LI->contains(PN->getIncomingBlock(i))) {
8102 471 : if (!InitValue)
8103 471 : InitValue = PN->getIncomingValue(i);
8104 : else if (InitValue != PN->getIncomingValue(i)) {
8105 443 : MultipleInitValues = true;
8106 : break;
8107 443 : }
8108 : }
8109 : if (!MultipleInitValues && InitValue)
8110 : return getSCEV(InitValue);
8111 : }
8112 : }
8113 2109 : // Okay, we know how many times the containing loop executes. If
8114 1666 : // this is a constant evolving PHI node, get the final value at
8115 1666 : // the specified iteration number.
8116 383 : Constant *RV =
8117 : getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8118 : if (RV) return getSCEV(RV);
8119 : }
8120 826 : }
8121 383 :
8122 383 : // Okay, this is an expression that we cannot symbolically evaluate
8123 383 : // into a SCEV. Check to see if it's possible to symbolically evaluate
8124 383 : // the arguments into constants, and if so, try to constant propagate the
8125 383 : // result. This is particularly useful for computing loop exit values.
8126 : if (CanConstantFold(I)) {
8127 383 : SmallVector<Constant *, 4> Operands;
8128 : bool MadeImprovement = false;
8129 : for (Value *Op : I->operands()) {
8130 : if (Constant *C = dyn_cast<Constant>(Op)) {
8131 : Operands.push_back(C);
8132 : continue;
8133 443 : }
8134 0 :
8135 : // If any of the operands is non-constant and if they are
8136 : // non-integer and non-pointer, don't even try to analyze them
8137 443 : // with scev techniques.
8138 : if (!isSCEVable(Op->getType()))
8139 : return V;
8140 13630 :
8141 : const SCEV *OrigV = getSCEV(Op);
8142 : const SCEV *OpV = getSCEVAtScope(OrigV, L);
8143 13630 : MadeImprovement |= OrigV != OpV;
8144 13630 :
8145 : Constant *C = BuildConstantFromSCEV(OpV);
8146 : if (!C) return V;
8147 : if (C->getType() != Op->getType())
8148 1782 : C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8149 : Op->getType(),
8150 : false),
8151 : C, Op->getType());
8152 : Operands.push_back(C);
8153 : }
8154 1779 :
8155 : // Check to see if getSCEVAtScope actually made an improvement.
8156 : if (MadeImprovement) {
8157 7044 : Constant *C = nullptr;
8158 3486 : const DataLayout &DL = getDataLayout();
8159 1000 : if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8160 : C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8161 182 : Operands[1], DL, &TLI);
8162 1597 : else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8163 : if (!LI->isVolatile())
8164 : C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8165 : } else
8166 : C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8167 : if (!C) return V;
8168 182 : return getSCEV(C);
8169 6692 : }
8170 6631 : }
8171 6631 : }
8172 :
8173 : // This is some other type of SCEVUnknown, just return it.
8174 121 : return V;
8175 : }
8176 13152 :
8177 : if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8178 66 : // Avoid performing the look-up in the common case where the specified
8179 : // expression has no loop-variant portions.
8180 : for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8181 : const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8182 : if (OpAtScope != Comm->getOperand(i)) {
8183 : // Okay, at least one of these operands is loop variant but might be
8184 : // foldable. Build a new instance of the folded commutative expression.
8185 : SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8186 : Comm->op_begin()+i);
8187 : NewOps.push_back(OpAtScope);
8188 30126 :
8189 23616 : for (++i; i != e; ++i) {
8190 23616 : OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8191 7943 : NewOps.push_back(OpAtScope);
8192 : }
8193 14453 : if (isa<SCEVAddExpr>(Comm))
8194 7943 : return getAddExpr(NewOps);
8195 7943 : if (isa<SCEVMulExpr>(Comm))
8196 : return getMulExpr(NewOps);
8197 7943 : if (isa<SCEVSMaxExpr>(Comm))
8198 7943 : return getSMaxExpr(NewOps);
8199 : if (isa<SCEVUMaxExpr>(Comm))
8200 : return getUMaxExpr(NewOps);
8201 : llvm_unreachable("Unknown commutative SCEV type!");
8202 : }
8203 : }
8204 61 : // If we got here, all operands are loop invariant.
8205 : return Comm;
8206 : }
8207 605174 :
8208 : if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8209 605174 : const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8210 : const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8211 1204891 : if (LHS == Div->getLHS() && RHS == Div->getRHS())
8212 924548 : return Div; // must be loop invariant
8213 324831 : return getUDivExpr(LHS, RHS);
8214 : }
8215 280343 :
8216 : // If this is a loop recurrence for a loop that does not contain L, then we
8217 : // are dealing with the final value computed by the loop.
8218 280343 : if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8219 280500 : // First, attempt to evaluate each operand.
8220 279665 : // Avoid performing the look-up in the common case where the specified
8221 279508 : // expression has no loop-variant portions.
8222 279508 : for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8223 : const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8224 : if (OpAtScope == AddRec->getOperand(i))
8225 : continue;
8226 :
8227 : // Okay, at least one of these operands is loop variant but might be
8228 : // foldable. Build a new instance of the folded commutative expression.
8229 : SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8230 : AddRec->op_begin()+i);
8231 52606 : NewOps.push_back(OpAtScope);
8232 52606 : for (++i; i != e; ++i)
8233 : NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8234 :
8235 : const SCEV *FoldedRec =
8236 : getAddRecExpr(NewOps, AddRec->getLoop(),
8237 9963 : AddRec->getNoWrapFlags(SCEV::FlagNW));
8238 : AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8239 : // The addrec may be folded to a nonrecurrence, for example, if the
8240 : // induction variable is multiplied by zero after constant folding. Go
8241 : // ahead and return the folded value.
8242 409 : if (!AddRec)
8243 0 : return FoldedRec;
8244 : break;
8245 : }
8246 :
8247 : // If the scope is outside the addrec's loop, evaluate it by using the
8248 598 : // loop exit value of the addrec.
8249 5 : if (!AddRec->getLoop()->contains(L)) {
8250 : // To evaluate this recurrence, we need to know how many times the AddRec
8251 : // loop iterates. Compute this now.
8252 : const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8253 : if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8254 339 :
8255 2 : // Then, evaluate the AddRec.
8256 : return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8257 : }
8258 :
8259 : return AddRec;
8260 19386 : }
8261 7560 :
8262 : if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8263 0 : const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8264 0 : if (Op == Cast->getOperand())
8265 : return Cast; // must be loop invariant
8266 7578 : return getZeroExtendExpr(Op, Cast->getType());
8267 15122 : }
8268 7561 :
8269 : if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8270 : const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8271 36 : if (Op == Cast->getOperand())
8272 : return Cast; // must be loop invariant
8273 : return getSignExtendExpr(Op, Cast->getType());
8274 15 : }
8275 :
8276 : if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8277 15 : const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8278 : if (Op == Cast->getOperand())
8279 : return Cast; // must be loop invariant
8280 : return getTruncateExpr(Op, Cast->getType());
8281 : }
8282 36 :
8283 : llvm_unreachable("Unknown SCEV type!");
8284 : }
8285 18 :
8286 30 : const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8287 0 : return getSCEVAtScope(getSCEV(V), L);
8288 0 : }
8289 15 :
8290 : const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8291 3 : if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8292 : return stripInjectiveFunctions(ZExt->getOperand());
8293 17 : if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8294 : return stripInjectiveFunctions(SExt->getOperand());
8295 : return S;
8296 : }
8297 :
8298 : /// Finds the minimum unsigned root of the following equation:
8299 4706 : ///
8300 : /// A * X = B (mod N)
8301 4642 : ///
8302 2324 : /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8303 4642 : /// A and B isn't important.
8304 2321 : ///
8305 3 : /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8306 : static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8307 3 : ScalarEvolution &SE) {
8308 : uint32_t BW = A.getBitWidth();
8309 : assert(BW == SE.getTypeSizeInBits(B->getType()));
8310 : assert(A != 0 && "A must be non-zero.");
8311 :
8312 : // 1. D = gcd(A, N)
8313 342 : //
8314 8 : // The gcd of A and N may have only one prime factor: 2. The number of
8315 2 : // trailing zeros in A is its multiplicity
8316 2 : uint32_t Mult2 = A.countTrailingZeros();
8317 : // D = 2^Mult2
8318 :
8319 : // 2. Check if B is divisible by D.
8320 : //
8321 : // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8322 : // is not less than multiplicity of this prime factor for D.
8323 : if (SE.GetMinTrailingZeros(B) < Mult2)
8324 : return SE.getCouldNotCompute();
8325 :
8326 280343 : // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8327 280343 : // modulo (N / D).
8328 : //
8329 : // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8330 : // (N / D) in general. The inverse itself always fits into BW bits, though,
8331 69181 : // so we immediately truncate it.
8332 : APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
8333 43718 : APInt Mod(BW + 1, 0);
8334 25413 : Mod.setBit(BW - Mult2); // Mod = N / D
8335 : APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8336 930 :
8337 : // 4. Compute the minimum unsigned root of the equation:
8338 : // I * (B / D) mod (N / D)
8339 : // To simplify the computation, we factor out the divide by D:
8340 : // (I * B mod N) / D
8341 365 : const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8342 : return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8343 : }
8344 :
8345 : /// For a given quadratic addrec, generate coefficients of the corresponding
8346 : /// quadratic equation, multiplied by a common value to ensure that they are
8347 298 : /// integers.
8348 : /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8349 : /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8350 46 : /// were multiplied by, and BitWidth is the bit width of the original addrec
8351 46 : /// coefficients.
8352 26 : /// This function returns None if the addrec coefficients are not compile-
8353 : /// time constants.
8354 0 : static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8355 : GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8356 : assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8357 : const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8358 : const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8359 46 : const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8360 26 : LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8361 : << *AddRec << '\n');
8362 :
8363 : // We currently can only solve this if the coefficients are constants.
8364 : if (!LC || !MC || !NC) {
8365 : LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8366 : return None;
8367 123 : }
8368 123 :
8369 : APInt L = LC->getAPInt();
8370 : APInt M = MC->getAPInt();
8371 : APInt N = NC->getAPInt();
8372 : assert(!N.isNullValue() && "This is not a quadratic addrec");
8373 :
8374 : unsigned BitWidth = LC->getAPInt().getBitWidth();
8375 : unsigned NewWidth = BitWidth + 1;
8376 43627 : LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8377 : << BitWidth << '\n');
8378 : // The sign-extension (as opposed to a zero-extension) here matches the
8379 61658 : // extension used in SolveQuadraticEquationWrap (with the same motivation).
8380 30459 : N = N.sext(NewWidth);
8381 1339 : M = M.sext(NewWidth);
8382 1339 : L = L.sext(NewWidth);
8383 :
8384 : // The increments are M, M+N, M+2N, ..., so the accumulated values are
8385 : // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8386 : // L+M, L+2M+N, L+3M+3N, ...
8387 : // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8388 29120 : //
8389 29003 : // The equation Acc = 0 is then
8390 : // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8391 28982 : // In a quadratic form it becomes:
8392 28982 : // N n^2 + (2M-N) n + 2L = 0.
8393 28982 :
8394 : APInt A = N;
8395 28982 : APInt B = 2 * M - A;
8396 28982 : APInt C = 2 * L;
8397 117 : APInt T = APInt(NewWidth, 2);
8398 25 : LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8399 : << "x + " << C << ", coeff bw: " << NewWidth
8400 : << ", multiplied by " << T << '\n');
8401 : return std::make_tuple(A, B, C, T, BitWidth);
8402 117 : }
8403 :
8404 : /// Helper function to compare optional APInts:
8405 : /// (a) if X and Y both exist, return min(X, Y),
8406 1098 : /// (b) if neither X nor Y exist, return None,
8407 : /// (c) if exactly one of X and Y exists, return that value.
8408 39 : static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8409 : if (X.hasValue() && Y.hasValue()) {
8410 26 : unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8411 13 : APInt XW = X->sextOrSelf(W);
8412 : APInt YW = Y->sextOrSelf(W);
8413 14 : return XW.slt(YW) ? *X : *Y;
8414 28 : }
8415 : if (!X.hasValue() && !Y.hasValue())
8416 24 : return None;
8417 39 : return X.hasValue() ? *X : *Y;
8418 31 : }
8419 :
8420 : /// Helper function to truncate an optional APInt to a given BitWidth.
8421 : /// When solving addrec-related equations, it is preferable to return a value
8422 : /// that has the same bit width as the original addrec's coefficients. If the
8423 : /// solution fits in the original bit width, truncate it (except for i1).
8424 40048 : /// Returning a value of a different bit width may inhibit some optimizations.
8425 : ///
8426 : /// In general, a solution to a quadratic equation generated from an addrec
8427 : /// may require BW+1 bits, where BW is the bit width of the addrec's
8428 : /// coefficients. The reason is that the coefficients of the quadratic
8429 : /// equation are BW+1 bits wide (to avoid truncation when converting from
8430 193555 : /// the addrec to the equation).
8431 286524 : static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8432 286524 : if (!X.hasValue())
8433 : return None;
8434 : unsigned W = X->getBitWidth();
8435 : if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8436 : return X->trunc(BitWidth);
8437 18400 : return X;
8438 : }
8439 31329 :
8440 25858 : /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8441 12929 : /// iterations. The values L, M, N are assumed to be signed, and they
8442 : /// should all have the same bit widths.
8443 18400 : /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8444 4248 : /// where BW is the bit width of the addrec's coefficients.
8445 14152 : /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8446 14145 : /// returned as such, otherwise the bit width of the returned value may
8447 7 : /// be greater than BW.
8448 4 : ///
8449 3 : /// This function returns None if
8450 3 : /// (a) the addrec coefficients are not constant, or
8451 0 : /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8452 : /// like x^2 = 5, no integer solutions exist, in other cases an integer
8453 : /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8454 : static Optional<APInt>
8455 : SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8456 : APInt A, B, C, M;
8457 : unsigned BitWidth;
8458 : auto T = GetQuadraticEquation(AddRec);
8459 3196 : if (!T.hasValue())
8460 3196 : return None;
8461 3196 :
8462 : std::tie(A, B, C, M, BitWidth) = *T;
8463 8 : LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8464 : Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8465 : if (!X.hasValue())
8466 : return None;
8467 :
8468 : ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8469 : ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8470 : if (!V->isZero())
8471 : return None;
8472 149155 :
8473 201828 : return TruncIfPossible(X, BitWidth);
8474 201828 : }
8475 97534 :
8476 : /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8477 : /// iterations. The values M, N are assumed to be signed, and they
8478 : /// should all have the same bit widths.
8479 : /// Find the least n such that c(n) does not belong to the given range,
8480 : /// while c(n-1) does.
8481 3380 : ///
8482 10232 : /// This function returns None if
8483 13704 : /// (a) the addrec coefficients are not constant, or
8484 : /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8485 : /// bounds of the range.
8486 6760 : static Optional<APInt>
8487 : SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8488 : const ConstantRange &Range, ScalarEvolution &SE) {
8489 : assert(AddRec->getOperand(0)->isZero() &&
8490 : "Starting value of addrec should be 0");
8491 : LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8492 : << Range << ", addrec " << *AddRec << '\n');
8493 : // This case is handled in getNumIterationsInRange. Here we can assume that
8494 : // we start in the range.
8495 : assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8496 : "Addrec's initial value should be in range");
8497 :
8498 : APInt A, B, C, M;
8499 101222 : unsigned BitWidth;
8500 : auto T = GetQuadraticEquation(AddRec);
8501 : if (!T.hasValue())
8502 4693 : return None;
8503 4693 :
8504 : // Be careful about the return value: there can be two reasons for not
8505 : // returning an actual number. First, if no solutions to the equations
8506 4060 : // were found, and second, if the solutions don't leave the given range.
8507 : // The first case means that the actual solution is "unknown", the second
8508 : // means that it's known, but not valid. If the solution is unknown, we
8509 : // cannot make any conclusions.
8510 : // Return a pair: the optional solution and a flag indicating if the
8511 : // solution was found.
8512 : auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8513 3208 : // Solve for signed overflow and unsigned overflow, pick the lower
8514 3208 : // solution.
8515 : LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8516 20 : << Bound << " (before multiplying by " << M << ")\n");
8517 : Bound *= M; // The quadratic equation multiplier.
8518 :
8519 : Optional<APInt> SO = None;
8520 2135 : if (BitWidth > 1) {
8521 2135 : LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8522 : "signed overflow\n");
8523 44 : SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8524 : }
8525 : LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8526 : "unsigned overflow\n");
8527 2278 : Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8528 2278 : BitWidth+1);
8529 :
8530 9 : auto LeavesRange = [&] (const APInt &X) {
8531 : ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8532 : ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8533 0 : if (Range.contains(V0->getValue()))
8534 : return false;
8535 : // X should be at least 1, so X-1 is non-negative.
8536 216416 : ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8537 216416 : ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8538 : if (Range.contains(V1->getValue()))
8539 : return true;
8540 12657 : return false;
8541 : };
8542 62 :
8543 : // If SolveQuadraticEquationWrap returns None, it means that there can
8544 0 : // be a solution, but the function failed to find it. We cannot treat it
8545 : // as "no solution".
8546 : if (!SO.hasValue() || !UO.hasValue())
8547 : return { None, false };
8548 :
8549 : // Check the smaller value first to see if it leaves the range.
8550 : // At this point, both SO and UO must have values.
8551 : Optional<APInt> Min = MinOptional(SO, UO);
8552 : if (LeavesRange(*Min))
8553 : return { Min, true };
8554 : Optional<APInt> Max = Min == SO ? UO : SO;
8555 : if (LeavesRange(*Max))
8556 2676 : return { Max, true };
8557 :
8558 2676 : // Solutions were found, but were eliminated, hence the "true".
8559 : return { None, true };
8560 : };
8561 :
8562 : std::tie(A, B, C, M, BitWidth) = *T;
8563 : // Lower bound is inclusive, subtract 1 to represent the exiting value.
8564 : APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8565 : APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8566 2676 : auto SL = SolveForBoundary(Lower);
8567 : auto SU = SolveForBoundary(Upper);
8568 : // If any of the solutions was unknown, no meaninigful conclusions can
8569 : // be made.
8570 : if (!SL.second || !SU.second)
8571 : return None;
8572 :
8573 2676 : // Claim: The correct solution is not some value between Min and Max.
8574 2188 : //
8575 : // Justification: Assuming that Min and Max are different values, one of
8576 : // them is when the first signed overflow happens, the other is when the
8577 : // first unsigned overflow happens. Crossing the range boundary is only
8578 : // possible via an overflow (treating 0 as a special case of it, modeling
8579 : // an overflow as crossing k*2^W for some k).
8580 : //
8581 : // The interesting case here is when Min was eliminated as an invalid
8582 976 : // solution, but Max was not. The argument is that if there was another
8583 : // overflow between Min and Max, it would also have been eliminated if
8584 488 : // it was considered.
8585 488 : //
8586 : // For a given boundary, it is possible to have two overflows of the same
8587 : // type (signed/unsigned) without having the other type in between: this
8588 : // can happen when the vertex of the parabola is between the iterations
8589 : // corresponding to the overflows. This is only possible when the two
8590 : // overflows cross k*2^W for the same k. In such case, if the second one
8591 488 : // left the range (and was the first one to do so), the first overflow
8592 488 : // would have to enter the range, which would mean that either we had left
8593 : // the range before or that we started outside of it. Both of these cases
8594 : // are contradictions.
8595 : //
8596 : // Claim: In the case where SolveForBoundary returns None, the correct
8597 : // solution is not some value between the Max for this boundary and the
8598 : // Min of the other boundary.
8599 : //
8600 : // Justification: Assume that we had such Max_A and Min_B corresponding
8601 : // to range boundaries A and B and such that Max_A < Min_B. If there was
8602 : // a solution between Max_A and Min_B, it would have to be caused by an
8603 : // overflow corresponding to either A or B. It cannot correspond to B,
8604 : // since Min_B is the first occurrence of such an overflow. If it
8605 25 : // corresponded to A, it would have to be either a signed or an unsigned
8606 : // overflow that is larger than both eliminated overflows for A. But
8607 25 : // between the eliminated overflows and this overflow, the values would
8608 : // cover the entire value space, thus crossing the other boundary, which
8609 : // is a contradiction.
8610 :
8611 : return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8612 : }
8613 :
8614 25 : ScalarEvolution::ExitLimit
8615 : ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8616 : bool AllowPredicates) {
8617 :
8618 : // This is only used for loops with a "x != y" exit test. The exit condition
8619 : // is now expressed as a single expression, V = x-y. So the exit test is
8620 : // effectively V != 0. We know and take advantage of the fact that this
8621 : // expression only being used in a comparison by zero context.
8622 :
8623 : SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8624 25 : // If the value is a constant
8625 25 : if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8626 : // If the value is already zero, the branch will execute zero times.
8627 : if (C->getValue()->isZero()) return C;
8628 : return getCouldNotCompute(); // Otherwise it will loop infinitely.
8629 : }
8630 25 :
8631 25 : const SCEVAddRecExpr *AddRec =
8632 50 : dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8633 :
8634 : if (!AddRec && AllowPredicates)
8635 : // Try to make this an AddRec using runtime tests, in the first X
8636 : // iterations of this loop, where X is the SCEV expression found by the
8637 : // algorithm below.
8638 : AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8639 :
8640 : if (!AddRec || AddRec->getLoop() != L)
8641 : return getCouldNotCompute();
8642 :
8643 : // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8644 : // the quadratic equation to solve it.
8645 25 : if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8646 25 : // We can only use this value if the chrec ends up with an exact zero
8647 : // value at this index. When solving for "X*X != 5", for example, we
8648 : // should not accept a root of 2.
8649 : if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8650 : const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8651 25 : return ExitLimit(R, R, false, Predicates);
8652 : }
8653 : return getCouldNotCompute();
8654 : }
8655 :
8656 : // Otherwise we can only handle this if it is affine.
8657 : if (!AddRec->isAffine())
8658 42 : return getCouldNotCompute();
8659 42 :
8660 30 : // If this is an affine expression, the execution count of this branch is
8661 30 : // the minimum unsigned root of the following equation:
8662 30 : //
8663 30 : // Start + Step*N = 0 (mod 2^BW)
8664 : //
8665 12 : // equivalent to:
8666 : //
8667 6 : // Step*N = -Start (mod 2^BW)
8668 : //
8669 : // where BW is the common bit width of Start and Step.
8670 :
8671 : // Get the initial value for the loop.
8672 : const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8673 : const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8674 :
8675 : // For now we handle only constant steps.
8676 : //
8677 : // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8678 : // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8679 : // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8680 : // We have not yet seen any such cases.
8681 16 : const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8682 16 : if (!StepC || StepC->getValue()->isZero())
8683 : return getCouldNotCompute();
8684 10 :
8685 10 : // For positive steps (counting up until unsigned overflow):
8686 8 : // N = -Start/Step (as unsigned)
8687 : // For negative steps (counting down to zero):
8688 : // N = Start/-Step
8689 : // First compute the unsigned distance from zero in the direction of Step.
8690 : bool CountDown = StepC->getAPInt().isNegative();
8691 : const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8692 :
8693 : // Handle unitary steps, which cannot wraparound.
8694 : // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8695 : // N = Distance (as unsigned)
8696 : if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8697 : APInt MaxBECount = getUnsignedRangeMax(Distance);
8698 :
8699 : // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8700 : // we end up with a loop whose backedge-taken count is n - 1. Detect this
8701 : // case, and see if we can improve the bound.
8702 : //
8703 : // Explicitly handling this here is necessary because getUnsignedRange
8704 : // isn't context-sensitive; it doesn't know that we only care about the
8705 11 : // range inside the loop.
8706 : const SCEV *Zero = getZero(Distance->getType());
8707 : const SCEV *One = getOne(Distance->getType());
8708 11 : const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8709 11 : if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8710 : // If Distance + 1 doesn't overflow, we can compute the maximum distance
8711 : // as "unsigned_max(Distance + 1) - 1".
8712 11 : ConstantRange CR = getUnsignedRange(DistancePlusOne);
8713 : MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8714 42 : }
8715 11 : return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8716 : }
8717 :
8718 11 : // If the condition controls loop exit (the loop exits only if the expression
8719 11 : // is true) and the addition is no-wrap we can use unsigned divide to
8720 11 : // compute the backedge count. In this case, the step may not divide the
8721 : // distance, but we don't care because if the condition is "missed" the loop
8722 : // will have undefined behavior due to wrapping.
8723 6 : if (ControlsExit && AddRec->hasNoSelfWrap() &&
8724 : loopHasNoAbnormalExits(AddRec->getLoop())) {
8725 : const SCEV *Exact =
8726 : getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8727 : const SCEV *Max =
8728 : Exact == getCouldNotCompute()
8729 : ? Exact
8730 : : getConstant(getUnsignedRangeMax(Exact));
8731 : return ExitLimit(Exact, Max, false, Predicates);
8732 : }
8733 :
8734 : // Solve the general equation.
8735 : const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8736 : getNegativeSCEV(Start), *this);
8737 14 : const SCEV *M = E == getCouldNotCompute()
8738 : ? E
8739 : : getConstant(getUnsignedRangeMax(E));
8740 : return ExitLimit(E, M, false, Predicates);
8741 : }
8742 :
8743 : ScalarEvolution::ExitLimit
8744 : ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8745 : // Loops that look like: while (X == 0) are very strange indeed. We don't
8746 : // handle them yet except for the trivial case. This could be expanded in the
8747 : // future as needed.
8748 :
8749 : // If the value is a constant, check to see if it is known to be non-zero
8750 14 : // already. If so, the backedge will execute zero times.
8751 14 : if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8752 : if (!C->getValue()->isZero())
8753 : return getZero(C->getType());
8754 : return getCouldNotCompute(); // Otherwise it will loop infinitely.
8755 : }
8756 :
8757 : // We could implement others, but I really doubt anyone writes loops like
8758 : // this, and if they did, they would already be constant folded.
8759 : return getCouldNotCompute();
8760 : }
8761 :
8762 : std::pair<BasicBlock *, BasicBlock *>
8763 : ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8764 : // If the block has a unique predecessor, then there is no path from the
8765 : // predecessor to the block that does not go through the direct edge
8766 : // from the predecessor to the block.
8767 : if (BasicBlock *Pred = BB->getSinglePredecessor())
8768 : return {Pred, BB};
8769 :
8770 : // A loop's header is defined to be a block that dominates the loop.
8771 : // If the header has a unique predecessor outside the loop, it must be
8772 : // a block that has exactly one successor that can reach the loop.
8773 : if (Loop *L = LI.getLoopFor(BB))
8774 : return {L->getLoopPredecessor(), L->getHeader()};
8775 :
8776 : return {nullptr, nullptr};
8777 : }
8778 :
8779 : /// SCEV structural equivalence is usually sufficient for testing whether two
8780 : /// expressions are equal, however for the purposes of looking for a condition
8781 : /// guarding a loop, it can be useful to be a little more general, since a
8782 : /// front-end may have replicated the controlling expression.
8783 : static bool HasSameValue(const SCEV *A, const SCEV *B) {
8784 : // Quick check to see if they are the same SCEV.
8785 : if (A == B) return true;
8786 :
8787 : auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8788 : // Not all instructions that are "identical" compute the same value. For
8789 : // instance, two distinct alloca instructions allocating the same type are
8790 : // identical and do not read memory; but compute distinct values.
8791 : return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8792 : };
8793 :
8794 : // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8795 : // two different instructions with the same value. Check for this case.
8796 : if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8797 : if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8798 : if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8799 : if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8800 : if (ComputesEqualValues(AI, BI))
8801 : return true;
8802 :
8803 : // Otherwise assume they may have a different value.
8804 : return false;
8805 : }
8806 :
8807 : bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8808 : const SCEV *&LHS, const SCEV *&RHS,
8809 : unsigned Depth) {
8810 14 : bool Changed = false;
8811 : // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8812 14 : // '0 != 0'.
8813 : auto TrivialCase = [&](bool TriviallyTrue) {
8814 28 : LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8815 14 : Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8816 28 : return true;
8817 14 : };
8818 : // If we hit the max recursion limit bail out.
8819 : if (Depth >= 3)
8820 14 : return false;
8821 :
8822 : // Canonicalize a constant to the right side.
8823 : if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8824 : // Check for both operands constant.
8825 : if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8826 : if (ConstantExpr::getICmp(Pred,
8827 : LHSC->getValue(),
8828 : RHSC->getValue())->isNullValue())
8829 : return TrivialCase(false);
8830 : else
8831 : return TrivialCase(true);
8832 : }
8833 : // Otherwise swap the operands to put the constant on the right.
8834 : std::swap(LHS, RHS);
8835 : Pred = ICmpInst::getSwappedPredicate(Pred);
8836 : Changed = true;
8837 : }
8838 :
8839 : // If we're comparing an addrec with a value which is loop-invariant in the
8840 : // addrec's loop, put the addrec on the left. Also make a dominance check,
8841 : // as both operands could be addrecs loop-invariant in each other's loop.
8842 : if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8843 : const Loop *L = AR->getLoop();
8844 : if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8845 : std::swap(LHS, RHS);
8846 : Pred = ICmpInst::getSwappedPredicate(Pred);
8847 : Changed = true;
8848 : }
8849 : }
8850 :
8851 : // If there's a constant operand, canonicalize comparisons with boundary
8852 : // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8853 : if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8854 : const APInt &RA = RC->getAPInt();
8855 :
8856 : bool SimplifiedByConstantRange = false;
8857 :
8858 : if (!ICmpInst::isEquality(Pred)) {
8859 : ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8860 : if (ExactCR.isFullSet())
8861 42 : return TrivialCase(true);
8862 : else if (ExactCR.isEmptySet())
8863 : return TrivialCase(false);
8864 :
8865 12673 : APInt NewRHS;
8866 : CmpInst::Predicate NewPred;
8867 : if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8868 : ICmpInst::isEquality(NewPred)) {
8869 : // We were able to convert an inequality to an equality.
8870 : Pred = NewPred;
8871 : RHS = getConstant(NewRHS);
8872 : Changed = SimplifiedByConstantRange = true;
8873 : }
8874 : }
8875 :
8876 : if (!SimplifiedByConstantRange) {
8877 32 : switch (Pred) {
8878 0 : default:
8879 : break;
8880 : case ICmpInst::ICMP_EQ:
8881 : case ICmpInst::ICMP_NE:
8882 12657 : // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8883 : if (!RA)
8884 12657 : if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8885 : if (const SCEVMulExpr *ME =
8886 : dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8887 : if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8888 480 : ME->getOperand(0)->isAllOnesValue()) {
8889 : RHS = AE->getOperand(1);
8890 12657 : LHS = ME->getOperand(1);
8891 4905 : Changed = true;
8892 : }
8893 : break;
8894 :
8895 7769 :
8896 : // The "Should have been caught earlier!" messages refer to the fact
8897 : // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8898 : // should have fired on the corresponding cases, and canonicalized the
8899 11 : // check to trivial case.
8900 2 :
8901 2 : case ICmpInst::ICMP_UGE:
8902 : assert(!RA.isMinValue() && "Should have been caught earlier!");
8903 9 : Pred = ICmpInst::ICMP_UGT;
8904 : RHS = getConstant(RA - 1);
8905 : Changed = true;
8906 : break;
8907 7741 : case ICmpInst::ICMP_ULE:
8908 6 : assert(!RA.isMaxValue() && "Should have been caught earlier!");
8909 : Pred = ICmpInst::ICMP_ULT;
8910 : RHS = getConstant(RA + 1);
8911 : Changed = true;
8912 : break;
8913 : case ICmpInst::ICMP_SGE:
8914 : assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8915 : Pred = ICmpInst::ICMP_SGT;
8916 : RHS = getConstant(RA - 1);
8917 : Changed = true;
8918 : break;
8919 : case ICmpInst::ICMP_SLE:
8920 : assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8921 : Pred = ICmpInst::ICMP_SLT;
8922 15470 : RHS = getConstant(RA + 1);
8923 15470 : Changed = true;
8924 : break;
8925 : }
8926 : }
8927 : }
8928 :
8929 : // Check for obvious equality.
8930 : if (HasSameValue(LHS, RHS)) {
8931 : if (ICmpInst::isTrueWhenEqual(Pred))
8932 15338 : return TrivialCase(true);
8933 69 : if (ICmpInst::isFalseWhenEqual(Pred))
8934 : return TrivialCase(false);
8935 : }
8936 :
8937 : // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
8938 : // adding or subtracting 1 from one of the operands.
8939 : switch (Pred) {
8940 7666 : case ICmpInst::ICMP_SLE:
8941 7666 : if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
8942 : RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8943 : SCEV::FlagNSW);
8944 : Pred = ICmpInst::ICMP_SLT;
8945 : Changed = true;
8946 19882 : } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
8947 : LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
8948 : SCEV::FlagNSW);
8949 : Pred = ICmpInst::ICMP_SLT;
8950 : Changed = true;
8951 : }
8952 : break;
8953 : case ICmpInst::ICMP_SGE:
8954 : if (!getSignedRangeMin(RHS).isMinSignedValue()) {
8955 : RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
8956 4182 : SCEV::FlagNSW);
8957 4182 : Pred = ICmpInst::ICMP_SGT;
8958 4182 : Changed = true;
8959 4182 : } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
8960 : LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8961 : SCEV::FlagNSW);
8962 2611 : Pred = ICmpInst::ICMP_SGT;
8963 7833 : Changed = true;
8964 : }
8965 4182 : break;
8966 : case ICmpInst::ICMP_ULE:
8967 : if (!getUnsignedRangeMax(RHS).isMaxValue()) {
8968 : RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
8969 : SCEV::FlagNUW);
8970 : Pred = ICmpInst::ICMP_ULT;
8971 : Changed = true;
8972 : } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
8973 5272 : LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
8974 1788 : Pred = ICmpInst::ICMP_ULT;
8975 : Changed = true;
8976 808 : }
8977 : break;
8978 808 : case ICmpInst::ICMP_UGE:
8979 808 : if (!getUnsignedRangeMin(RHS).isMinValue()) {
8980 808 : RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
8981 808 : Pred = ICmpInst::ICMP_UGT;
8982 : Changed = true;
8983 : } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
8984 : LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
8985 2676 : SCEV::FlagNUW);
8986 : Pred = ICmpInst::ICMP_UGT;
8987 2676 : Changed = true;
8988 2676 : }
8989 488 : break;
8990 2676 : default:
8991 : break;
8992 : }
8993 :
8994 1568 : // TODO: More simplifications are possible here.
8995 :
8996 : // Recursively simplify until we either hit a recursion limit or nothing
8997 : // changes.
8998 : if (Changed)
8999 : return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9000 :
9001 : return Changed;
9002 44 : }
9003 0 :
9004 22 : bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9005 : return getSignedRangeMax(S).isNegative();
9006 : }
9007 :
9008 : bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9009 1546 : return getSignedRangeMin(S).isStrictlyPositive();
9010 : }
9011 :
9012 : bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9013 63133 : return !getSignedRangeMin(S).isNegative();
9014 : }
9015 :
9016 : bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9017 63133 : return !getSignedRangeMax(S).isStrictlyPositive();
9018 33390 : }
9019 :
9020 : bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9021 : return isKnownNegative(S) || isKnownPositive(S);
9022 : }
9023 40042 :
9024 10299 : std::pair<const SCEV *, const SCEV *>
9025 : ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9026 19444 : // Compute SCEV on entry of loop L.
9027 : const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9028 : if (Start == getCouldNotCompute())
9029 : return { Start, Start };
9030 : // Compute post increment SCEV for loop L.
9031 : const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9032 : assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9033 581302 : return { Start, PostInc };
9034 : }
9035 581302 :
9036 : bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9037 : const SCEV *LHS, const SCEV *RHS) {
9038 : // First collect all loops.
9039 : SmallPtrSet<const Loop *, 8> LoopsUsed;
9040 : getUsedLoops(LHS, LoopsUsed);
9041 : getUsedLoops(RHS, LoopsUsed);
9042 :
9043 : if (LoopsUsed.empty())
9044 : return false;
9045 :
9046 88029 : // Domination relationship must be a linear order on collected loops.
9047 17234 : #ifndef NDEBUG
9048 : for (auto *L1 : LoopsUsed)
9049 : for (auto *L2 : LoopsUsed)
9050 10609 : assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9051 4 : DT.dominates(L2->getHeader(), L1->getHeader())) &&
9052 : "Domination relationship is not a linear order");
9053 : #endif
9054 :
9055 : const Loop *MDL =
9056 : *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9057 313243 : [&](const Loop *L1, const Loop *L2) {
9058 : return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9059 : });
9060 :
9061 : // Get init and post increment value for LHS.
9062 : auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9063 : // if LHS contains unknown non-invariant SCEV then bail out.
9064 : if (SplitLHS.first == getCouldNotCompute())
9065 : return false;
9066 : assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9067 313243 : // Get init and post increment value for RHS.
9068 : auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9069 313243 : // if RHS contains unknown non-invariant SCEV then bail out.
9070 : if (SplitRHS.first == getCouldNotCompute())
9071 : return false;
9072 : assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9073 313243 : // It is possible that init SCEV contains an invariant load but it does
9074 : // not dominate MDL and is not available at MDL loop entry, so we should
9075 27121 : // check it here.
9076 10396 : if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9077 10396 : !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9078 10396 : return false;
9079 8307 :
9080 : return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9081 2089 : isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9082 : SplitRHS.second);
9083 : }
9084 :
9085 16725 : bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9086 : const SCEV *LHS, const SCEV *RHS) {
9087 : // Canonicalize the inputs first.
9088 : (void)SimplifyICmpOperands(Pred, LHS, RHS);
9089 :
9090 : if (isKnownViaInduction(Pred, LHS, RHS))
9091 : return true;
9092 302847 :
9093 2178 : if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9094 2178 : return true;
9095 :
9096 361 : // Otherwise see what can be done with some simple reasoning.
9097 : return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9098 : }
9099 :
9100 : bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9101 : const SCEVAddRecExpr *LHS,
9102 : const SCEV *RHS) {
9103 302847 : const Loop *L = LHS->getLoop();
9104 : return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9105 : isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9106 : }
9107 :
9108 468202 : bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9109 285592 : ICmpInst::Predicate Pred,
9110 142848 : bool &Increasing) {
9111 104 : bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9112 142839 :
9113 95 : #ifndef NDEBUG
9114 : // Verify an invariant: inverting the predicate should turn a monotonically
9115 : // increasing change to a monotonically decreasing one, and vice versa.
9116 : bool IncreasingSwapped;
9117 142744 : bool ResultSwapped = isMonotonicPredicateImpl(
9118 142744 : LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9119 :
9120 27440 : assert(Result == ResultSwapped && "should be able to analyze both!");
9121 27440 : if (ResultSwapped)
9122 : assert(Increasing == !IncreasingSwapped &&
9123 : "monotonicity should flip as we flip the predicate");
9124 : #endif
9125 :
9126 233997 : return Result;
9127 206557 : }
9128 :
9129 : bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9130 : ICmpInst::Predicate Pred,
9131 : bool &Increasing) {
9132 :
9133 91253 : // A zero step value for LHS means the induction variable is essentially a
9134 41223 : // loop invariant value. We don't really depend on the predicate actually
9135 : // flipping from false to true (for increasing predicates, and the other way
9136 6283 : // around for decreasing predicates), all we care about is that *if* the
9137 2603 : // predicate changes then it only changes from false to true.
9138 2458 : //
9139 1146 : // A zero step value in itself is not very useful, but there may be places
9140 2292 : // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9141 : // as general as possible.
9142 :
9143 : switch (Pred) {
9144 : default:
9145 : return false; // Conservative answer
9146 :
9147 : case ICmpInst::ICMP_UGT:
9148 : case ICmpInst::ICMP_UGE:
9149 : case ICmpInst::ICMP_ULT:
9150 : case ICmpInst::ICMP_ULE:
9151 4522 : if (!LHS->hasNoUnsignedWrap())
9152 : return false;
9153 4522 :
9154 4522 : Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9155 : return true;
9156 4522 :
9157 2320 : case ICmpInst::ICMP_SGT:
9158 : case ICmpInst::ICMP_SGE:
9159 2320 : case ICmpInst::ICMP_SLT:
9160 2320 : case ICmpInst::ICMP_SLE: {
9161 : if (!LHS->hasNoSignedWrap())
9162 2320 : return false;
9163 10923 :
9164 : const SCEV *Step = LHS->getStepRecurrence(*this);
9165 10923 :
9166 10923 : if (isKnownNonNegative(Step)) {
9167 : Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9168 10923 : return true;
9169 5614 : }
9170 :
9171 5614 : if (isKnownNonPositive(Step)) {
9172 5614 : Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9173 : return true;
9174 5614 : }
9175 :
9176 : return false;
9177 : }
9178 :
9179 : }
9180 302743 :
9181 226 : llvm_unreachable("switch has default clause!");
9182 198 : }
9183 28 :
9184 28 : bool ScalarEvolution::isLoopInvariantPredicate(
9185 : ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9186 : ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9187 : const SCEV *&InvariantRHS) {
9188 :
9189 302517 : // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9190 1959 : if (!isLoopInvariant(RHS, L)) {
9191 3918 : if (!isLoopInvariant(LHS, L))
9192 423 : return false;
9193 :
9194 423 : std::swap(LHS, RHS);
9195 : Pred = ICmpInst::getSwappedPredicate(Pred);
9196 3072 : }
9197 134 :
9198 : const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9199 134 : if (!ArLHS || ArLHS->getLoop() != L)
9200 : return false;
9201 :
9202 : bool Increasing;
9203 3445 : if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9204 6890 : return false;
9205 850 :
9206 : // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9207 850 : // true as the loop iterates, and the backedge is control dependent on
9208 : // "ArLHS `Pred` RHS" == true then we can reason as follows:
9209 5190 : //
9210 210 : // * if the predicate was false in the first iteration then the predicate
9211 : // is never evaluated again, since the loop exits without taking the
9212 210 : // backedge.
9213 : // * if the predicate was true in the first iteration then it will
9214 : // continue to be true for all future iterations since it is
9215 : // monotonically increasing.
9216 1702 : //
9217 3404 : // For both the above possibilities, we can replace the loop varying
9218 457 : // predicate with its value on the first iteration of the loop (which is
9219 : // loop invariant).
9220 457 : //
9221 : // A similar reasoning applies for a monotonically decreasing predicate, by
9222 2490 : // replacing true with false and false with true in the above two bullets.
9223 48 :
9224 48 : auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9225 :
9226 : if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9227 : return false;
9228 3385 :
9229 6770 : InvariantPred = Pred;
9230 194 : InvariantLHS = ArLHS->getStart();
9231 194 : InvariantRHS = RHS;
9232 : return true;
9233 6382 : }
9234 891 :
9235 : bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9236 891 : ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9237 : if (HasSameValue(LHS, RHS))
9238 : return ICmpInst::isTrueWhenEqual(Pred);
9239 :
9240 : // This code is split out from isKnownPredicate because it is called from
9241 : // within isLoopEntryGuardedByCond.
9242 :
9243 : auto CheckRanges =
9244 : [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9245 : return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9246 : .contains(RangeLHS);
9247 : };
9248 299310 :
9249 62905 : // The check at the top of the function catches the case where the values are
9250 : // known to be equal.
9251 : if (Pred == CmpInst::ICMP_EQ)
9252 : return false;
9253 :
9254 39390 : if (Pred == CmpInst::ICMP_NE)
9255 39390 : return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9256 : CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9257 : isKnownNonZero(getMinusSCEV(LHS, RHS));
9258 64863 :
9259 64863 : if (CmpInst::isSigned(Pred))
9260 : return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9261 :
9262 1541314 : return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9263 1605557 : }
9264 :
9265 : bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9266 147473 : const SCEV *LHS,
9267 147473 : const SCEV *RHS) {
9268 : // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9269 : // Return Y via OutY.
9270 22755 : auto MatchBinaryAddToConst =
9271 22755 : [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9272 : SCEV::NoWrapFlags ExpectedFlags) {
9273 : const SCEV *NonConstOp, *ConstOp;
9274 : SCEV::NoWrapFlags FlagsPresent;
9275 31206 :
9276 : if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9277 31206 : !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9278 31206 : return false;
9279 1241 :
9280 : OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9281 29965 : return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9282 : };
9283 29965 :
9284 : APInt C;
9285 :
9286 33486 : switch (Pred) {
9287 : default:
9288 : break;
9289 :
9290 33486 : case ICmpInst::ICMP_SGE:
9291 33486 : std::swap(LHS, RHS);
9292 : LLVM_FALLTHROUGH;
9293 33486 : case ICmpInst::ICMP_SLE:
9294 : // X s<= (X + C)<nsw> if C >= 0
9295 : if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9296 : return true;
9297 :
9298 : // (X + C)<nsw> s<= X if C <= 0
9299 : if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9300 : !C.isStrictlyPositive())
9301 : return true;
9302 : break;
9303 :
9304 : case ICmpInst::ICMP_SGT:
9305 : std::swap(LHS, RHS);
9306 : LLVM_FALLTHROUGH;
9307 : case ICmpInst::ICMP_SLT:
9308 0 : // X s< (X + C)<nsw> if C > 0
9309 15701 : if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9310 : C.isStrictlyPositive())
9311 : return true;
9312 15701 :
9313 : // (X + C)<nsw> s< X if C < 0
9314 15701 : if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9315 : return true;
9316 : break;
9317 : }
9318 15505 :
9319 : return false;
9320 15505 : }
9321 :
9322 : bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9323 : const SCEV *LHS,
9324 : const SCEV *RHS) {
9325 : if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9326 28920 : return false;
9327 14460 :
9328 0 : // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9329 : // the stack can result in exponential time complexity.
9330 20206 : SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9331 5746 :
9332 : // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9333 : //
9334 : // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9335 33486 : // isKnownPredicate. isKnownPredicate is more powerful, but also more
9336 : // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9337 : // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9338 33486 : // use isKnownPredicate later if needed.
9339 : return isKnownNonNegative(RHS) &&
9340 33486 : isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9341 : isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9342 : }
9343 31539 :
9344 : bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9345 : ICmpInst::Predicate Pred,
9346 : const SCEV *LHS, const SCEV *RHS) {
9347 31537 : // No need to even try if we know the module has no guards.
9348 : if (!HasGuards)
9349 : return false;
9350 12126 :
9351 : return any_of(*BB, [&](Instruction &I) {
9352 : using namespace llvm::PatternMatch;
9353 12126 :
9354 29882 : Value *Condition;
9355 5630 : return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9356 : m_Value(Condition))) &&
9357 : isImpliedCond(Pred, LHS, RHS, Condition, false);
9358 802 : });
9359 : }
9360 :
9361 802 : /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9362 : /// protected by a conditional between LHS and RHS. This is used to
9363 : /// to eliminate casts.
9364 : bool
9365 : ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9366 : ICmpInst::Predicate Pred,
9367 : const SCEV *LHS, const SCEV *RHS) {
9368 : // Interpret a null as meaning no loop, where there is obviously no guard
9369 : // (interprocedural conditions notwithstanding).
9370 : if (!L) return true;
9371 :
9372 : if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9373 : return true;
9374 :
9375 : BasicBlock *Latch = L->getLoopLatch();
9376 802 : if (!Latch)
9377 : return false;
9378 :
9379 802 : BranchInst *LoopContinuePredicate =
9380 : dyn_cast<BranchInst>(Latch->getTerminator());
9381 : if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9382 : isImpliedCond(Pred, LHS, RHS,
9383 : LoopContinuePredicate->getCondition(),
9384 : LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9385 : return true;
9386 :
9387 : // We don't want more than one activation of the following loops on the stack
9388 : // -- that can lead to O(n!) time complexity.
9389 : if (WalkingBEDominatingConds)
9390 : return false;
9391 :
9392 : SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9393 802 :
9394 : // See if we can exploit a trip count to prove the predicate.
9395 : const auto &BETakenInfo = getBackedgeTakenInfo(L);
9396 : const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9397 274 : if (LatchBECount != getCouldNotCompute()) {
9398 : // We know that Latch branches back to the loop header exactly
9399 : // LatchBECount times. This means the backdege condition at Latch is
9400 : // equivalent to "{0,+,1} u< LatchBECount".
9401 274 : Type *Ty = LatchBECount->getType();
9402 : auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9403 : const SCEV *LoopCounter =
9404 181 : getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9405 181 : if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9406 : LatchBECount))
9407 120 : return true;
9408 : }
9409 :
9410 : // Check conditions due to any @llvm.assume intrinsics.
9411 120 : for (auto &AssumeVH : AC.assumptions()) {
9412 : if (!AssumeVH)
9413 : continue;
9414 107 : auto *CI = cast<CallInst>(AssumeVH);
9415 : if (!DT.dominates(CI, Latch->getTerminator()))
9416 107 : continue;
9417 74 :
9418 74 : if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9419 : return true;
9420 : }
9421 33 :
9422 31 : // If the loop is not reachable from the entry block, we risk running into an
9423 31 : // infinite loop as we walk up into the dom tree. These loops do not matter
9424 : // anyway, so we just return a conservative answer when we see them.
9425 : if (!DT.isReachableFromEntry(L->getHeader()))
9426 : return false;
9427 :
9428 : if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9429 : return true;
9430 :
9431 : for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9432 : DTN != HeaderDTN; DTN = DTN->getIDom()) {
9433 : assert(DTN && "should reach the loop header before reaching the root!");
9434 1541 :
9435 : BasicBlock *BB = DTN->getBlock();
9436 : if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9437 : return true;
9438 :
9439 : BasicBlock *PBB = BB->getSinglePredecessor();
9440 1541 : if (!PBB)
9441 517 : continue;
9442 :
9443 : BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9444 : if (!ContinuePredicate || !ContinuePredicate->isConditional())
9445 1 : continue;
9446 :
9447 : Value *Condition = ContinuePredicate->getCondition();
9448 :
9449 723 : // If we have an edge `E` within the loop body that dominates the only
9450 : // latch, the condition guarding `E` also guards the backedge. This
9451 : // reasoning works only for loops with a single latch.
9452 :
9453 723 : BasicBlockEdge DominatingEdge(PBB, BB);
9454 : if (DominatingEdge.isSingleEdge()) {
9455 : // We're constructively (and conservatively) enumerating edges within the
9456 : // loop body that dominate the latch. The dominator tree better agree
9457 : // with us on this:
9458 : assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9459 :
9460 : if (isImpliedCond(Pred, LHS, RHS, Condition,
9461 : BB != ContinuePredicate->getSuccessor(0)))
9462 : return true;
9463 : }
9464 : }
9465 :
9466 : return false;
9467 : }
9468 :
9469 : bool
9470 : ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9471 : ICmpInst::Predicate Pred,
9472 : const SCEV *LHS, const SCEV *RHS) {
9473 : // Interpret a null as meaning no loop, where there is obviously no guard
9474 272 : // (interprocedural conditions notwithstanding).
9475 : if (!L) return false;
9476 272 :
9477 : // Both LHS and RHS must be available at loop entry.
9478 : assert(isAvailableAtLoopEntry(LHS, L) &&
9479 11 : "LHS is not available at Loop Entry");
9480 11 : assert(isAvailableAtLoopEntry(RHS, L) &&
9481 11 : "RHS is not available at Loop Entry");
9482 11 :
9483 : if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9484 : return true;
9485 241108 :
9486 : // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9487 241108 : // the facts (a >= b && a != b) separately. A typical situation is when the
9488 18095 : // non-strict comparison is known from ranges and non-equality is known from
9489 : // dominating predicates. If we are proving strict comparison, we always try
9490 : // to prove non-equality and non-strict comparison separately.
9491 : auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9492 : const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9493 : bool ProvedNonStrictComparison = false;
9494 : bool ProvedNonEquality = false;
9495 :
9496 : if (ProvingStrictComparison) {
9497 : ProvedNonStrictComparison =
9498 : isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9499 : ProvedNonEquality =
9500 : isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9501 223013 : if (ProvedNonStrictComparison && ProvedNonEquality)
9502 : return true;
9503 : }
9504 217331 :
9505 74714 : // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9506 71799 : auto ProveViaGuard = [&](BasicBlock *Block) {
9507 22719 : if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9508 : return true;
9509 191388 : if (ProvingStrictComparison) {
9510 92477 : if (!ProvedNonStrictComparison)
9511 : ProvedNonStrictComparison =
9512 98911 : isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9513 : if (!ProvedNonEquality)
9514 : ProvedNonEquality =
9515 188975 : isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9516 : if (ProvedNonStrictComparison && ProvedNonEquality)
9517 : return true;
9518 : }
9519 : return false;
9520 : };
9521 :
9522 : // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9523 : auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9524 : if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9525 : return true;
9526 : if (ProvingStrictComparison) {
9527 : if (!ProvedNonStrictComparison)
9528 : ProvedNonStrictComparison =
9529 : isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9530 : if (!ProvedNonEquality)
9531 : ProvedNonEquality =
9532 : isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9533 : if (ProvedNonStrictComparison && ProvedNonEquality)
9534 : return true;
9535 : }
9536 188975 : return false;
9537 : };
9538 :
9539 : // Starting at the loop predecessor, climb up the predecessor chain, as long
9540 : // as there are predecessors that can be found that have unique successors
9541 : // leading to the original header.
9542 : for (std::pair<BasicBlock *, BasicBlock *>
9543 41270 : Pair(L->getLoopPredecessor(), L->getHeader());
9544 : Pair.first;
9545 41482 : Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9546 :
9547 : if (ProveViaGuard(Pair.first))
9548 : return true;
9549 41176 :
9550 166 : BranchInst *LoopEntryPredicate =
9551 106 : dyn_cast<BranchInst>(Pair.first->getTerminator());
9552 : if (!LoopEntryPredicate ||
9553 : LoopEntryPredicate->isUnconditional())
9554 : continue;
9555 :
9556 : if (ProveViaCond(LoopEntryPredicate->getCondition(),
9557 37706 : LoopEntryPredicate->getSuccessor(0) != Pair.second))
9558 : return true;
9559 37706 : }
9560 2 :
9561 : // Check conditions due to any @llvm.assume intrinsics.
9562 : for (auto &AssumeVH : AC.assumptions()) {
9563 : if (!AssumeVH)
9564 37704 : continue;
9565 0 : auto *CI = cast<CallInst>(AssumeVH);
9566 : if (!DT.dominates(CI, L->getHeader()))
9567 : continue;
9568 :
9569 : if (ProveViaCond(CI->getArgOperand(0), false))
9570 : return true;
9571 : }
9572 31539 :
9573 : return false;
9574 : }
9575 31539 :
9576 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9577 : const SCEV *LHS, const SCEV *RHS,
9578 : Value *FoundCondValue,
9579 : bool Inverse) {
9580 2259 : if (!PendingLoopPredicates.insert(FoundCondValue).second)
9581 : return false;
9582 :
9583 : auto ClearOnExit =
9584 : make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9585 :
9586 : // Recursively handle And and Or conditions.
9587 : if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9588 : if (BO->getOpcode() == Instruction::And) {
9589 3768 : if (!Inverse)
9590 5115 : return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9591 1347 : isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9592 : } else if (BO->getOpcode() == Instruction::Or) {
9593 : if (Inverse)
9594 175344 : return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9595 : isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9596 : }
9597 : }
9598 175344 :
9599 : ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9600 : if (!ICI) return false;
9601 1565 :
9602 : // Now that we found a conditional branch that dominates the loop or controls
9603 : // the loop latch. Check to see if it is the comparison we are looking for.
9604 : ICmpInst::Predicate FoundPred;
9605 : if (Inverse)
9606 : FoundPred = ICI->getInversePredicate();
9607 : else
9608 1565 : FoundPred = ICI->getPredicate();
9609 :
9610 : const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9611 : const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9612 :
9613 : return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9614 : }
9615 34126 :
9616 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9617 : const SCEV *RHS,
9618 : ICmpInst::Predicate FoundPred,
9619 : const SCEV *FoundLHS,
9620 34126 : const SCEV *FoundRHS) {
9621 : // Balance the types.
9622 34126 : if (getTypeSizeInBits(LHS->getType()) <
9623 : getTypeSizeInBits(FoundLHS->getType())) {
9624 : if (CmpInst::isSigned(Pred)) {
9625 22473 : LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9626 22473 : RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9627 : } else {
9628 : LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9629 : RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9630 : }
9631 43163 : } else if (getTypeSizeInBits(LHS->getType()) >
9632 41668 : getTypeSizeInBits(FoundLHS->getType())) {
9633 : if (CmpInst::isSigned(FoundPred)) {
9634 : FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9635 : FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9636 : } else {
9637 : FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9638 : FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9639 21689 : }
9640 : }
9641 :
9642 19161 : // Canonicalize the query to match the way instcombine will have
9643 : // canonicalized the comparison.
9644 : if (SimplifyICmpOperands(Pred, LHS, RHS))
9645 19161 : if (LHS == RHS)
9646 19161 : return CmpInst::isTrueWhenEqual(Pred);
9647 19161 : if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9648 : if (FoundLHS == FoundRHS)
9649 : return CmpInst::isFalseWhenEqual(FoundPred);
9650 :
9651 16074 : // Check to see if we can make the LHS or RHS match.
9652 : if (LHS == FoundRHS || RHS == FoundLHS) {
9653 : if (isa<SCEVConstant>(RHS)) {
9654 16074 : std::swap(FoundLHS, FoundRHS);
9655 16074 : FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9656 : } else {
9657 : std::swap(LHS, RHS);
9658 : Pred = ICmpInst::getSwappedPredicate(Pred);
9659 : }
9660 : }
9661 41739 :
9662 3479 : // Check whether the found predicate is the same as the desired predicate.
9663 : if (FoundPred == Pred)
9664 : return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9665 6958 :
9666 : // Check whether swapping the found predicate makes it the same as the
9667 : // desired predicate.
9668 3479 : if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9669 : if (isa<SCEVConstant>(RHS))
9670 : return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9671 : else
9672 : return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9673 : RHS, LHS, FoundLHS, FoundRHS);
9674 : }
9675 38258 :
9676 : // Unsigned comparison is the same as signed comparison when both the operands
9677 : // are non-negative.
9678 19129 : if (CmpInst::isUnsigned(FoundPred) &&
9679 : CmpInst::getSignedPredicate(FoundPred) == Pred &&
9680 : isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9681 38232 : return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9682 42443 :
9683 : // Check if we can make progress by sharpening ranges.
9684 : if (FoundPred == ICmpInst::ICMP_NE &&
9685 23405 : (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9686 23405 :
9687 78 : const SCEVConstant *C = nullptr;
9688 : const SCEV *V = nullptr;
9689 :
9690 23405 : if (isa<SCEVConstant>(FoundLHS)) {
9691 17378 : C = cast<SCEVConstant>(FoundLHS);
9692 : V = FoundRHS;
9693 : } else {
9694 7073 : C = cast<SCEVConstant>(FoundRHS);
9695 : V = FoundLHS;
9696 : }
9697 :
9698 : // The guarding predicate tells us that C != V. If the known range
9699 : // of V is [C, t), we can sharpen the range to [C + 1, t). The
9700 : // range we consider has to correspond to same signedness as the
9701 : // predicate we're interested in folding.
9702 :
9703 : APInt Min = ICmpInst::isSigned(Pred) ?
9704 6027 : getSignedRangeMin(V) : getUnsignedRangeMin(V);
9705 :
9706 : if (Min == C->getAPInt()) {
9707 : // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9708 : // This is true even if (Min + 1) wraps around -- in case of
9709 : // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9710 6027 :
9711 : APInt SharperMin = Min + 1;
9712 :
9713 : switch (Pred) {
9714 : case ICmpInst::ICMP_SGE:
9715 : case ICmpInst::ICMP_UGE:
9716 : // We know V `Pred` SharperMin. If this implies LHS `Pred`
9717 : // RHS, we're done.
9718 : if (isImpliedCondOperands(Pred, LHS, RHS, V,
9719 : getConstant(SharperMin)))
9720 35774 : return true;
9721 : LLVM_FALLTHROUGH;
9722 :
9723 : case ICmpInst::ICMP_SGT:
9724 : case ICmpInst::ICMP_UGT:
9725 35774 : // We know from the range information that (V `Pred` Min ||
9726 : // V == Min). We know from the guarding condition that !(V
9727 : // == Min). This gives us
9728 : //
9729 : // V `Pred` Min || V == Min && !(V == Min)
9730 : // => V `Pred` Min
9731 : //
9732 : // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9733 35774 :
9734 : if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9735 : return true;
9736 : LLVM_FALLTHROUGH;
9737 :
9738 : default:
9739 : // No change
9740 : break;
9741 24281 : }
9742 24281 : }
9743 24281 : }
9744 24281 :
9745 : // Check whether the actual condition is beyond sufficient.
9746 24281 : if (FoundPred == ICmpInst::ICMP_EQ)
9747 15786 : if (ICmpInst::isTrueWhenEqual(Pred))
9748 15786 : if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9749 15786 : return true;
9750 15786 : if (Pred == ICmpInst::ICMP_NE)
9751 15786 : if (!ICmpInst::isTrueWhenEqual(FoundPred))
9752 : if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9753 : return true;
9754 :
9755 : // Otherwise assume the worst.
9756 : return false;
9757 : }
9758 :
9759 : bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9760 : const SCEV *&L, const SCEV *&R,
9761 : SCEV::NoWrapFlags &Flags) {
9762 : const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9763 : if (!AE || AE->getNumOperands() != 2)
9764 : return false;
9765 :
9766 : L = AE->getOperand(0);
9767 : R = AE->getOperand(1);
9768 : Flags = AE->getNoWrapFlags();
9769 : return true;
9770 24281 : }
9771 :
9772 : Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9773 : const SCEV *Less) {
9774 : // We avoid subtracting expressions here because this function is usually
9775 : // fairly deep in the call stack (i.e. is called many times).
9776 :
9777 : if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9778 : const auto *LAR = cast<SCEVAddRecExpr>(Less);
9779 : const auto *MAR = cast<SCEVAddRecExpr>(More);
9780 :
9781 : if (LAR->getLoop() != MAR->getLoop())
9782 : return None;
9783 :
9784 : // We look at affine expressions only; not for correctness but to keep
9785 : // getStepRecurrence cheap.
9786 : if (!LAR->isAffine() || !MAR->isAffine())
9787 24281 : return None;
9788 :
9789 : if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9790 : return None;
9791 :
9792 63133 : Less = LAR->getStart();
9793 24281 : More = MAR->getStart();
9794 87414 :
9795 63133 : // fall through
9796 : }
9797 67966 :
9798 : if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9799 : const auto &M = cast<SCEVConstant>(More)->getAPInt();
9800 : const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9801 : return M - L;
9802 64229 : }
9803 :
9804 : SCEV::NoWrapFlags Flags;
9805 : const SCEV *LLess = nullptr, *RLess = nullptr;
9806 59468 : const SCEV *LMore = nullptr, *RMore = nullptr;
9807 : const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9808 : // Compare (X + C1) vs X.
9809 : if (splitBinaryAdd(Less, LLess, RLess, Flags))
9810 : if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9811 : if (RLess == More)
9812 48681 : return -(C1->getAPInt());
9813 9794 :
9814 : // Compare X vs (X + C2).
9815 : if (splitBinaryAdd(More, LMore, RMore, Flags))
9816 19588 : if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9817 : if (RMore == Less)
9818 : return C2->getAPInt();
9819 41 :
9820 : // Compare (X + C1) vs (X + C2).
9821 : if (C1 && C2 && RLess == RMore)
9822 : return C2->getAPInt() - C1->getAPInt();
9823 :
9824 : return None;
9825 : }
9826 86543 :
9827 : bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9828 : ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9829 : const SCEV *FoundLHS, const SCEV *FoundRHS) {
9830 86543 : if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9831 : return false;
9832 :
9833 : const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9834 83109 : if (!AddRecLHS)
9835 : return false;
9836 :
9837 : const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9838 1866 : if (!AddRecFoundLHS)
9839 1339 : return false;
9840 2077 :
9841 950 : // We'd like to let SCEV reason about control dependencies, so we constrain
9842 527 : // both the inequalities to be about add recurrences on the same loop. This
9843 483 : // way we can use isLoopEntryGuardedByCond later.
9844 547 :
9845 259 : const Loop *L = AddRecFoundLHS->getLoop();
9846 : if (L != AddRecLHS->getLoop())
9847 : return false;
9848 :
9849 : // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
9850 : //
9851 : // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9852 : // ... (2)
9853 : //
9854 : // Informal proof for (2), assuming (1) [*]:
9855 78709 : //
9856 : // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9857 : //
9858 : // Then
9859 : //
9860 78709 : // FoundLHS s< FoundRHS s< INT_MIN - C
9861 78709 : // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
9862 : // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9863 78709 : // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
9864 : // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9865 : // <=> FoundLHS + C s< FoundRHS + C
9866 94783 : //
9867 : // [*]: (1) can be proved by ruling out overflow.
9868 : //
9869 : // [**]: This can be proved by analyzing all the four possibilities:
9870 : // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9871 : // (A s>= 0, B s>= 0).
9872 189566 : //
9873 94783 : // Note:
9874 11820 : // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9875 2096 : // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
9876 2096 : // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
9877 : // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
9878 9724 : // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9879 9724 : // C)".
9880 :
9881 165926 : Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9882 82963 : Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9883 10540 : if (!LDiff || !RDiff || *LDiff != *RDiff)
9884 3702 : return false;
9885 3702 :
9886 : if (LDiff->isMinValue())
9887 6838 : return true;
9888 6838 :
9889 : APInt FoundRHSLimit;
9890 :
9891 : if (Pred == CmpInst::ICMP_ULT) {
9892 : FoundRHSLimit = -(*RDiff);
9893 : } else {
9894 94783 : assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9895 3755 : FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9896 3755 : }
9897 91028 :
9898 52 : // Try to prove (1) or (2), as needed.
9899 52 : return isAvailableAtLoopEntry(FoundRHS, L) &&
9900 : isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9901 : getConstant(FoundRHSLimit));
9902 90976 : }
9903 1616 :
9904 : bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9905 417 : const SCEV *LHS, const SCEV *RHS,
9906 : const SCEV *FoundLHS,
9907 : const SCEV *FoundRHS, unsigned Depth) {
9908 391 : const PHINode *LPhi = nullptr, *RPhi = nullptr;
9909 :
9910 : auto ClearOnExit = make_scope_exit([&]() {
9911 : if (LPhi) {
9912 : bool Erased = PendingMerges.erase(LPhi);
9913 90976 : assert(Erased && "Failed to erase LPhi!");
9914 28709 : (void)Erased;
9915 : }
9916 : if (RPhi) {
9917 : bool Erased = PendingMerges.erase(RPhi);
9918 62267 : assert(Erased && "Failed to erase RPhi!");
9919 10502 : (void)Erased;
9920 4898 : }
9921 : });
9922 353 :
9923 353 : // Find respective Phis and check that they are not being pending.
9924 : if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
9925 : if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
9926 : if (!PendingMerges.insert(Phi).second)
9927 : return false;
9928 57016 : LPhi = Phi;
9929 29563 : }
9930 65579 : if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
9931 3173 : if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
9932 : // If we detect a loop of Phi nodes being processed by this method, for
9933 : // example:
9934 53843 : //
9935 14325 : // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
9936 : // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
9937 : //
9938 : // we don't want to deal with a case that complex, so return conservative
9939 : // answer false.
9940 10062 : if (!PendingMerges.insert(Phi).second)
9941 : return false;
9942 0 : RPhi = Phi;
9943 : }
9944 10062 :
9945 : // If none of LHS, RHS is a Phi, nothing to do here.
9946 : if (!LPhi && !RPhi)
9947 : return false;
9948 :
9949 : // If there is a SCEVUnknown Phi we are interested in, make it left.
9950 : if (!LPhi) {
9951 : std::swap(LHS, RHS);
9952 : std::swap(FoundLHS, FoundRHS);
9953 10062 : std::swap(LPhi, RPhi);
9954 10062 : Pred = ICmpInst::getSwappedPredicate(Pred);
9955 : }
9956 10062 :
9957 : assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
9958 : const BasicBlock *LBB = LPhi->getParent();
9959 : const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
9960 :
9961 4092 : auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
9962 : return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
9963 4092 : isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
9964 52 : isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
9965 : };
9966 :
9967 : if (RPhi && RPhi->getParent() == LBB) {
9968 52 : // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
9969 : // If we compare two Phis from the same block, and for each entry block
9970 : // the predicate is true for incoming values from this block, then the
9971 : // predicate is also true for the Phis.
9972 : for (const BasicBlock *IncBB : predecessors(LBB)) {
9973 : const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
9974 : const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
9975 : if (!ProvedEasily(L, R))
9976 : return false;
9977 : }
9978 : } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
9979 : // Case two: RHS is also a Phi from the same basic block, and it is an
9980 : // AddRec. It means that there is a loop which has both AddRec and Unknown
9981 : // PHIs, for it we can compare incoming values of AddRec from above the loop
9982 : // and latch with their respective incoming values of LPhi.
9983 : // TODO: Generalize to handle loops with many inputs in a header.
9984 1526 : if (LPhi->getNumIncomingValues() != 2) return false;
9985 :
9986 : auto *RLoop = RAR->getLoop();
9987 : auto *Predecessor = RLoop->getLoopPredecessor();
9988 : assert(Predecessor && "Loop with AddRec with no predecessor?");
9989 : const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
9990 : if (!ProvedEasily(L1, RAR->getStart()))
9991 : return false;
9992 : auto *Latch = RLoop->getLoopLatch();
9993 : assert(Latch && "Loop with AddRec with no latch?");
9994 : const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
9995 : if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
9996 53782 : return false;
9997 7483 : } else {
9998 12 : // In all other cases go over inputs of LHS and compare each of them to RHS,
9999 : // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10000 53782 : // At this point RHS is either a non-Phi, or it is a Phi from some block
10001 29402 : // different from LBB.
10002 23584 : for (const BasicBlock *IncBB : predecessors(LBB)) {
10003 1975 : // Check that RHS is available in this block.
10004 : if (!dominates(RHS, IncBB))
10005 : return false;
10006 : const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10007 : if (!ProvedEasily(L, RHS))
10008 : return false;
10009 237559 : }
10010 : }
10011 : return true;
10012 : }
10013 54702 :
10014 : bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10015 : const SCEV *LHS, const SCEV *RHS,
10016 92272 : const SCEV *FoundLHS,
10017 46136 : const SCEV *FoundRHS) {
10018 46136 : if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10019 46136 : return true;
10020 :
10021 : if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10022 71130 : return true;
10023 :
10024 : return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10025 : FoundLHS, FoundRHS) ||
10026 : // ~x < ~y --> x > y
10027 71130 : isImpliedCondOperandsHelper(Pred, LHS, RHS,
10028 : getNotSCEV(FoundRHS),
10029 : getNotSCEV(FoundLHS));
10030 : }
10031 30770 :
10032 : /// If Expr computes ~A, return A else return nullptr
10033 : static const SCEV *MatchNotExpr(const SCEV *Expr) {
10034 : const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
10035 : if (!Add || Add->getNumOperands() != 2 ||
10036 30682 : !Add->getOperand(0)->isAllOnesValue())
10037 : return nullptr;
10038 :
10039 30656 : const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
10040 : if (!AddRHS || AddRHS->getNumOperands() != 2 ||
10041 : !AddRHS->getOperand(0)->isAllOnesValue())
10042 24388 : return nullptr;
10043 24388 :
10044 : return AddRHS->getOperand(1);
10045 : }
10046 :
10047 : /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
10048 64748 : template<typename MaxExprType>
10049 : static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
10050 : const SCEV *Candidate) {
10051 24489 : const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
10052 : if (!MaxExpr) return false;
10053 :
10054 : return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
10055 40259 : }
10056 40259 :
10057 : /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
10058 : template<typename MaxExprType>
10059 40259 : static bool IsMinConsistingOf(ScalarEvolution &SE,
10060 9274 : const SCEV *MaybeMinExpr,
10061 7374 : const SCEV *Candidate) {
10062 815 : const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
10063 : if (!MaybeMaxExpr)
10064 : return false;
10065 39444 :
10066 11731 : return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
10067 11041 : }
10068 :
10069 : static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10070 : ICmpInst::Predicate Pred,
10071 37284 : const SCEV *LHS, const SCEV *RHS) {
10072 1798 : // If both sides are affine addrecs for the same loop, with equal
10073 |