LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
185 cl::init(2));
186
188 "scalar-evolution-max-value-compare-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive value complexity comparisons"),
190 cl::init(2));
191
193 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive arithmetics"),
195 cl::init(32));
196
198 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
200
202 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
204 cl::init(8));
205
207 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
208 cl::desc("Max coefficients in AddRec during evolving"),
209 cl::init(8));
210
212 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
213 cl::desc("Size of the expression which is considered huge"),
214 cl::init(4096));
215
217 "scev-range-iter-threshold", cl::Hidden,
218 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
219 cl::init(32));
220
222 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
223 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
224
225static cl::opt<bool>
226ClassifyExpressions("scalar-evolution-classify-expressions",
227 cl::Hidden, cl::init(true),
228 cl::desc("When printing analysis, include information on every instruction"));
229
231 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
232 cl::init(false),
233 cl::desc("Use more powerful methods of sharpening expression ranges. May "
234 "be costly in terms of compile time"));
235
236static cl::opt<bool>
237 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
238 cl::desc("Handle <= and >= in finite loops"),
239 cl::init(true));
240
242 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
243 cl::desc("Infer nuw/nsw flags using context where suitable"),
244 cl::init(true));
245
246//===----------------------------------------------------------------------===//
247// SCEV class definitions
248//===----------------------------------------------------------------------===//
249
251 // Leaf nodes are always their own canonical.
252 switch (getSCEVType()) {
253 case scConstant:
254 case scVScale:
255 case scUnknown:
256 CanonicalSCEV = this;
257 return;
258 default:
259 break;
260 }
261
262 // For all other expressions, check whether any immediate operand has a
263 // different canonical. Since operands are always created before their parent,
264 // their canonical pointers are already set — no recursion needed.
265 if (all_of(operands(), [](SCEVUse Op) { return Op.isCanonical(); })) {
266 CanonicalSCEV = this;
267 return;
268 }
269
271 map_range(operands(), [](SCEVUse Op) { return Op.getCanonical(); }));
272 // Rebuild the expression from the canonical operands, stripping use flags.
273 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
274}
275
276//===----------------------------------------------------------------------===//
277// Implementation of the SCEV class.
278//
279
280#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
282 print(dbgs());
283 dbgs() << '\n';
284}
285#endif
286
287void SCEV::print(raw_ostream &OS) const {
288 switch (getSCEVType()) {
289 case scConstant:
290 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
291 return;
292 case scVScale:
293 OS << "vscale";
294 return;
295 case scPtrToAddr: {
296 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
297 SCEVUse Op = PtrCast->getOperand();
298 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
299 << *PtrCast->getType() << ")";
300 return;
301 }
302 case scTruncate: {
303 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
304 SCEVUse Op = Trunc->getOperand();
305 OS << "(trunc " << *Op->getType() << " " << Op << " to "
306 << *Trunc->getType() << ")";
307 return;
308 }
309 case scZeroExtend: {
311 SCEVUse Op = ZExt->getOperand();
312 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
313 << ")";
314 return;
315 }
316 case scSignExtend: {
318 SCEVUse Op = SExt->getOperand();
319 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
320 << ")";
321 return;
322 }
323 case scAddRecExpr: {
324 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
325 OS << "{" << AR->getOperand(0);
326 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
327 OS << ",+," << AR->getOperand(i);
328 OS << "}<";
329 if (AR->hasNoUnsignedWrap())
330 OS << "nuw><";
331 if (AR->hasNoSignedWrap())
332 OS << "nsw><";
333 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
334 !AR->hasNoSignedWrap())
335 OS << "nw><";
336 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
337 OS << ">";
338 return;
339 }
340 case scAddExpr:
341 case scMulExpr:
342 case scUMaxExpr:
343 case scSMaxExpr:
344 case scUMinExpr:
345 case scSMinExpr:
347 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
348 const char *OpStr = nullptr;
349 switch (NAry->getSCEVType()) {
350 case scAddExpr: OpStr = " + "; break;
351 case scMulExpr: OpStr = " * "; break;
352 case scUMaxExpr: OpStr = " umax "; break;
353 case scSMaxExpr: OpStr = " smax "; break;
354 case scUMinExpr:
355 OpStr = " umin ";
356 break;
357 case scSMinExpr:
358 OpStr = " smin ";
359 break;
361 OpStr = " umin_seq ";
362 break;
363 default:
364 llvm_unreachable("There are no other nary expression types.");
365 }
366 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
367 switch (NAry->getSCEVType()) {
368 case scAddExpr:
369 case scMulExpr:
370 if (NAry->hasNoUnsignedWrap())
371 OS << "<nuw>";
372 if (NAry->hasNoSignedWrap())
373 OS << "<nsw>";
374 break;
375 default:
376 // Nothing to print for other nary expressions.
377 break;
378 }
379 return;
380 }
381 case scUDivExpr: {
382 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
383 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
384 return;
385 }
386 case scUnknown:
387 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
388 return;
390 OS << "***COULDNOTCOMPUTE***";
391 return;
392 }
393 llvm_unreachable("Unknown SCEV kind!");
394}
395
397 switch (getSCEVType()) {
398 case scConstant:
399 case scVScale:
400 case scUnknown:
401 return {};
402 case scPtrToAddr:
403 case scTruncate:
404 case scZeroExtend:
405 case scSignExtend:
406 return cast<SCEVCastExpr>(this)->operands();
407 case scAddRecExpr:
408 case scAddExpr:
409 case scMulExpr:
410 case scUMaxExpr:
411 case scSMaxExpr:
412 case scUMinExpr:
413 case scSMinExpr:
415 return cast<SCEVNAryExpr>(this)->operands();
416 case scUDivExpr:
417 return cast<SCEVUDivExpr>(this)->operands();
419 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
420 }
421 llvm_unreachable("Unknown SCEV kind!");
422}
423
424bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
425
426bool SCEV::isOne() const { return match(this, m_scev_One()); }
427
428bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
429
432 if (!Mul) return false;
433
434 // If there is a constant factor, it will be first.
435 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
436 if (!SC) return false;
437
438 // Return true if the value is negative, this matches things like (-42 * V).
439 return SC->getAPInt().isNegative();
440}
441
444
446 return S->getSCEVType() == scCouldNotCompute;
447}
448
450 auto &Entry = ConstantSCEVs[V];
451 if (Entry)
452 return Entry;
453
456 ID.AddPointer(V);
458 if (SCEVConstant *S =
459 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
460 return Entry = S;
461 SCEVConstant *S =
462 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
463 UniqueSCEVs.insert(S, Token);
464 S->computeAndSetCanonical(*this);
465 return Entry = S;
466}
467
469 return getConstant(ConstantInt::get(getContext(), Val));
470}
471
472const SCEV *
475 // TODO: Avoid implicit trunc?
476 // See https://github.com/llvm/llvm-project/issues/112510.
477 return getConstant(
478 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
479}
480
484 ID.AddPointer(Ty);
486 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
487 return S;
488 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
489 UniqueSCEVs.insert(S, Token);
490 S->computeAndSetCanonical(*this);
491 return S;
492}
493
495 SCEVFlags Flags) {
496 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
497 if (EC.isScalable())
498 Res = getMulExpr(Res, getVScale(Ty), Flags);
499 return Res;
500}
501
503 SCEVUse op, Type *ty)
504 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
505
506SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
507 const SCEV *Op, Type *ITy)
508 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
509 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
510 "Must be a non-bit-width-changing pointer-to-integer cast!");
511}
512
517
518SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
519 Type *ty)
521 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
522 "Cannot truncate non-integer value!");
523}
524
525SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
526 Type *ty)
528 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
529 "Cannot zero extend non-integer value!");
530}
531
532SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
533 Type *ty)
535 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
536 "Cannot sign extend non-integer value!");
537}
538
540 // Clear this SCEVUnknown from various maps.
541 SE->forgetMemoizedResults({this});
542
543 // Remove this SCEVUnknown from the uniquing map.
544 SE->UniqueSCEVs.erase(this);
545
546 // Release the value.
547 setValPtr(nullptr);
548}
549
550void SCEVUnknown::allUsesReplacedWith(Value *New) {
551 // Clear this SCEVUnknown from various maps.
552 SE->forgetMemoizedResults({this});
553
554 // Remove this SCEVUnknown from the uniquing map.
555 SE->UniqueSCEVs.erase(this);
556
557 // Replace the value pointer in case someone is still using this SCEVUnknown.
558 setValPtr(New);
559}
560
561//===----------------------------------------------------------------------===//
562// SCEV Utilities
563//===----------------------------------------------------------------------===//
564
565/// Compare the two values \p LV and \p RV in terms of their "complexity" where
566/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
567/// operands in SCEV expressions.
568static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
569 Value *RV, unsigned Depth) {
571 return 0;
572
573 // Order pointer values after integer values. This helps SCEVExpander form
574 // GEPs.
575 bool LIsPointer = LV->getType()->isPointerTy(),
576 RIsPointer = RV->getType()->isPointerTy();
577 if (LIsPointer != RIsPointer)
578 return (int)LIsPointer - (int)RIsPointer;
579
580 // Compare getValueID values.
581 unsigned LID = LV->getValueID(), RID = RV->getValueID();
582 if (LID != RID)
583 return (int)LID - (int)RID;
584
585 // Sort arguments by their position.
586 if (const auto *LA = dyn_cast<Argument>(LV)) {
587 const auto *RA = cast<Argument>(RV);
588 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
589 return (int)LArgNo - (int)RArgNo;
590 }
591
592 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
593 const auto *RGV = cast<GlobalValue>(RV);
594
595 if (auto L = LGV->getLinkage() - RGV->getLinkage())
596 return L;
597
598 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
599 auto LT = GV->getLinkage();
600 return !(GlobalValue::isPrivateLinkage(LT) ||
602 };
603
604 // Use the names to distinguish the two values, but only if the
605 // names are semantically important.
606 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
607 return LGV->getName().compare(RGV->getName());
608 }
609
610 // For instructions, compare their loop depth, and their operand count. This
611 // is pretty loose.
612 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
613 const auto *RInst = cast<Instruction>(RV);
614
615 // Compare loop depths.
616 const BasicBlock *LParent = LInst->getParent(),
617 *RParent = RInst->getParent();
618 if (LParent != RParent) {
619 unsigned LDepth = LI->getLoopDepth(LParent),
620 RDepth = LI->getLoopDepth(RParent);
621 if (LDepth != RDepth)
622 return (int)LDepth - (int)RDepth;
623 }
624
625 // Compare the number of operands.
626 unsigned LNumOps = LInst->getNumOperands(),
627 RNumOps = RInst->getNumOperands();
628 if (LNumOps != RNumOps)
629 return (int)LNumOps - (int)RNumOps;
630
631 for (unsigned Idx : seq(LNumOps)) {
632 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
633 RInst->getOperand(Idx), Depth + 1);
634 if (Result != 0)
635 return Result;
636 }
637 }
638
639 return 0;
640}
641
642// Return negative, zero, or positive, if LHS is less than, equal to, or greater
643// than RHS, respectively. A three-way result allows recursive comparisons to be
644// more efficient. The result is a total order.
645static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS,
647 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
648 if (LHS == RHS)
649 return 0;
650
651 if (LHS.getPointer() == RHS.getPointer())
652 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
653
654 // Primarily, sort the SCEVs by their getSCEVType().
655 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
656 if (LType != RType)
657 return (int)LType - (int)RType;
658
659 // Aside from the getSCEVType() ordering, the particular ordering
660 // isn't very important except that it's beneficial to be consistent,
661 // so that (a + b) and (b + a) don't end up as different expressions.
662 switch (LType) {
663 case scUnknown: {
664 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
665 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
666
667 if (int X = CompareValueComplexity(LI, LU->getValue(), RU->getValue(),
668 /*Depth=*/0))
669 return X;
670 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
671 }
672
673 case scConstant: {
676
677 // Compare constant values.
678 const APInt &LA = LC->getAPInt();
679 const APInt &RA = RC->getAPInt();
680 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
681 if (LBitWidth != RBitWidth)
682 return (int)LBitWidth - (int)RBitWidth;
683 return LA.ult(RA) ? -1 : 1;
684 }
685
686 case scVScale: {
687 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
688 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
689 return LTy->getBitWidth() - RTy->getBitWidth();
690 }
691
692 case scAddRecExpr: {
695
696 // There is always a dominance between two recs that are used by one SCEV,
697 // so we can safely sort recs by loop header dominance. We require such
698 // order in getAddExpr.
699 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
700 if (LLoop != RLoop) {
701 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
702 assert(LHead != RHead && "Two loops share the same header?");
703 if (DT.dominates(LHead, RHead))
704 return 1;
705 assert(DT.dominates(RHead, LHead) &&
706 "No dominance between recurrences used by one SCEV?");
707 return -1;
708 }
709
710 [[fallthrough]];
711 }
712
713 case scTruncate:
714 case scZeroExtend:
715 case scSignExtend:
716 case scPtrToAddr:
717 case scAddExpr:
718 case scMulExpr:
719 case scUDivExpr:
720 case scSMaxExpr:
721 case scUMaxExpr:
722 case scSMinExpr:
723 case scUMinExpr:
725 ArrayRef<SCEVUse> LOps = LHS->operands();
726 ArrayRef<SCEVUse> ROps = RHS->operands();
727
728 // Lexicographically compare n-ary-like expressions.
729 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
730 if (LNumOps != RNumOps)
731 return (int)LNumOps - (int)RNumOps;
732
733 for (unsigned i = 0; i != LNumOps; ++i) {
734 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
735 ROps[i].getPointer(), DT);
736 if (X != 0)
737 return X;
738 }
739
740 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
741 unsigned LBitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
742 unsigned RBitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
743 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
744 return (int)LBitWidth - (int)RBitWidth;
745 }
746
748 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
749 }
750 llvm_unreachable("Unknown SCEV kind!");
751}
752
753/// Given a list of SCEV objects, order them by their complexity, and group
754/// objects of the same complexity together by value. When this routine is
755/// finished, we know that any duplicates in the vector are consecutive and that
756/// complexity is monotonically increasing.
757///
758/// Note that we go take special precautions to ensure that we get deterministic
759/// results from this routine. In other words, we don't want the results of
760/// this to depend on where the addresses of various SCEV objects happened to
761/// land in memory.
763 DominatorTree &DT) {
764 if (Ops.size() < 2) return; // Noop
765
766 // Whether LHS has provably less complexity than RHS.
767 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
768 return CompareSCEVComplexity(LI, LHS, RHS, DT) < 0;
769 };
770 if (Ops.size() == 2) {
771 // This is the common case, which also happens to be trivially simple.
772 // Special case it.
773 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
774 if (IsLessComplex(RHS, LHS))
775 std::swap(LHS, RHS);
776 return;
777 }
778
779 llvm::sort(Ops, IsLessComplex);
780}
781
782/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
783/// least HugeExprThreshold nodes).
785 return any_of(Ops, [](const SCEV *S) {
787 });
788}
789
790/// Performs a number of common optimizations on the passed \p Ops. If the
791/// whole expression reduces down to a single operand, it will be returned.
792///
793/// The following optimizations are performed:
794/// * Fold constants using the \p Fold function.
795/// * Remove identity constants satisfying \p IsIdentity.
796/// * If a constant satisfies \p IsAbsorber, return it.
797/// * Sort operands by complexity.
798template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
799static const SCEV *
801 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
802 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
803 const SCEVConstant *Folded = nullptr;
804 for (unsigned Idx = 0; Idx < Ops.size();) {
805 const SCEV *Op = Ops[Idx];
806 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
807 if (!Folded)
808 Folded = C;
809 else
810 Folded = cast<SCEVConstant>(
811 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
812 Ops.erase(Ops.begin() + Idx);
813 continue;
814 }
815 ++Idx;
816 }
817
818 if (Ops.empty()) {
819 assert(Folded && "Must have folded value");
820 return Folded;
821 }
822
823 if (Folded && IsAbsorber(Folded->getAPInt()))
824 return Folded;
825
826 GroupByComplexity(Ops, &LI, DT);
827 if (Folded && !IsIdentity(Folded->getAPInt()))
828 Ops.insert(Ops.begin(), Folded);
829
830 return Ops.size() == 1 ? Ops[0] : nullptr;
831}
832
833//===----------------------------------------------------------------------===//
834// Simple SCEV method implementations
835//===----------------------------------------------------------------------===//
836
837/// Compute BC(It, K). The result has width W. Assume, K > 0.
838static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
839 ScalarEvolution &SE,
840 Type *ResultTy) {
841 // Handle the simplest case efficiently.
842 if (K == 1)
843 return SE.getTruncateOrZeroExtend(It, ResultTy);
844
845 // We are using the following formula for BC(It, K):
846 //
847 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
848 //
849 // Suppose, W is the bitwidth of the return value. We must be prepared for
850 // overflow. Hence, we must assure that the result of our computation is
851 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
852 // safe in modular arithmetic.
853 //
854 // However, this code doesn't use exactly that formula; the formula it uses
855 // is something like the following, where T is the number of factors of 2 in
856 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
857 // exponentiation:
858 //
859 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
860 //
861 // This formula is trivially equivalent to the previous formula. However,
862 // this formula can be implemented much more efficiently. The trick is that
863 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
864 // arithmetic. To do exact division in modular arithmetic, all we have
865 // to do is multiply by the inverse. Therefore, this step can be done at
866 // width W.
867 //
868 // The next issue is how to safely do the division by 2^T. The way this
869 // is done is by doing the multiplication step at a width of at least W + T
870 // bits. This way, the bottom W+T bits of the product are accurate. Then,
871 // when we perform the division by 2^T (which is equivalent to a right shift
872 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
873 // truncated out after the division by 2^T.
874 //
875 // In comparison to just directly using the first formula, this technique
876 // is much more efficient; using the first formula requires W * K bits,
877 // but this formula less than W + K bits. Also, the first formula requires
878 // a division step, whereas this formula only requires multiplies and shifts.
879 //
880 // It doesn't matter whether the subtraction step is done in the calculation
881 // width or the input iteration count's width; if the subtraction overflows,
882 // the result must be zero anyway. We prefer here to do it in the width of
883 // the induction variable because it helps a lot for certain cases; CodeGen
884 // isn't smart enough to ignore the overflow, which leads to much less
885 // efficient code if the width of the subtraction is wider than the native
886 // register width.
887 //
888 // (It's possible to not widen at all by pulling out factors of 2 before
889 // the multiplication; for example, K=2 can be calculated as
890 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
891 // extra arithmetic, so it's not an obvious win, and it gets
892 // much more complicated for K > 3.)
893
894 // Protection from insane SCEVs; this bound is conservative,
895 // but it probably doesn't matter.
896 if (K > 1000)
897 return SE.getCouldNotCompute();
898
899 unsigned W = SE.getTypeSizeInBits(ResultTy);
900
901 // Calculate K! / 2^T and T; we divide out the factors of two before
902 // multiplying for calculating K! / 2^T to avoid overflow.
903 // Other overflow doesn't matter because we only care about the bottom
904 // W bits of the result.
905 APInt OddFactorial(W, 1);
906 unsigned T = 1;
907 for (unsigned i = 3; i <= K; ++i) {
908 unsigned TwoFactors = countr_zero(i);
909 T += TwoFactors;
910 OddFactorial *= (i >> TwoFactors);
911 }
912
913 // We need at least W + T bits for the multiplication step
914 unsigned CalculationBits = W + T;
915
916 // Calculate 2^T, at width T+W.
917 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
918
919 // Calculate the multiplicative inverse of K! / 2^T;
920 // this multiplication factor will perform the exact division by
921 // K! / 2^T.
922 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
923
924 // Calculate the product, at width T+W
925 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
926 CalculationBits);
927 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
928 for (unsigned i = 1; i != K; ++i) {
929 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
930 Dividend = SE.getMulExpr(Dividend,
931 SE.getTruncateOrZeroExtend(S, CalculationTy));
932 }
933
934 // Divide by 2^T
935 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
936
937 // Truncate the result, and divide by K! / 2^T.
938
939 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
940 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
941}
942
943/// Return the value of this chain of recurrences at the specified iteration
944/// number. We can evaluate this recurrence by multiplying each element in the
945/// chain by the binomial coefficient corresponding to it. In other words, we
946/// can evaluate {A,+,B,+,C,+,D} as:
947///
948/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
949///
950/// where BC(It, k) stands for binomial coefficient.
952 ScalarEvolution &SE) const {
953 return evaluateAtIteration(operands(), It, SE);
954}
955
957 const SCEV *It, ScalarEvolution &SE,
958 SCEVFlags UseFlags) {
959 assert(Operands.size() > 0);
960 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
961 "use-specific flags only supported for affine AddRecs");
962 SCEVUse Result = Operands[0].getPointer();
963 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
964 // The computation is correct in the face of overflow provided that the
965 // multiplication is performed _after_ the evaluation of the binomial
966 // coefficient.
967 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
968 if (isa<SCEVCouldNotCompute>(Coeff))
969 return Coeff;
970
971 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
972 {SCEV::FlagNone, UseFlags});
973 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
974 }
975 return Result;
976}
977
979 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
981 return BTC;
982 // The loop reaches iteration BTC, so the value this recurrence computes there
983 // is the value it had, and that did not wrap.
984 return evaluateAtIteration(operands(), BTC, SE,
987}
988
989//===----------------------------------------------------------------------===//
990// SCEV Expression folder implementations
991//===----------------------------------------------------------------------===//
992
993/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
994/// which computes a pointer-typed value, and rewrites the whole expression
995/// tree so that *all* the computations are done on integers, and the only
996/// pointer-typed operands in the expression are SCEVUnknown.
997/// The CreatePtrCast callback is invoked to create the actual conversion
998/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1000 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1002 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1003 Type *TargetTy;
1004 ConversionFn CreatePtrCast;
1005
1006public:
1008 ConversionFn CreatePtrCast)
1009 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1010
1011 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1012 Type *TargetTy, ConversionFn CreatePtrCast) {
1013 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1014 return Rewriter.visit(Scev);
1015 }
1016
1017 const SCEV *visit(const SCEV *S) {
1018 Type *STy = S->getType();
1019 // If the expression is not pointer-typed, just keep it as-is.
1020 if (!STy->isPointerTy())
1021 return S;
1022 // Else, recursively sink the cast down into it.
1023 return Base::visit(S);
1024 }
1025
1026 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1027 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1028 // implementation drops.
1030 bool Changed = false;
1031 for (SCEVUse Op : Expr->operands()) {
1032 Operands.push_back(visit(Op.getPointer()));
1033 Changed |= Op.getPointer() != Operands.back();
1034 }
1035 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1036 }
1037
1038 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1039 assert(Expr->getType()->isPointerTy() &&
1040 "Should only reach pointer-typed SCEVUnknown's.");
1041 // Perform some basic constant folding. If the operand of the cast is a
1042 // null pointer, don't create a cast SCEV expression (that will be left
1043 // as-is), but produce a zero constant.
1045 return SE.getZero(TargetTy);
1046 return CreatePtrCast(Expr);
1047 }
1048};
1049
1051 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1052
1053 // Treat pointers with unstable representation conservatively, since the
1054 // address bits may change.
1055 if (DL.hasUnstableRepresentation(Op->getType()))
1056 return getCouldNotCompute();
1057
1058 Type *Ty = DL.getAddressType(Op->getType());
1059
1060 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1061 // The rewriter handles null pointer constant folding.
1063 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1066 ID.AddPointer(U);
1067 ID.AddPointer(Ty);
1069 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1070 return S;
1071 SCEV *S = new (SCEVAllocator)
1072 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1073 UniqueSCEVs.insert(S, Token);
1074 S->computeAndSetCanonical(*this);
1075 registerUser(S, {U});
1076 return static_cast<const SCEV *>(S);
1077 });
1078 assert(IntOp->getType()->isIntegerTy() &&
1079 "We must have succeeded in sinking the cast, "
1080 "and ending up with an integer-typed expression!");
1081 return IntOp;
1082}
1083
1085 unsigned Depth) {
1086 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1087 "This is not a truncating conversion!");
1088 assert(isSCEVable(Ty) &&
1089 "This is not a conversion to a SCEVable type!");
1090 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1091 Ty = getEffectiveSCEVType(Ty);
1092
1095 ID.AddPointer(Op.getOpaqueValue());
1096 ID.AddPointer(Ty);
1098 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1099 return S;
1100
1101 // Fold if the operand is constant.
1102 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1103 return getConstant(
1104 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1105
1106 // trunc(trunc(x)) --> trunc(x)
1108 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1109
1110 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1112 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1113
1114 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1116 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1117
1118 if (Depth > MaxCastDepth) {
1119 SCEV *S =
1120 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1121 UniqueSCEVs.insert(S, Token);
1122 S->computeAndSetCanonical(*this);
1123 registerUser(S, Op);
1124 return S;
1125 }
1126
1127 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1128 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1129 // if after transforming we have at most one truncate, not counting truncates
1130 // that replace other casts.
1132 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1134 unsigned numTruncs = 0;
1135 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1136 ++i) {
1137 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1138 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1140 numTruncs++;
1141 Operands.push_back(S);
1142 }
1143 if (numTruncs < 2) {
1144 if (isa<SCEVAddExpr>(Op))
1145 return getAddExpr(Operands);
1146 if (isa<SCEVMulExpr>(Op))
1147 return getMulExpr(Operands);
1148 llvm_unreachable("Unexpected SCEV type for Op.");
1149 }
1150 // Although we checked in the beginning that ID is not in the cache, it is
1151 // possible that during recursion and different modification ID was inserted
1152 // into the cache. So if we find it, just return it.
1153 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1154 return S;
1155 }
1156
1157 // If the input value is a chrec scev, truncate the chrec's operands.
1158 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1160 for (const SCEV *Op : AddRec->operands())
1161 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1162 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1163 }
1164
1165 // Return zero if truncating to known zeros.
1166 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1167 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1168 return getZero(Ty);
1169
1170 // The cast wasn't folded; create an explicit cast node. We can reuse
1171 // the existing insert position since if we get here, we won't have
1172 // made any changes which would invalidate it.
1173 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1174 Op, Ty);
1175 UniqueSCEVs.insert(S, Token);
1176 S->computeAndSetCanonical(*this);
1177 registerUser(S, Op);
1178 return S;
1179}
1180
1181// Get the limit of a recurrence such that incrementing by Step cannot cause
1182// signed overflow as long as the value of the recurrence within the
1183// loop does not exceed this limit before incrementing.
1184static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1185 ICmpInst::Predicate *Pred,
1186 ScalarEvolution *SE) {
1187 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1188 if (SE->isKnownPositive(Step)) {
1189 *Pred = ICmpInst::ICMP_SLT;
1191 SE->getSignedRangeMax(Step));
1192 }
1193 if (SE->isKnownNegative(Step)) {
1194 *Pred = ICmpInst::ICMP_SGT;
1196 SE->getSignedRangeMin(Step));
1197 }
1198 return nullptr;
1199}
1200
1201// Get the limit of a recurrence such that incrementing by Step cannot cause
1202// unsigned overflow as long as the value of the recurrence within the loop does
1203// not exceed this limit before incrementing.
1205 ICmpInst::Predicate *Pred,
1206 ScalarEvolution *SE) {
1207 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1208 *Pred = ICmpInst::ICMP_ULT;
1209
1211 SE->getUnsignedRangeMax(Step));
1212}
1213
1214namespace {
1215
1216struct ExtendOpTraitsBase {
1217 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1218 unsigned);
1219};
1220
1221// Used to make code generic over signed and unsigned overflow.
1222template <typename ExtendOp> struct ExtendOpTraits {
1223 // Members present:
1224 //
1225 // static const SCEVFlags WrapType;
1226 //
1227 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1228 //
1229 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1230 // ICmpInst::Predicate *Pred,
1231 // ScalarEvolution *SE);
1232};
1233
1234template <>
1235struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1236 static const SCEVFlags WrapType = SCEV::FlagNSW;
1237
1238 static const GetExtendExprTy GetExtendExpr;
1239
1240 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1241 ICmpInst::Predicate *Pred,
1242 ScalarEvolution *SE) {
1243 return getSignedOverflowLimitForStep(Step, Pred, SE);
1244 }
1245};
1246
1247const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1249
1250template <>
1251struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1252 static const SCEVFlags WrapType = SCEV::FlagNUW;
1253
1254 static const GetExtendExprTy GetExtendExpr;
1255
1256 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1257 ICmpInst::Predicate *Pred,
1258 ScalarEvolution *SE) {
1259 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1260 }
1261};
1262
1263const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1265
1266} // end anonymous namespace
1267
1268// The recurrence AR has been shown to have no signed/unsigned wrap or something
1269// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1270// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1271// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1272// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1273// expression "Step + sext/zext(PreIncAR)" is congruent with
1274// "sext/zext(PostIncAR)"
1275template <typename ExtendOpTy>
1277 ScalarEvolution *SE, unsigned Depth) {
1278 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1279 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1280
1281 const Loop *L = AR->getLoop();
1282 const SCEV *Start = AR->getStart();
1283 const SCEV *Step = AR->getStepRecurrence(*SE);
1284
1285 // Check for a simple looking step prior to loop entry.
1286 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1287 if (!SA)
1288 return nullptr;
1289
1290 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1291 // subtraction is expensive. For this purpose, perform a quick and dirty
1292 // difference, by checking for Step in the operand list. Note, that
1293 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1294 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1295 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1296 if (*It == Step) {
1297 DiffOps.erase(It);
1298 break;
1299 }
1300
1301 if (DiffOps.size() == SA->getNumOperands())
1302 return nullptr;
1303
1304 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1305 // `Step`:
1306
1307 // 1. NSW/NUW flags on the step increment.
1308 auto PreStartFlags =
1310 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1312 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
1313
1314 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1315 // "S+X does not sign/unsign-overflow".
1316 //
1317
1318 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1319 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1320 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1321 return PreStart;
1322
1323 // 2. Direct overflow check on the step operation's expression.
1324 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1325 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1326 const SCEV *OperandExtendedStart =
1327 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1328 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1329 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1330 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1331 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1332 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1333 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1334 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1335 }
1336 return PreStart;
1337 }
1338
1339 // 3. Loop precondition.
1341 const SCEV *OverflowLimit =
1342 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1343
1344 if (OverflowLimit &&
1345 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1346 return PreStart;
1347
1348 return nullptr;
1349}
1350
1351// Get the normalized zero or sign extended expression for this AddRec's Start.
1352template <typename ExtendOpTy>
1353static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1354 ScalarEvolution *SE,
1355 unsigned Depth) {
1356 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1357
1358 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1359 if (!PreStart)
1360 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1361
1362 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1363 Depth),
1364 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1365}
1366
1367// Try to prove away overflow by looking at "nearby" add recurrences. A
1368// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1369// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1370//
1371// Formally:
1372//
1373// {S,+,X} == {S-T,+,X} + T
1374// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1375//
1376// If ({S-T,+,X} + T) does not overflow ... (1)
1377//
1378// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1379//
1380// If {S-T,+,X} does not overflow ... (2)
1381//
1382// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1383// == {Ext(S-T)+Ext(T),+,Ext(X)}
1384//
1385// If (S-T)+T does not overflow ... (3)
1386//
1387// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1388// == {Ext(S),+,Ext(X)} == LHS
1389//
1390// Thus, if (1), (2) and (3) are true for some T, then
1391// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1392//
1393// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1394// does not overflow" restricted to the 0th iteration. Therefore we only need
1395// to check for (1) and (2).
1396//
1397// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1398// is `Delta` (defined below).
1399template <typename ExtendOpTy>
1400bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1401 const SCEV *Step,
1402 const Loop *L) {
1403 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1404
1405 // We restrict `Start` to a constant to prevent SCEV from spending too much
1406 // time here. It is correct (but more expensive) to continue with a
1407 // non-constant `Start` and do a general SCEV subtraction to compute
1408 // `PreStart` below.
1409 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1410 if (!StartC)
1411 return false;
1412
1413 APInt StartAI = StartC->getAPInt();
1414
1415 for (unsigned Delta : {-2, -1, 1, 2}) {
1416 const SCEV *PreStart = getConstant(StartAI - Delta);
1417 const auto *PreAR = static_cast<SCEVAddRecExpr *>(
1418 findExistingSCEVInCache(scAddRecExpr, {PreStart, Step}, L));
1419
1420 // Give up if we don't already have the add recurrence we need because
1421 // actually constructing an add recurrence is relatively expensive.
1422 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1423 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1425 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1426 DeltaS, &Pred, this);
1427 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1428 return true;
1429 }
1430 }
1431
1432 return false;
1433}
1434
1435// Finds an integer D for an expression (C + x + y + ...) such that the top
1436// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1437// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1438// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1439// the (C + x + y + ...) expression is \p WholeAddExpr.
1441 const SCEVConstant *ConstantTerm,
1442 const SCEVAddExpr *WholeAddExpr) {
1443 const APInt &C = ConstantTerm->getAPInt();
1444 const unsigned BitWidth = C.getBitWidth();
1445 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1446 uint32_t TZ = BitWidth;
1447 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1448 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1449 if (TZ) {
1450 // Set D to be as many least significant bits of C as possible while still
1451 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1452 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1453 }
1454 return APInt(BitWidth, 0);
1455}
1456
1457// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1458// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1459// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1460// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1462 const APInt &ConstantStart,
1463 const SCEV *Step) {
1464 const unsigned BitWidth = ConstantStart.getBitWidth();
1465 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1466 if (TZ)
1467 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1468 : ConstantStart;
1469 return APInt(BitWidth, 0);
1470}
1471
1473 const ScalarEvolution::FoldID &ID, const SCEV *S,
1476 &FoldCacheUser) {
1477 auto I = FoldCache.insert({ID, S});
1478 if (!I.second) {
1479 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1480 // entry.
1481 auto &UserIDs = FoldCacheUser[I.first->second];
1482 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1483 for (unsigned I = 0; I != UserIDs.size(); ++I)
1484 if (UserIDs[I] == ID) {
1485 std::swap(UserIDs[I], UserIDs.back());
1486 break;
1487 }
1488 UserIDs.pop_back();
1489 I.first->second = S;
1490 }
1491 FoldCacheUser[S].push_back(ID);
1492}
1493
1495 unsigned Depth) {
1496 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1497 "This is not an extending conversion!");
1498 assert(isSCEVable(Ty) &&
1499 "This is not a conversion to a SCEVable type!");
1500 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1501 Ty = getEffectiveSCEVType(Ty);
1502
1503 FoldID ID(scZeroExtend, Op, Ty);
1504 if (const SCEV *S = FoldCache.lookup(ID))
1505 return S;
1506
1507 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1509 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1510 return S;
1511}
1512
1514 unsigned Depth) {
1515 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1516 "This is not an extending conversion!");
1517 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1518 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1519
1520 // Fold if the operand is constant.
1521 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1522 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1523
1524 // zext(zext(x)) --> zext(x)
1526 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1527
1528 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1529 // zero-extension distributes over the recurrence.
1530 const SCEV *Start, *Step;
1531 const Loop *L;
1532 if (Depth <= MaxCastDepth &&
1533 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1534 const auto *AR = cast<SCEVAddRecExpr>(Op);
1535 if (AR->hasNoUnsignedWrap()) {
1536 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1537 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1538 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1539 }
1540 }
1541
1542 // Before doing any expensive analysis, check to see if we've already
1543 // computed a SCEV for this Op and Ty.
1546 ID.AddPointer(Op.getOpaqueValue());
1547 ID.AddPointer(Ty);
1549 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1550 return S;
1551 if (Depth > MaxCastDepth) {
1552 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1553 Op, Ty);
1554 UniqueSCEVs.insert(S, Token);
1555 S->computeAndSetCanonical(*this);
1556 registerUser(S, Op);
1557 return S;
1558 }
1559
1560 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1562 // It's possible the bits taken off by the truncate were all zero bits. If
1563 // so, we should be able to simplify this further.
1564 const SCEV *X = ST->getOperand();
1566 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1567 unsigned NewBits = getTypeSizeInBits(Ty);
1568 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1569 CR.zextOrTrunc(NewBits)))
1570 return getTruncateOrZeroExtend(X, Ty, Depth);
1571 }
1572
1573 // If the input value is a chrec scev, and we can prove that the value
1574 // did not overflow the old, smaller, value, we can zero extend all of the
1575 // operands (often constants). This allows analysis of something like
1576 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1577 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1578 const auto *AR = cast<SCEVAddRecExpr>(Op);
1579 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1580
1581 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1582
1583 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1584 // Note that this serves two purposes: It filters out loops that are
1585 // simply not analyzable, and it covers the case where this code is
1586 // being called from within backedge-taken count analysis, such that
1587 // attempting to ask for the backedge-taken count would likely result
1588 // in infinite recursion. In the later case, the analysis code will
1589 // cope with a conservative value, and it will take care to purge
1590 // that value once it has finished.
1591 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1592 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1593 // Manually compute the final value for AR, checking for overflow.
1594
1595 // Check whether the backedge-taken count can be losslessly casted to
1596 // the addrec's type. The count is always unsigned.
1597 const SCEV *CastedMaxBECount =
1598 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1599 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1600 CastedMaxBECount, MaxBECount->getType(), Depth);
1601 if (MaxBECount == RecastedMaxBECount) {
1602 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1603 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1604 const SCEV *ZMul =
1605 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1606 const SCEV *ZAdd = getZeroExtendExpr(
1607 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1608 Depth + 1);
1609 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1610 const SCEV *WideMaxBECount =
1611 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1612 const SCEV *OperandExtendedAdd =
1613 getAddExpr(WideStart,
1614 getMulExpr(WideMaxBECount,
1615 getZeroExtendExpr(Step, WideTy, Depth + 1),
1616 SCEV::FlagNone, Depth + 1),
1617 SCEV::FlagNone, Depth + 1);
1618 if (ZAdd == OperandExtendedAdd) {
1619 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1620 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1621 // Return the expression with the addrec on the outside.
1622 Start =
1624 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1625 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1626 }
1627 // Similar to above, only this time treat the step value as signed.
1628 // This covers loops that count down.
1629 OperandExtendedAdd =
1630 getAddExpr(WideStart,
1631 getMulExpr(WideMaxBECount,
1632 getSignExtendExpr(Step, WideTy, Depth + 1),
1633 SCEV::FlagNone, Depth + 1),
1634 SCEV::FlagNone, Depth + 1);
1635 if (ZAdd == OperandExtendedAdd) {
1636 // Cache knowledge of AR NW, which is propagated to this AddRec.
1637 // Negative step causes unsigned wrap, but it still can't self-wrap.
1638 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1639 // Return the expression with the addrec on the outside.
1640 Start =
1642 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1643 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1644 }
1645 }
1646 }
1647
1648 // Normally, in the cases we can prove no-overflow via a
1649 // backedge guarding condition, we can also compute a backedge
1650 // taken count for the loop. The exceptions are assumptions and
1651 // guards present in the loop -- SCEV is not great at exploiting
1652 // these to compute max backedge taken counts, but can still use
1653 // these to prove lack of overflow. Use this fact to avoid
1654 // doing extra work that may not pay off.
1655 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1656 !AC.assumptions().empty()) {
1657
1658 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1659 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1660 if (AR->hasNoUnsignedWrap()) {
1661 // Same as nuw case above - duplicated here to avoid a compile time
1662 // issue. It's not clear that the order of checks does matter, but
1663 // it's one of two issue possible causes for a change which was
1664 // reverted. Be conservative for the moment.
1665 Start =
1667 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1668 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1669 }
1670
1671 // For a negative step, we can extend the operands iff doing so only
1672 // traverses values in the range zext([0,UINT_MAX]).
1673 if (isKnownNegative(Step)) {
1674 const SCEV *N =
1678 // Cache knowledge of AR NW, which is propagated to this
1679 // AddRec. Negative step causes unsigned wrap, but it
1680 // still can't self-wrap.
1681 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1682 // Return the expression with the addrec on the outside.
1683 Start =
1685 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1686 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1687 }
1688 }
1689 }
1690
1691 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1692 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1693 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1694 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1695 const APInt &C = SC->getAPInt();
1696 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1697 if (D != 0) {
1698 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1699 const SCEV *SResidual =
1700 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1701 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1702 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1703 Depth + 1);
1704 }
1705 }
1706
1707 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1708 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1709 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1710 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1711 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1712 }
1713 }
1714
1715 // zext(A % B) --> zext(A) % zext(B)
1716 {
1717 const SCEV *LHS;
1718 const SCEV *RHS;
1719 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1720 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1721 getZeroExtendExpr(RHS, Ty, Depth + 1));
1722 }
1723
1724 // zext(A / B) --> zext(A) / zext(B).
1725 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1726 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1727 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1728
1729 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1730 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1731 if (SA->hasNoUnsignedWrap()) {
1732 // If the addition does not unsign overflow then we can, by definition,
1733 // commute the zero extension with the addition operation.
1735 for (SCEVUse Op : SA->operands())
1736 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1737 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1738 }
1739
1740 const APInt *C, *C2;
1741 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1742 // Currently the non-negative check is done manually, as isKnownNonNegative
1743 // is too expensive.
1744 if (SA->hasNoSignedWrap() &&
1746 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1747 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1748 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1749 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1750 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1751 SCEV::FlagNSW, Depth + 1);
1752 }
1753
1754 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1755 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1756 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1757 //
1758 // Often address arithmetics contain expressions like
1759 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1760 // This transformation is useful while proving that such expressions are
1761 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1762 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1763 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1764 if (D != 0) {
1765 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1766 const SCEV *SResidual =
1768 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1769 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1770 Depth + 1);
1771 }
1772 }
1773 }
1774
1775 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1776 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1777 if (SM->hasNoUnsignedWrap()) {
1778 // If the multiply does not unsign overflow then we can, by definition,
1779 // commute the zero extension with the multiply operation.
1781 for (SCEVUse Op : SM->operands())
1782 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1783 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1784 }
1785
1786 // zext(2^K * (trunc X to iN)) to iM ->
1787 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1788 //
1789 // Proof:
1790 //
1791 // zext(2^K * (trunc X to iN)) to iM
1792 // = zext((trunc X to iN) << K) to iM
1793 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1794 // (because shl removes the top K bits)
1795 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1796 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1797 //
1798 const APInt *C;
1799 const SCEV *TruncRHS;
1800 if (match(SM,
1801 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1802 C->isPowerOf2()) {
1803 int NewTruncBits =
1804 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1805 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1806 return getMulExpr(
1807 getZeroExtendExpr(SM->getOperand(0), Ty),
1808 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1809 SCEV::FlagNUW, Depth + 1);
1810 }
1811 }
1812
1813 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1814 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1818 for (SCEVUse Operand : MinMax->operands())
1819 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1821 return getUMinExpr(Operands);
1822 return getUMaxExpr(Operands);
1823 }
1824
1825 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1827 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1829 for (SCEVUse Operand : MinMax->operands())
1830 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1831 return getUMinExpr(Operands, /*Sequential*/ true);
1832 }
1833
1834 // The cast wasn't folded; create an explicit cast node.
1835 // Recompute the insert position, as it may have been invalidated.
1836 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1837 return S;
1838 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1839 Op, Ty);
1840 UniqueSCEVs.insert(S, Token);
1841 S->computeAndSetCanonical(*this);
1842 registerUser(S, Op);
1843 return S;
1844}
1845
1847 unsigned Depth) {
1848 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1849 "This is not an extending conversion!");
1850 assert(isSCEVable(Ty) &&
1851 "This is not a conversion to a SCEVable type!");
1852 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1853 Ty = getEffectiveSCEVType(Ty);
1854
1855 FoldID ID(scSignExtend, Op, Ty);
1856 if (const SCEV *S = FoldCache.lookup(ID))
1857 return S;
1858
1859 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1861 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1862 return S;
1863}
1864
1866 unsigned Depth) {
1867 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1868 "This is not an extending conversion!");
1869 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1870 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1871 Ty = getEffectiveSCEVType(Ty);
1872
1873 // Fold if the operand is constant.
1874 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1875 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1876
1877 // sext(sext(x)) --> sext(x)
1879 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1880
1881 // sext(zext(x)) --> zext(x)
1883 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1884
1885 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1886 // sign-extension distributes over the recurrence.
1887 const SCEV *Start, *Step;
1888 const Loop *L;
1889 if (Depth <= MaxCastDepth &&
1890 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1891 const auto *AR = cast<SCEVAddRecExpr>(Op);
1892 if (AR->hasNoSignedWrap()) {
1893 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1894 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1895 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1896 }
1897 }
1898
1899 // Before doing any expensive analysis, check to see if we've already
1900 // computed a SCEV for this Op and Ty.
1903 ID.AddPointer(Op.getOpaqueValue());
1904 ID.AddPointer(Ty);
1906 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1907 return S;
1908 // Limit recursion depth.
1909 if (Depth > MaxCastDepth) {
1910 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1911 Op, Ty);
1912 UniqueSCEVs.insert(S, Token);
1913 S->computeAndSetCanonical(*this);
1914 registerUser(S, Op);
1915 return S;
1916 }
1917
1918 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1920 // It's possible the bits taken off by the truncate were all sign bits. If
1921 // so, we should be able to simplify this further.
1922 const SCEV *X = ST->getOperand();
1924 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1925 unsigned NewBits = getTypeSizeInBits(Ty);
1926 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1927 CR.sextOrTrunc(NewBits)))
1928 return getTruncateOrSignExtend(X, Ty, Depth);
1929 }
1930
1931 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1932 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1933 if (SA->hasNoSignedWrap()) {
1934 // If the addition does not sign overflow then we can, by definition,
1935 // commute the sign extension with the addition operation.
1937 for (SCEVUse Op : SA->operands())
1938 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1939 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1940 }
1941
1942 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1943 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1944 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1945 //
1946 // For instance, this will bring two seemingly different expressions:
1947 // 1 + sext(5 + 20 * %x + 24 * %y) and
1948 // sext(6 + 20 * %x + 24 * %y)
1949 // to the same form:
1950 // 2 + sext(4 + 20 * %x + 24 * %y)
1951 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1952 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1953 if (D != 0) {
1954 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1955 const SCEV *SResidual =
1957 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1958 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1959 Depth + 1);
1960 }
1961 }
1962 }
1963 // If the input value is a chrec scev, and we can prove that the value
1964 // did not overflow the old, smaller, value, we can sign extend all of the
1965 // operands (often constants). This allows analysis of something like
1966 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1967 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1968 const auto *AR = cast<SCEVAddRecExpr>(Op);
1969 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1970
1971 // The no-signed-wrap case is handled before the uniquing lookup above.
1972
1973 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1974 // Note that this serves two purposes: It filters out loops that are
1975 // simply not analyzable, and it covers the case where this code is
1976 // being called from within backedge-taken count analysis, such that
1977 // attempting to ask for the backedge-taken count would likely result
1978 // in infinite recursion. In the later case, the analysis code will
1979 // cope with a conservative value, and it will take care to purge
1980 // that value once it has finished.
1981 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1982 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1983 // Manually compute the final value for AR, checking for
1984 // overflow.
1985
1986 // Check whether the backedge-taken count can be losslessly casted to
1987 // the addrec's type. The count is always unsigned.
1988 const SCEV *CastedMaxBECount =
1989 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1990 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1991 CastedMaxBECount, MaxBECount->getType(), Depth);
1992 if (MaxBECount == RecastedMaxBECount) {
1993 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1994 // Check whether Start+Step*MaxBECount has no signed overflow.
1995 const SCEV *SMul =
1996 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1997 const SCEV *SAdd = getSignExtendExpr(
1998 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
1999 Depth + 1);
2000 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2001 const SCEV *WideMaxBECount =
2002 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2003 const SCEV *OperandExtendedAdd =
2004 getAddExpr(WideStart,
2005 getMulExpr(WideMaxBECount,
2006 getSignExtendExpr(Step, WideTy, Depth + 1),
2007 SCEV::FlagNone, Depth + 1),
2008 SCEV::FlagNone, Depth + 1);
2009 if (SAdd == OperandExtendedAdd) {
2010 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2011 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2012 // Return the expression with the addrec on the outside.
2013 Start =
2015 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2016 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2017 }
2018 // Similar to above, only this time treat the step value as unsigned.
2019 // This covers loops that count up with an unsigned step.
2020 OperandExtendedAdd =
2021 getAddExpr(WideStart,
2022 getMulExpr(WideMaxBECount,
2023 getZeroExtendExpr(Step, WideTy, Depth + 1),
2024 SCEV::FlagNone, Depth + 1),
2025 SCEV::FlagNone, Depth + 1);
2026 if (SAdd == OperandExtendedAdd) {
2027 // If AR wraps around then
2028 //
2029 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2030 // => SAdd != OperandExtendedAdd
2031 //
2032 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2033 // (SAdd == OperandExtendedAdd => AR is NW)
2034
2035 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2036
2037 // Return the expression with the addrec on the outside.
2038 Start =
2040 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2041 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2042 }
2043 }
2044 }
2045
2046 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2047 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2048 if (AR->hasNoSignedWrap()) {
2049 // Same as nsw case above - duplicated here to avoid a compile time
2050 // issue. It's not clear that the order of checks does matter, but
2051 // it's one of two issue possible causes for a change which was
2052 // reverted. Be conservative for the moment.
2053 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2054 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2055 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2056 }
2057
2058 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2059 // if D + (C - D + Step * n) could be proven to not signed wrap
2060 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2061 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2062 const APInt &C = SC->getAPInt();
2063 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2064 if (D != 0) {
2065 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2066 const SCEV *SResidual =
2067 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2068 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2069 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2070 Depth + 1);
2071 }
2072 }
2073
2074 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2075 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2076 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2077 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2078 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2079 }
2080 }
2081
2082 // If the input value is provably positive and we could not simplify
2083 // away the sext build a zext instead.
2085 return getZeroExtendExpr(Op, Ty, Depth + 1);
2086
2087 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2088 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2092 for (SCEVUse Operand : MinMax->operands())
2093 Operands.push_back(getSignExtendExpr(Operand, Ty));
2095 return getSMinExpr(Operands);
2096 return getSMaxExpr(Operands);
2097 }
2098
2099 // The cast wasn't folded; create an explicit cast node.
2100 // Recompute the insert position, as it may have been invalidated.
2101 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2102 return S;
2103 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2104 Op, Ty);
2105 UniqueSCEVs.insert(S, Token);
2106 S->computeAndSetCanonical(*this);
2107 registerUser(S, Op);
2108 return S;
2109}
2110
2112 switch (Kind) {
2113 case scTruncate:
2114 return getTruncateExpr(Op, Ty);
2115 case scZeroExtend:
2116 return getZeroExtendExpr(Op, Ty);
2117 case scSignExtend:
2118 return getSignExtendExpr(Op, Ty);
2119 case scPtrToAddr: {
2120 const SCEV *Expr = getPtrToAddrExpr(Op);
2121 assert(Expr->getType() == Ty && "requested type must match");
2122 return Expr;
2123 }
2124 default:
2125 llvm_unreachable("Not a SCEV cast expression!");
2126 }
2127}
2128
2129/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2130/// unspecified bits out to the given type.
2132 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2133 "This is not an extending conversion!");
2134 assert(isSCEVable(Ty) &&
2135 "This is not a conversion to a SCEVable type!");
2136 Ty = getEffectiveSCEVType(Ty);
2137
2138 // Sign-extend negative constants.
2139 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2140 if (SC->getAPInt().isNegative())
2141 return getSignExtendExpr(Op, Ty);
2142
2143 // Peel off a truncate cast.
2145 const SCEV *NewOp = T->getOperand();
2146 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2147 return getAnyExtendExpr(NewOp, Ty);
2148 return getTruncateOrNoop(NewOp, Ty);
2149 }
2150
2151 // Next try a zext cast. If the cast is folded, use it.
2152 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2153 if (!isa<SCEVZeroExtendExpr>(ZExt))
2154 return ZExt;
2155
2156 // Next try a sext cast. If the cast is folded, use it.
2157 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2158 if (!isa<SCEVSignExtendExpr>(SExt))
2159 return SExt;
2160
2161 // Force the cast to be folded into the operands of an addrec.
2162 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2164 for (const SCEV *Op : AR->operands())
2165 Ops.push_back(getAnyExtendExpr(Op, Ty));
2166 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2167 }
2168
2169 // If the expression is obviously signed, use the sext cast value.
2170 if (isa<SCEVSMaxExpr>(Op))
2171 return SExt;
2172
2173 // Absent any other information, use the zext cast value.
2174 return ZExt;
2175}
2176
2177/// Process the given Ops list, which is a list of operands to be added under
2178/// the given scale, update the given map. This is a helper function for
2179/// getAddRecExpr. As an example of what it does, given a sequence of operands
2180/// that would form an add expression like this:
2181///
2182/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2183///
2184/// where A and B are constants, update the map with these values:
2185///
2186/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2187///
2188/// and add 13 + A*B*29 to AccumulatedConstant.
2189/// This will allow getAddRecExpr to produce this:
2190///
2191/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2192///
2193/// This form often exposes folding opportunities that are hidden in
2194/// the original operand list.
2195///
2196/// Return true iff it appears that any interesting folding opportunities
2197/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2198/// the common case where no interesting opportunities are present, and
2199/// is also used as a check to avoid infinite recursion.
2202 APInt &AccumulatedConstant,
2204 const APInt &Scale,
2205 ScalarEvolution &SE) {
2206 bool Interesting = false;
2207
2208 // Iterate over the add operands. They are sorted, with constants first.
2209 unsigned i = 0;
2210 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2211 ++i;
2212 // Pull a buried constant out to the outside.
2213 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2214 Interesting = true;
2215 AccumulatedConstant += Scale * C->getAPInt();
2216 }
2217
2218 // Next comes everything else. We're especially interested in multiplies
2219 // here, but they're in the middle, so just visit the rest with one loop.
2220 for (; i != Ops.size(); ++i) {
2222 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2223 APInt NewScale =
2224 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2225 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2226 // A multiplication of a constant with another add; recurse.
2227 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2228 Interesting |= CollectAddOperandsWithScales(
2229 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2230 } else {
2231 // A multiplication of a constant with some other value. Update
2232 // the map.
2233 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2234 const SCEV *Key = SE.getMulExpr(MulOps);
2235 auto Pair = M.insert({Key, NewScale});
2236 if (Pair.second) {
2237 NewOps.push_back(Pair.first->first);
2238 } else {
2239 Pair.first->second += NewScale;
2240 // The map already had an entry for this value, which may indicate
2241 // a folding opportunity.
2242 Interesting = true;
2243 }
2244 }
2245 } else {
2246 // An ordinary operand. Update the map.
2247 auto Pair = M.insert({Ops[i], Scale});
2248 if (Pair.second) {
2249 NewOps.push_back(Pair.first->first);
2250 } else {
2251 Pair.first->second += Scale;
2252 // The map already had an entry for this value, which may indicate
2253 // a folding opportunity.
2254 Interesting = true;
2255 }
2256 }
2257 }
2258
2259 return Interesting;
2260}
2261
2263 const SCEV *LHS, const SCEV *RHS,
2264 const Instruction *CtxI) {
2265 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2266 switch (BinOp) {
2267 default:
2268 llvm_unreachable("Unsupported binary op");
2269 case Instruction::Add:
2270 return getAddExpr(L, R);
2271 case Instruction::Sub:
2272 return getMinusSCEV(L, R);
2273 case Instruction::Mul:
2274 return getMulExpr(L, R);
2275 }
2276 };
2277
2278 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2281
2282 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2283 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2284 auto *WideTy =
2285 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2286
2287 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2288 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2289 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2290 const SCEV *B = Operation(LHSB, RHSB);
2291 if (A == B)
2292 return true;
2293 // Can we use context to prove the fact we need?
2294 if (!CtxI)
2295 return false;
2296 // TODO: Support mul.
2297 if (BinOp == Instruction::Mul)
2298 return false;
2299 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2300 // TODO: Lift this limitation.
2301 if (!RHSC)
2302 return false;
2303 APInt C = RHSC->getAPInt();
2304 unsigned NumBits = C.getBitWidth();
2305 bool IsSub = (BinOp == Instruction::Sub);
2306 bool IsNegativeConst = (Signed && C.isNegative());
2307 // Compute the direction and magnitude by which we need to check overflow.
2308 bool OverflowDown = IsSub ^ IsNegativeConst;
2309 APInt Magnitude = C;
2310 if (IsNegativeConst) {
2311 if (C == APInt::getSignedMinValue(NumBits))
2312 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2313 // want to deal with that.
2314 return false;
2315 Magnitude = -C;
2316 }
2317
2319 if (OverflowDown) {
2320 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2321 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2322 : APInt::getMinValue(NumBits);
2323 APInt Limit = Min + Magnitude;
2324 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2325 } else {
2326 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2327 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2328 : APInt::getMaxValue(NumBits);
2329 APInt Limit = Max - Magnitude;
2330 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2331 }
2332}
2333
2335 const OverflowingBinaryOperator *OBO) {
2336 // It cannot be done any better.
2337 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2338 return std::nullopt;
2339
2341
2342 if (OBO->hasNoUnsignedWrap())
2344 if (OBO->hasNoSignedWrap())
2346
2347 bool Deduced = false;
2348
2350 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2351 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2352
2353 bool CanUseNSW = true;
2354 const APInt *ShiftAmt;
2355 // Treat `shl %a, C` as `mul %a, 1 << C`.
2356 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2357 unsigned BitWidth = ShiftAmt->getBitWidth();
2358 if (ShiftAmt->uge(BitWidth))
2359 return std::nullopt;
2360 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2361 // overflows.
2362 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2363 Opcode = Instruction::Mul;
2365 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2366 Opcode != Instruction::Mul) {
2367 return std::nullopt;
2368 }
2369
2370 const Instruction *CtxI =
2372 if (!OBO->hasNoUnsignedWrap() &&
2373 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2375 Deduced = true;
2376 }
2377
2378 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2379 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2381 Deduced = true;
2382 }
2383
2384 if (Deduced)
2385 return Flags;
2386 return std::nullopt;
2387}
2388
2389// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2390// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2391// can't-overflow flags for the operation if possible.
2394 using namespace std::placeholders;
2395
2396 using OBO = OverflowingBinaryOperator;
2397
2398 bool CanAnalyze =
2400 (void)CanAnalyze;
2401 assert(CanAnalyze && "don't call from other places!");
2402
2403 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2404 SCEVFlags SignOrUnsignWrap =
2405 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2406
2407 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2408 auto IsKnownNonNegative = [&](SCEVUse U) {
2409 return SE->isKnownNonNegative(U);
2410 };
2411
2412 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2413 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2414
2415 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2416
2417 if (SignOrUnsignWrap != SignOrUnsignMask &&
2418 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2419 isa<SCEVConstant>(Ops[0])) {
2420
2421 auto Opcode = [&] {
2422 switch (Type) {
2423 case scAddExpr:
2424 return Instruction::Add;
2425 case scMulExpr:
2426 return Instruction::Mul;
2427 default:
2428 llvm_unreachable("Unexpected SCEV op.");
2429 }
2430 }();
2431
2432 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2433
2434 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2435 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2436 auto NSWRegion =
2437 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoSignedWrap);
2438 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2440 }
2441
2442 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2443 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2444 auto NUWRegion =
2445 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoUnsignedWrap);
2446 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2448 }
2449 }
2450
2451 // <0,+,nonnegative><nw> is also nuw
2452 // TODO: Add corresponding nsw case
2454 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2455 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2457
2458 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2460 Ops.size() == 2) {
2461 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2462 if (UDiv->getOperand(1) == Ops[1])
2464 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2465 if (UDiv->getOperand(1) == Ops[0])
2467 }
2468
2469 return Flags;
2470}
2471
2473 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2474}
2475
2476/// Get a canonical add expression, or something simpler if possible.
2478 SCEVFlagsPair Flags, unsigned Depth) {
2479 SCEVFlags ExprFlags = Flags.ExprFlags;
2480 SCEVFlags UseFlags = Flags.UseFlags;
2481 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2482 "only nuw or nsw allowed");
2483 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2484 "only nuw or nsw allowed");
2485 assert(!Ops.empty() && "Cannot get empty add!");
2486 if (Ops.size() == 1) return Ops[0];
2487#ifndef NDEBUG
2488 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2489 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2490 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2491 "SCEVAddExpr operand types don't match!");
2492 unsigned NumPtrs = count_if(
2493 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2494 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2495#endif
2496
2497 const SCEV *Folded = constantFoldAndGroupOps(
2498 *this, LI, DT, Ops,
2499 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2500 [](const APInt &C) { return C.isZero(); }, // identity
2501 [](const APInt &C) { return false; }); // absorber
2502 if (Folded)
2503 return Folded;
2504
2505#ifndef NDEBUG
2506 // Keep track of operands after constant folding, for verification when adding
2507 // use-specific flags.
2508 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2509#endif
2510
2511 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2512
2513 // Delay expensive flag strengthening until necessary.
2514 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2515 return StrengthenNoWrapFlags(this, scAddExpr, Ops, ExprFlags);
2516 };
2517
2518 // Limit recursion calls depth.
2520 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2521
2522 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2523 // Don't strengthen flags if we have no new information.
2524 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2525 if (Add->getNoWrapFlags(ExprFlags) != ExprFlags)
2526 Add->setNoWrapFlags(ComputeFlags(Ops));
2527 return {S, UseFlags};
2528 }
2529
2530 // Okay, check to see if the same value occurs in the operand list more than
2531 // once. If so, merge them together into an multiply expression. Since we
2532 // sorted the list, these values are required to be adjacent.
2533 Type *Ty = Ops[0]->getType();
2534 bool FoundMatch = false;
2535 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2536 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2537 // Scan ahead to count how many equal operands there are.
2538 unsigned Count = 2;
2539 while (i+Count != e && Ops[i+Count] == Ops[i])
2540 ++Count;
2541 // Merge the values into a multiply.
2542 SCEVUse Scale = getConstant(Ty, Count);
2543 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagNone, Depth + 1);
2544 if (Ops.size() == Count)
2545 return Mul;
2546 Ops[i] = Mul;
2547 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2548 --i; e -= Count - 1;
2549 FoundMatch = true;
2550 }
2551 if (FoundMatch)
2552 return getAddExpr(Ops, ExprFlags, Depth + 1);
2553
2554 // Check for truncates. If all the operands are truncated from the same
2555 // type, see if factoring out the truncate would permit the result to be
2556 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2557 // if the contents of the resulting outer trunc fold to something simple.
2558 auto FindTruncSrcType = [&]() -> Type * {
2559 // We're ultimately looking to fold an addrec of truncs and muls of only
2560 // constants and truncs, so if we find any other types of SCEV
2561 // as operands of the addrec then we bail and return nullptr here.
2562 // Otherwise, we return the type of the operand of a trunc that we find.
2563 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2564 return T->getOperand()->getType();
2565 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2566 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2567 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2568 return T->getOperand()->getType();
2569 }
2570 return nullptr;
2571 };
2572 if (auto *SrcType = FindTruncSrcType()) {
2573 SmallVector<SCEVUse, 8> LargeOps;
2574 bool Ok = true;
2575 // Check all the operands to see if they can be represented in the
2576 // source type of the truncate.
2577 for (const SCEV *Op : Ops) {
2579 if (T->getOperand()->getType() != SrcType) {
2580 Ok = false;
2581 break;
2582 }
2583 LargeOps.push_back(T->getOperand());
2584 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2585 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2586 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2587 SmallVector<SCEVUse, 8> LargeMulOps;
2588 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2589 if (const SCEVTruncateExpr *T =
2590 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2591 if (T->getOperand()->getType() != SrcType) {
2592 Ok = false;
2593 break;
2594 }
2595 LargeMulOps.push_back(T->getOperand());
2596 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2597 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2598 } else {
2599 Ok = false;
2600 break;
2601 }
2602 }
2603 if (Ok)
2604 LargeOps.push_back(
2605 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2606 } else {
2607 Ok = false;
2608 break;
2609 }
2610 }
2611 if (Ok) {
2612 // Evaluate the expression in the larger type.
2613 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2614 // If it folds to something simple, use it. Otherwise, don't.
2615 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2616 return getTruncateExpr(Fold, Ty);
2617 }
2618 }
2619
2620 if (Ops.size() == 2) {
2621 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2622 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2623 // C1).
2624 const SCEV *A = Ops[0];
2625 const SCEV *B = Ops[1];
2626 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2627 auto *C = dyn_cast<SCEVConstant>(A);
2628 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2629 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2630 auto C2 = C->getAPInt();
2631 SCEVFlags PreservedFlags = SCEV::FlagNone;
2632
2633 APInt ConstAdd = C1 + C2;
2634 auto AddFlags = AddExpr->getNoWrapFlags();
2635 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2637 ConstAdd.ule(C1)) {
2638 PreservedFlags =
2640 }
2641
2642 // Adding a constant with the same sign and small magnitude is NSW, if the
2643 // original AddExpr was NSW.
2645 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2646 ConstAdd.abs().ule(C1.abs())) {
2647 PreservedFlags =
2649 }
2650
2651 if (PreservedFlags != SCEV::FlagNone) {
2652 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2653 NewOps[0] = getConstant(ConstAdd);
2654 return getAddExpr(NewOps, PreservedFlags);
2655 }
2656 }
2657
2658 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2659 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2660 const SCEVAddExpr *InnerAdd;
2661 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2662 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2663 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2664 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2665 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2667 SCEV::FlagNUW)) {
2668 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2669 }
2670 }
2671 }
2672
2673 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2674 const SCEV *Y;
2675 if (Ops.size() == 2 &&
2676 match(Ops[0],
2678 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2679 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2680
2681 // Skip past any other cast SCEVs.
2682 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2683 ++Idx;
2684
2685 // If there are add operands they would be next.
2686 if (Idx < Ops.size()) {
2687 bool DeletedAdd = false;
2688 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2689 // common NUW flag for expression after inlining. Other flags cannot be
2690 // preserved, because they may depend on the original order of operations.
2691 SCEVFlags CommonFlags = maskFlags(ExprFlags, SCEV::FlagNUW);
2692 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2693 if (Ops.size() > AddOpsInlineThreshold ||
2694 Add->getNumOperands() > AddOpsInlineThreshold)
2695 break;
2696 // If we have an add, expand the add operands onto the end of the operands
2697 // list.
2698 Ops.erase(Ops.begin()+Idx);
2699 append_range(Ops, Add->operands());
2700 DeletedAdd = true;
2701 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2702 }
2703
2704 // If we deleted at least one add, we added operands to the end of the list,
2705 // and they are not necessarily sorted. Recurse to resort and resimplify
2706 // any operands we just acquired.
2707 if (DeletedAdd)
2708 return getAddExpr(Ops, CommonFlags, Depth + 1);
2709 }
2710
2711 // Skip over the add expression until we get to a multiply.
2712 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2713 ++Idx;
2714
2715 // Check to see if there are any folding opportunities present with
2716 // operands multiplied by constant values.
2717 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2718 uint64_t BitWidth = getTypeSizeInBits(Ty);
2721 APInt AccumulatedConstant(BitWidth, 0);
2722 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2723 Ops, APInt(BitWidth, 1), *this)) {
2724 struct APIntCompare {
2725 bool operator()(const APInt &LHS, const APInt &RHS) const {
2726 return LHS.ult(RHS);
2727 }
2728 };
2729
2730 // Some interesting folding opportunity is present, so its worthwhile to
2731 // re-generate the operands list. Group the operands by constant scale,
2732 // to avoid multiplying by the same constant scale multiple times.
2733 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2734 for (SCEVUse NewOp : NewOps)
2735 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2736 // Re-generate the operands list.
2737 Ops.clear();
2738 if (AccumulatedConstant != 0)
2739 Ops.push_back(getConstant(AccumulatedConstant));
2740 for (auto &MulOp : MulOpLists) {
2741 if (MulOp.first == 1) {
2742 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2743 } else if (MulOp.first != 0) {
2744 Ops.push_back(
2745 getMulExpr(getConstant(MulOp.first),
2746 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2747 SCEV::FlagNone, Depth + 1));
2748 }
2749 }
2750 if (Ops.empty())
2751 return getZero(Ty);
2752 if (Ops.size() == 1)
2753 return Ops[0];
2754 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2755 }
2756 }
2757
2758 // Given a SCEVMulExpr and an operand index, return the product of all
2759 // operands except the one at OpIdx.
2760 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2761 if (M->getNumOperands() == 2)
2762 return M->getOperand(OpIdx == 0);
2763 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2764 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2765 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2766 };
2767
2768 // If we are adding something to a multiply expression, make sure the
2769 // something is not already an operand of the multiply. If so, merge it into
2770 // the multiply.
2771 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2772 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2773 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2774 // Scan all terms to find every occurrence of common factor MulOpSCEV
2775 // and fold them in one shot:
2776 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2777 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2778 if (isa<SCEVConstant>(MulOpSCEV))
2779 continue;
2780
2781 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2782 // remaining product for multiply terms containing MulOpSCEV.
2783 SmallVector<SCEVUse, 4> Cofactors;
2784 SmallVector<unsigned, 4> DeadIndices;
2785 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2786 if (MulOpSCEV == Ops[AddOp]) {
2787 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2788 Cofactors.push_back(getOne(Ty));
2789 DeadIndices.push_back(AddOp);
2790 continue;
2791 }
2792
2793 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2794 continue;
2795
2796 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2797 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2798 ++OMulOp) {
2799 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2800 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2801 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2802 DeadIndices.push_back(AddOp);
2803 break;
2804 }
2805 }
2806 }
2807
2808 // Fold all collected cofactors with the anchor multiply's cofactor:
2809 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2810 if (!Cofactors.empty()) {
2811 Cofactors.push_back(StripFactor(Mul, MulOp));
2812
2813 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2814 SCEVUse OuterMul =
2815 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2816
2817 // DeadIndices does not include Idx (the anchor), hence +1.
2818 if (Ops.size() == DeadIndices.size() + 1)
2819 return OuterMul;
2820
2821 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2822 // The -1 adjustment accounts for the shift from removing Idx;
2823 // reverse order means each erasure only shifts later positions,
2824 // which have already been processed.
2825 Ops.erase(Ops.begin() + Idx);
2826 for (unsigned Dead : reverse(DeadIndices))
2827 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2828
2829 Ops.push_back(OuterMul);
2830 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2831 }
2832 }
2833 }
2834
2835 // If there are any add recurrences in the operands list, see if any other
2836 // added values are loop invariant. If so, we can fold them into the
2837 // recurrence.
2838 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2839 ++Idx;
2840
2841 // Scan over all recurrences, trying to fold loop invariants into them.
2842 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2843 // Scan all of the other operands to this add and add them to the vector if
2844 // they are loop invariant w.r.t. the recurrence.
2846 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2847 const Loop *AddRecLoop = AddRec->getLoop();
2848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2849 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2850 LIOps.push_back(Ops[i]);
2851 Ops.erase(Ops.begin()+i);
2852 --i; --e;
2853 }
2854
2855 // If we found some loop invariants, fold them into the recurrence.
2856 if (!LIOps.empty()) {
2857 // Compute nowrap flags for the addition of the loop-invariant ops and
2858 // the addrec. Temporarily push it as an operand for that purpose. These
2859 // flags are valid in the scope of the addrec only.
2860 LIOps.push_back(AddRec);
2861 SCEVFlags Flags = ComputeFlags(LIOps);
2862 LIOps.pop_back();
2863
2864 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2865 LIOps.push_back(AddRec->getStart());
2866
2867 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2868
2869 // It is not in general safe to propagate flags valid on an add within
2870 // the addrec scope to one outside it. We must prove that the inner
2871 // scope is guaranteed to execute if the outer one does to be able to
2872 // safely propagate. We know the program is undefined if poison is
2873 // produced on the inner scoped addrec. We also know that *for this use*
2874 // the outer scoped add can't overflow (because of the flags we just
2875 // computed for the inner scoped add) without the program being undefined.
2876 // Proving that entry to the outer scope neccesitates entry to the inner
2877 // scope, thus proves the program undefined if the flags would be violated
2878 // in the outer scope.
2879 SCEVFlags AddFlags = Flags;
2880 if (AddFlags != SCEV::FlagNone) {
2881 auto *DefI = getDefiningScopeBound(LIOps);
2882 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2883 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2884 AddFlags = SCEV::FlagNone;
2885 }
2886 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2887
2888 // Build the new addrec. Propagate the NUW and NSW flags if both the
2889 // outer add and the inner addrec are guaranteed to have no overflow.
2890 // Always propagate NW.
2891 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2892 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2893
2894 // If all of the other operands were loop invariant, we are done.
2895 if (Ops.size() == 1) return NewRec;
2896
2897 // Otherwise, add the folded AddRec by the non-invariant parts.
2898 for (unsigned i = 0;; ++i)
2899 if (Ops[i] == AddRec) {
2900 Ops[i] = NewRec;
2901 break;
2902 }
2903 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2904 }
2905
2906 // Okay, if there weren't any loop invariants to be folded, check to see if
2907 // there are multiple AddRec's with the same loop induction variable being
2908 // added together. If so, we can fold them.
2909 for (unsigned OtherIdx = Idx+1;
2910 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2911 ++OtherIdx) {
2912 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2913 // so that the 1st found AddRecExpr is dominated by all others.
2914 assert(DT.dominates(
2915 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2916 AddRec->getLoop()->getHeader()) &&
2917 "AddRecExprs are not sorted in reverse dominance order?");
2918 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2919 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2920 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2921 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2922 ++OtherIdx) {
2923 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2924 if (OtherAddRec->getLoop() == AddRecLoop) {
2925 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2926 i != e; ++i) {
2927 if (i >= AddRecOps.size()) {
2928 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2929 break;
2930 }
2931 AddRecOps[i] =
2932 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2933 SCEV::FlagNone, Depth + 1);
2934 }
2935 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2936 }
2937 }
2938 // Step size has changed, so we cannot guarantee no self-wraparound.
2939 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2940 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2941 }
2942 }
2943
2944 // Otherwise couldn't fold anything into this recurrence. Move onto the
2945 // next one.
2946 }
2947
2948 // Okay, it looks like we really DO need an add expr. Check to see if we
2949 // already have one, otherwise create a new one.
2950 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2951 "Tried to add SCEVUse flags after operands changed");
2952 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2953}
2954
2955const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2956 SCEVFlags Flags) {
2959 for (SCEVUse Op : Ops)
2960 ID.AddPointer(Op.getOpaqueValue());
2962 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2963 if (!S) {
2964 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2966 S = new (SCEVAllocator)
2967 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2968 UniqueSCEVs.insert(S, Token);
2969 S->computeAndSetCanonical(*this);
2970 registerUser(S, Ops);
2971 }
2972 S->setNoWrapFlags(Flags);
2973 return S;
2974}
2975
2976const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2977 const Loop *L,
2978 SCEVFlags Flags) {
2979 FoldingSetNodeID ID;
2980 ID.AddInteger(scAddRecExpr);
2981 for (SCEVUse Op : Ops)
2982 ID.AddPointer(Op.getOpaqueValue());
2983 ID.AddPointer(L);
2984 FoldingSetInsertToken Token;
2985 SCEVAddRecExpr *S =
2986 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2987 if (!S) {
2988 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2990 S = new (SCEVAllocator)
2991 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2992 UniqueSCEVs.insert(S, Token);
2993 S->computeAndSetCanonical(*this);
2994 LoopUsers[L].push_back(S);
2995 registerUser(S, Ops);
2996 }
2997 setNoWrapFlags(S, Flags);
2998 return S;
2999}
3000
3001const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3002 SCEVFlags Flags) {
3003 FoldingSetNodeID ID;
3004 ID.AddInteger(scMulExpr);
3005 for (SCEVUse Op : Ops)
3006 ID.AddPointer(Op.getOpaqueValue());
3007 FoldingSetInsertToken Token;
3008 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3009 if (!S) {
3010 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3012 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3013 O, Ops.size());
3014 UniqueSCEVs.insert(S, Token);
3015 S->computeAndSetCanonical(*this);
3016 registerUser(S, Ops);
3017 }
3018 S->setNoWrapFlags(Flags);
3019 return S;
3020}
3021
3022const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3023 FoldingSetNodeID ID;
3024 ID.AddInteger(scUDivExpr);
3025 ID.AddPointer(LHS.getOpaqueValue());
3026 ID.AddPointer(RHS.getOpaqueValue());
3027 FoldingSetInsertToken Token;
3028 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3029 if (!S) {
3030 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3031 UniqueSCEVs.insert(S, Token);
3032 S->computeAndSetCanonical(*this);
3033 registerUser(S, {LHS, RHS});
3034 }
3035 return S;
3036}
3037
3038static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3039 uint64_t k = i*j;
3040 if (j > 1 && k / j != i) Overflow = true;
3041 return k;
3042}
3043
3044/// Compute the result of "n choose k", the binomial coefficient. If an
3045/// intermediate computation overflows, Overflow will be set and the return will
3046/// be garbage. Overflow is not cleared on absence of overflow.
3047static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3048 // We use the multiplicative formula:
3049 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3050 // At each iteration, we take the n-th term of the numeral and divide by the
3051 // (k-n)th term of the denominator. This division will always produce an
3052 // integral result, and helps reduce the chance of overflow in the
3053 // intermediate computations. However, we can still overflow even when the
3054 // final result would fit.
3055
3056 if (n == 0 || n == k) return 1;
3057 if (k > n) return 0;
3058
3059 if (k > n/2)
3060 k = n-k;
3061
3062 uint64_t r = 1;
3063 for (uint64_t i = 1; i <= k; ++i) {
3064 r = umul_ov(r, n-(i-1), Overflow);
3065 r /= i;
3066 }
3067 return r;
3068}
3069
3070/// Determine if any of the operands in this SCEV are a constant or if
3071/// any of the add or multiply expressions in this SCEV contain a constant.
3072static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3073 struct FindConstantInAddMulChain {
3074 bool FoundConstant = false;
3075
3076 bool follow(const SCEV *S) {
3077 FoundConstant |= isa<SCEVConstant>(S);
3078 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3079 }
3080
3081 bool isDone() const {
3082 return FoundConstant;
3083 }
3084 };
3085
3086 FindConstantInAddMulChain F;
3088 ST.visitAll(StartExpr);
3089 return F.FoundConstant;
3090}
3091
3092/// Get a canonical multiply expression, or something simpler if possible.
3094 SCEVFlagsPair Flags, unsigned Depth) {
3095 SCEVFlags ExprFlags = Flags.ExprFlags;
3096 SCEVFlags UseFlags = Flags.UseFlags;
3097 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3098 "only nuw or nsw allowed");
3099 assert(UseFlags == maskFlags(UseFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3100 "only nuw or nsw allowed");
3101 assert(!Ops.empty() && "Cannot get empty mul!");
3102 if (Ops.size() == 1) return Ops[0];
3103#ifndef NDEBUG
3104 Type *ETy = Ops[0]->getType();
3105 assert(!ETy->isPointerTy());
3106 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3107 assert(Ops[i]->getType() == ETy &&
3108 "SCEVMulExpr operand types don't match!");
3109#endif
3110
3111 const SCEV *Folded = constantFoldAndGroupOps(
3112 *this, LI, DT, Ops,
3113 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3114 [](const APInt &C) { return C.isOne(); }, // identity
3115 [](const APInt &C) { return C.isZero(); }); // absorber
3116 if (Folded)
3117 return Folded;
3118
3119#ifndef NDEBUG
3120 // Keep track of operands after constant folding, for verification when adding
3121 // use-specific flags.
3122 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3123#endif
3124
3125 // Delay expensive flag strengthening until necessary.
3126 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3127 return StrengthenNoWrapFlags(this, scMulExpr, Ops, ExprFlags);
3128 };
3129
3130 // Limit recursion calls depth.
3132 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3133
3134 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3135 // Don't strengthen flags if we have no new information.
3136 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3137 if (Mul->getNoWrapFlags(ExprFlags) != ExprFlags)
3138 Mul->setNoWrapFlags(ComputeFlags(Ops));
3139 return {S, UseFlags};
3140 }
3141
3142 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3143 if (Ops.size() == 2) {
3144 // C1*(C2+V) -> C1*C2 + C1*V
3145 // If any of Add's ops are Adds or Muls with a constant, apply this
3146 // transformation as well.
3147 //
3148 // TODO: There are some cases where this transformation is not
3149 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3150 // this transformation should be narrowed down.
3151 const SCEV *Op0, *Op1;
3152 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3154 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3155 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3156 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3157 }
3158
3159 if (Ops[0]->isAllOnesValue()) {
3160 // If we have a mul by -1 of an add, try distributing the -1 among the
3161 // add operands.
3162 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3164 bool AnyFolded = false;
3165 for (const SCEV *AddOp : Add->operands()) {
3166 const SCEV *Mul =
3167 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3168 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3169 NewOps.push_back(Mul);
3170 }
3171 if (AnyFolded)
3172 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3173 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3174 // Negation preserves a recurrence's no self-wrap property.
3176 for (const SCEV *AddRecOp : AddRec->operands())
3177 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3178 SCEV::FlagNone, Depth + 1));
3179 // Let M be the minimum representable signed value. AddRec with nsw
3180 // multiplied by -1 can have signed overflow if and only if it takes a
3181 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3182 // maximum signed value. In all other cases signed overflow is
3183 // impossible.
3184 auto FlagsMask = SCEV::FlagNW;
3185 if (AddRec->hasNoSignedWrap()) {
3186 auto MinInt =
3187 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3188 if (getSignedRangeMin(AddRec) != MinInt)
3190 }
3191 return getAddRecExpr(Operands, AddRec->getLoop(),
3192 AddRec->getNoWrapFlags(FlagsMask));
3193 }
3194 }
3195
3196 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3197 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3198 const SCEVAddExpr *InnerAdd;
3199 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3200 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3201 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3202 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3203 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3205 SCEV::FlagNUW)) {
3206 const SCEV *Res =
3207 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3208 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3209 };
3210 }
3211
3212 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3213 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3214 // of C1, fold to (D /u (C2 /u C1)).
3215 const SCEV *D;
3216 APInt C1V = LHSC->getAPInt();
3217 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3218 // as -1 * 1, as it won't enable additional folds.
3219 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3220 C1V = C1V.abs();
3221 const SCEVConstant *C2;
3222 if (C1V.isPowerOf2() &&
3224 C2->getAPInt().isPowerOf2() &&
3225 C1V.logBase2() <= getMinTrailingZeros(D)) {
3226 const SCEV *NewMul = nullptr;
3227 if (C1V.uge(C2->getAPInt())) {
3228 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3229 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3230 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3231 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3232 }
3233 if (NewMul)
3234 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3235 }
3236 }
3237 }
3238
3239 // Skip over the add expression until we get to a multiply.
3240 unsigned Idx = 0;
3241 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3242 ++Idx;
3243
3244 // If there are mul operands inline them all into this expression.
3245 if (Idx < Ops.size()) {
3246 bool DeletedMul = false;
3247 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3248 if (Ops.size() > MulOpsInlineThreshold)
3249 break;
3250 // If we have an mul, expand the mul operands onto the end of the
3251 // operands list.
3252 Ops.erase(Ops.begin()+Idx);
3253 append_range(Ops, Mul->operands());
3254 DeletedMul = true;
3255 }
3256
3257 // If we deleted at least one mul, we added operands to the end of the
3258 // list, and they are not necessarily sorted. Recurse to resort and
3259 // resimplify any operands we just acquired.
3260 if (DeletedMul)
3261 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3262 }
3263
3264 // If there are any add recurrences in the operands list, see if any other
3265 // added values are loop invariant. If so, we can fold them into the
3266 // recurrence.
3267 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3268 ++Idx;
3269
3270 // Scan over all recurrences, trying to fold loop invariants into them.
3271 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3272 // Scan all of the other operands to this mul and add them to the vector
3273 // if they are loop invariant w.r.t. the recurrence.
3275 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3276 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3277 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3278 LIOps.push_back(Ops[i]);
3279 Ops.erase(Ops.begin()+i);
3280 --i; --e;
3281 }
3282
3283 // If we found some loop invariants, fold them into the recurrence.
3284 if (!LIOps.empty()) {
3285 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3287 NewOps.reserve(AddRec->getNumOperands());
3288 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3289
3290 // If both the mul and addrec are nuw, we can preserve nuw.
3291 // If both the mul and addrec are nsw, we can only preserve nsw if either
3292 // a) they are also nuw, or
3293 // b) all multiplications of addrec operands with scale are nsw.
3294 SCEVFlags Flags = AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3295
3296 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3297 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3298 SCEV::FlagNone, Depth + 1));
3299
3300 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3302 Instruction::Mul, getSignedRange(Scale),
3304 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3305 Flags = clearFlags(Flags, SCEV::FlagNSW);
3306 }
3307 }
3308
3309 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3310
3311 // If all of the other operands were loop invariant, we are done.
3312 if (Ops.size() == 1) return NewRec;
3313
3314 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3315 for (unsigned i = 0;; ++i)
3316 if (Ops[i] == AddRec) {
3317 Ops[i] = NewRec;
3318 break;
3319 }
3320 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3321 }
3322
3323 // Okay, if there weren't any loop invariants to be folded, check to see
3324 // if there are multiple AddRec's with the same loop induction variable
3325 // being multiplied together. If so, we can fold them.
3326
3327 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3328 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3329 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3330 // ]]],+,...up to x=2n}.
3331 // Note that the arguments to choose() are always integers with values
3332 // known at compile time, never SCEV objects.
3333 //
3334 // The implementation avoids pointless extra computations when the two
3335 // addrec's are of different length (mathematically, it's equivalent to
3336 // an infinite stream of zeros on the right).
3337 bool OpsModified = false;
3338 for (unsigned OtherIdx = Idx+1;
3339 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3340 ++OtherIdx) {
3341 const SCEVAddRecExpr *OtherAddRec =
3342 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3343 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3344 continue;
3345
3346 // Limit max number of arguments to avoid creation of unreasonably big
3347 // SCEVAddRecs with very complex operands.
3348 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3349 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3350 continue;
3351
3352 bool Overflow = false;
3353 Type *Ty = AddRec->getType();
3354 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3355 SmallVector<SCEVUse, 7> AddRecOps;
3356 for (int x = 0, xe = AddRec->getNumOperands() +
3357 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3359 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3360 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3361 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3362 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3363 z < ze && !Overflow; ++z) {
3364 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3365 uint64_t Coeff;
3366 if (LargerThan64Bits)
3367 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3368 else
3369 Coeff = Coeff1*Coeff2;
3370 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3371 const SCEV *Term1 = AddRec->getOperand(y-z);
3372 const SCEV *Term2 = OtherAddRec->getOperand(z);
3373 SumOps.push_back(
3374 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3375 }
3376 }
3377 if (SumOps.empty())
3378 SumOps.push_back(getZero(Ty));
3379 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3380 }
3381 if (!Overflow) {
3382 const SCEV *NewAddRec =
3383 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3384 if (Ops.size() == 2) return NewAddRec;
3385 Ops[Idx] = NewAddRec;
3386 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3387 OpsModified = true;
3388 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3389 if (!AddRec)
3390 break;
3391 }
3392 }
3393 if (OpsModified)
3394 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3395
3396 // Otherwise couldn't fold anything into this recurrence. Move onto the
3397 // next one.
3398 }
3399
3400 // Okay, it looks like we really DO need an mul expr. Check to see if we
3401 // already have one, otherwise create a new one.
3402 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3403 "Tried to add SCEVUse flags after operands changed");
3404 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3405}
3406
3407/// Represents an unsigned remainder expression based on unsigned division.
3409 assert(getEffectiveSCEVType(LHS->getType()) ==
3410 getEffectiveSCEVType(RHS->getType()) &&
3411 "SCEVURemExpr operand types don't match!");
3412
3413 // Short-circuit easy cases
3414 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3415 // If constant is one, the result is trivial
3416 if (RHSC->getValue()->isOne())
3417 return getZero(LHS->getType()); // X urem 1 --> 0
3418
3419 // If constant is a power of two, fold into a zext(trunc(LHS)).
3420 if (RHSC->getAPInt().isPowerOf2()) {
3421 Type *FullTy = LHS->getType();
3422 Type *TruncTy =
3423 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3424 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3425 }
3426 }
3427
3428 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3429 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3430 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3431 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3432}
3433
3434/// Get a canonical unsigned division expression, or something simpler if
3435/// possible.
3437 assert(!LHS->getType()->isPointerTy() &&
3438 "SCEVUDivExpr operand can't be pointer!");
3439 assert(LHS->getType() == RHS->getType() &&
3440 "SCEVUDivExpr operand types don't match!");
3441
3442 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3443 return S;
3444
3445 // 0 udiv Y == 0
3446 if (match(LHS, m_scev_Zero()))
3447 return LHS;
3448
3449 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3450 if (RHSC->getValue()->isOne())
3451 return LHS; // X udiv 1 --> x
3452 // If the denominator is zero, the result of the udiv is undefined. Don't
3453 // try to analyze it, because the resolution chosen here may differ from
3454 // the resolution chosen in other parts of the compiler.
3455 if (!RHSC->getValue()->isZero()) {
3456 // Determine if the division can be folded into the operands of
3457 // its operands.
3458 // TODO: Generalize this to non-constants by using known-bits information.
3459 Type *Ty = LHS->getType();
3460 unsigned LZ = RHSC->getAPInt().countl_zero();
3461 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3462 // For non-power-of-two values, effectively round the value up to the
3463 // nearest power of two.
3464 if (!RHSC->getAPInt().isPowerOf2())
3465 ++MaxShiftAmt;
3466 IntegerType *ExtTy =
3467 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3468 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3469 if (const SCEVConstant *Step =
3470 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3471 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3472 const APInt &StepInt = Step->getAPInt();
3473 const APInt &DivInt = RHSC->getAPInt();
3474 if (!StepInt.urem(DivInt) &&
3475 getZeroExtendExpr(AR, ExtTy) ==
3476 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3477 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3478 SCEV::FlagNone)) {
3480 for (const SCEV *Op : AR->operands())
3481 Operands.push_back(getUDivExpr(Op, RHS));
3482 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3483 }
3484 /// Get a canonical UDivExpr for a recurrence.
3485 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3486 const APInt *StartRem;
3487 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3488 m_scev_APInt(StartRem))) {
3489 bool NoWrap =
3490 getZeroExtendExpr(AR, ExtTy) ==
3491 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3492 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3494
3495 // With N <= C and both N, C as powers-of-2, the transformation
3496 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3497 // if wrapping occurs, as the division results remain equivalent for
3498 // all offsets in [[(X - X%N), X).
3499 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3500 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3501 // Only fold if the subtraction can be folded in the start
3502 // expression.
3503 const SCEV *NewStart =
3504 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3505 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3506 !isa<SCEVAddExpr>(NewStart)) {
3507 const SCEV *NewLHS =
3508 getAddRecExpr(NewStart, Step, AR->getLoop(),
3509 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3510 if (LHS != NewLHS)
3511 return getUDivExpr(NewLHS, RHS);
3512 }
3513 }
3514 }
3515 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3516 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3517 if (M->hasNoUnsignedWrap()) {
3518 // Find an operand that's safely divisible.
3519 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3520 const SCEV *Op = M->getOperand(i);
3521 const SCEV *Div = getUDivExpr(Op, RHSC);
3522 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3523 SmallVector<SCEVUse, 4> Operands(M->operands());
3524 Operands[i] = Div;
3525 return getMulExpr(Operands);
3526 }
3527 }
3528
3529 // Even if it's not divisible, try to remove a common factor.
3530 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3531 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3532 RHSC->getAPInt());
3533 if (!Factor.isIntN(1)) {
3534 SmallVector<SCEVUse, 2> NewOperands;
3535 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3536 append_range(NewOperands, M->operands().drop_front());
3537 const SCEV *NewMul = getMulExpr(NewOperands);
3538 return getUDivExpr(NewMul,
3539 getConstant(RHSC->getAPInt().udiv(Factor)));
3540 }
3541 }
3542 }
3543 }
3544
3545 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3546 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3547 if (auto *DivisorConstant =
3548 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3549 bool Overflow = false;
3550 APInt NewRHS =
3551 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3552 if (Overflow) {
3553 return getConstant(RHSC->getType(), 0, false);
3554 }
3555 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3556 }
3557 }
3558
3559 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3560 // B/C can be folded.
3561 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3562 if (A->hasNoUnsignedWrap()) {
3564 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3565 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3566 if (isa<SCEVUDivExpr>(Op) ||
3567 getMulExpr(Op, RHS) != A->getOperand(i))
3568 break;
3569 Operands.push_back(Op);
3570 }
3571 if (Operands.size() == A->getNumOperands())
3572 return getAddExpr(Operands);
3573 }
3574 }
3575
3576 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3577 // This is an idiom for rounding A up to the next multiple of N, where A
3578 // is aready known to be a multiple of M. In this case, instcombine can
3579 // see that some low bits of the added constant are unused, so can clear
3580 // them, but we want to canonicalise to set the low bits. This makes the
3581 // pattern easier to match, without needing to check for known bits in
3582 // A*M.
3583 const APInt &N = RHSC->getAPInt();
3584 const APInt *NMinusM, *M;
3585 const SCEV *A;
3586 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3587 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3588 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3589 *NMinusM == N - *M) {
3590 return getUDivExpr(
3592 RHS);
3593 }
3594 }
3595
3596 // Fold if both operands are constant.
3597 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3598 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3599 }
3600 }
3601
3602 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3603 const APInt *NegC, *C;
3604 if (match(LHS,
3607 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3608 return getZero(LHS->getType());
3609
3610 // (%a * %b)<nuw> / %b -> %a
3611 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3612 if (Mul && Mul->hasNoUnsignedWrap()) {
3613 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3614 if (Mul->getOperand(i) == RHS) {
3616 append_range(Operands, Mul->operands().take_front(i));
3617 append_range(Operands, Mul->operands().drop_front(i + 1));
3618 return getMulExpr(Operands);
3619 }
3620 }
3621 }
3622
3623 // TODO: Generalize to handle any common factors.
3624 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3625 const SCEV *NewLHS, *NewRHS;
3626 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3627 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3628 return getUDivExpr(NewLHS, NewRHS);
3629
3630 return getOrCreateUDivExpr(LHS, RHS);
3631}
3632
3633/// Get a canonical unsigned division expression, or something simpler if
3634/// possible. There is no representation for an exact udiv in SCEV IR, but we
3635/// can attempt to optimize it prior to construction.
3637 // Currently there is no exact specific logic.
3638
3639 return getUDivExpr(LHS, RHS);
3640}
3641
3642/// Get an add recurrence expression for the specified loop. Simplify the
3643/// expression as much as possible.
3645 const Loop *L, SCEVFlagsPair Flags) {
3647 Operands.push_back(Start);
3648 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3649 if (StepChrec->getLoop() == L) {
3650 append_range(Operands, StepChrec->operands());
3651 // The use flags describe the two-operand recurrence, not the flattened
3652 // one built here, so drop them just like the expression's NUW/NSW.
3653 return getAddRecExpr(Operands, L,
3654 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3655 }
3656
3657 Operands.push_back(Step);
3658 return getAddRecExpr(Operands, L, Flags);
3659}
3660
3661/// Get an add recurrence expression for the specified loop. Simplify the
3662/// expression as much as possible.
3664 const Loop *L, SCEVFlagsPair NWFlags) {
3665 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3666 SCEVFlags UseFlags = NWFlags.UseFlags;
3667 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3668 "only nuw or nsw allowed");
3669 if (Operands.size() == 1) return Operands[0];
3670#ifndef NDEBUG
3672 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3673 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3674 "SCEVAddRecExpr operand types don't match!");
3675 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3676 }
3677 for (const SCEV *Op : Operands)
3679 "SCEVAddRecExpr operand is not available at loop entry!");
3680
3681 // Keep track of the original operands, for verification when adding
3682 // use-specific flags.
3683 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3684#endif
3685
3686 if (Operands.back()->isZero()) {
3687 Operands.pop_back();
3688 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3689 }
3690
3691 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3692 // use that information to infer NUW and NSW flags. However, computing a
3693 // BE count requires calling getAddRecExpr, so we may not yet have a
3694 // meaningful BE count at this point (and if we don't, we'd be stuck
3695 // with a SCEVCouldNotCompute as the cached BE count).
3696
3697 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3698
3699 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3700 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3701 const Loop *NestedLoop = NestedAR->getLoop();
3702 if (L->contains(NestedLoop)
3703 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3704 : (!NestedLoop->contains(L) &&
3705 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3706 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3707 Operands[0] = NestedAR->getStart();
3708 // AddRecs require their operands be loop-invariant with respect to their
3709 // loops. Don't perform this transformation if it would break this
3710 // requirement.
3711 bool AllInvariant = all_of(
3712 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3713
3714 if (AllInvariant) {
3715 // Create a recurrence for the outer loop with the same step size.
3716 //
3717 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3718 // inner recurrence has the same property.
3719 SCEVFlags OuterFlags =
3720 maskFlags(ExprFlags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3721
3722 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3723 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3724 return isLoopInvariant(Op, NestedLoop);
3725 });
3726
3727 if (AllInvariant) {
3728 // Ok, both add recurrences are valid after the transformation.
3729 //
3730 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3731 // the outer recurrence has the same property.
3732 SCEVFlags InnerFlags =
3733 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | ExprFlags);
3734 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3735 }
3736 }
3737 // Reset Operands to its original state.
3738 Operands[0] = NestedAR;
3739 }
3740 }
3741
3742 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3743 // already have one, otherwise create a new one.
3744 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3745 "Tried to add SCEVUse flags after operands changed");
3746 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3747}
3748
3750 ArrayRef<SCEVUse> IndexExprs) {
3751 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3752 // getSCEV(Base)->getType() has the same address space as Base->getType()
3753 // because SCEV::getType() preserves the address space.
3754 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3755 if (NW != GEPNoWrapFlags::none()) {
3756 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3757 // but to do that, we have to ensure that said flag is valid in the entire
3758 // defined scope of the SCEV.
3759 // TODO: non-instructions have global scope. We might be able to prove
3760 // some global scope cases
3761 auto *GEPI = dyn_cast<Instruction>(GEP);
3762 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3763 NW = GEPNoWrapFlags::none();
3764 }
3765
3766 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3767}
3768
3770 ArrayRef<SCEVUse> IndexExprs,
3771 Type *SrcElementTy, GEPNoWrapFlags NW) {
3772 SCEVFlags OffsetWrap = SCEV::FlagNone;
3773 if (NW.hasNoUnsignedSignedWrap())
3774 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3775 if (NW.hasNoUnsignedWrap())
3776 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3777
3778 Type *CurTy = BaseExpr->getType();
3779 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3780 bool FirstIter = true;
3782 for (SCEVUse IndexExpr : IndexExprs) {
3783 // Compute the (potentially symbolic) offset in bytes for this index.
3784 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3785 // For a struct, add the member offset.
3786 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3787 unsigned FieldNo = Index->getZExtValue();
3788 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3789 Offsets.push_back(FieldOffset);
3790
3791 // Update CurTy to the type of the field at Index.
3792 CurTy = STy->getTypeAtIndex(Index);
3793 } else {
3794 // Update CurTy to its element type.
3795 if (FirstIter) {
3796 assert(isa<PointerType>(CurTy) &&
3797 "The first index of a GEP indexes a pointer");
3798 CurTy = SrcElementTy;
3799 FirstIter = false;
3800 } else {
3801 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3802 }
3803 // For an array, add the element offset, explicitly scaled.
3804 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3805 // Getelementptr indices are signed.
3806 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3807
3808 // Multiply the index by the element size to compute the element offset.
3809 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3810 Offsets.push_back(LocalOffset);
3811 }
3812 }
3813
3814 // Handle degenerate case of GEP without offsets.
3815 if (Offsets.empty())
3816 return BaseExpr;
3817
3818 // Add the offsets together, assuming nsw if inbounds.
3819 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3820 // Add the base address and the offset. We cannot use the nsw flag, as the
3821 // base address is unsigned. However, if we know that the offset is
3822 // non-negative, we can use nuw.
3823 bool NUW = NW.hasNoUnsignedWrap() ||
3825 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3826 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3827 assert(BaseExpr->getType() == GEPExpr->getType() &&
3828 "GEP should not change type mid-flight.");
3829 return GEPExpr;
3830}
3831
3832SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3834 const Loop *L) {
3835 assert((SCEVType != scAddRecExpr || L) &&
3836 "L must be passed to find existing AddRecs");
3838 ID.AddInteger(SCEVType);
3839 for (SCEVUse Op : Ops)
3840 ID.AddPointer(Op.getOpaqueValue());
3841 if (L)
3842 ID.AddPointer(L);
3844 return UniqueSCEVs.lookup(ID, Token);
3845}
3846
3847const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3848 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3849 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3850}
3851
3854 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3855 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3856 if (Ops.size() == 1) return Ops[0];
3857#ifndef NDEBUG
3858 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3859 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3860 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3861 "Operand types don't match!");
3862 assert(Ops[0]->getType()->isPointerTy() ==
3863 Ops[i]->getType()->isPointerTy() &&
3864 "min/max should be consistently pointerish");
3865 }
3866#endif
3867
3868 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3869 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3870
3871 const SCEV *Folded = constantFoldAndGroupOps(
3872 *this, LI, DT, Ops,
3873 [&](const APInt &C1, const APInt &C2) {
3874 switch (Kind) {
3875 case scSMaxExpr:
3876 return APIntOps::smax(C1, C2);
3877 case scSMinExpr:
3878 return APIntOps::smin(C1, C2);
3879 case scUMaxExpr:
3880 return APIntOps::umax(C1, C2);
3881 case scUMinExpr:
3882 return APIntOps::umin(C1, C2);
3883 default:
3884 llvm_unreachable("Unknown SCEV min/max opcode");
3885 }
3886 },
3887 [&](const APInt &C) {
3888 // identity
3889 if (IsMax)
3890 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3891 else
3892 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3893 },
3894 [&](const APInt &C) {
3895 // absorber
3896 if (IsMax)
3897 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3898 else
3899 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3900 });
3901 if (Folded)
3902 return Folded;
3903
3904 // Check if we have created the same expression before.
3905 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3906 return S;
3907 }
3908
3909 // Find the first operation of the same kind
3910 unsigned Idx = 0;
3911 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3912 ++Idx;
3913
3914 // Check to see if one of the operands is of the same kind. If so, expand its
3915 // operands onto our operand list, and recurse to simplify.
3916 if (Idx < Ops.size()) {
3917 bool DeletedAny = false;
3918 while (Ops[Idx]->getSCEVType() == Kind) {
3919 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3920 Ops.erase(Ops.begin()+Idx);
3921 append_range(Ops, SMME->operands());
3922 DeletedAny = true;
3923 }
3924
3925 if (DeletedAny)
3926 return getMinMaxExpr(Kind, Ops);
3927 }
3928
3929 // Okay, check to see if the same value occurs in the operand list twice. If
3930 // so, delete one. Since we sorted the list, these values are required to
3931 // be adjacent.
3936 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3937 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3938 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3939 if (Ops[i] == Ops[i + 1] ||
3940 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3941 // X op Y op Y --> X op Y
3942 // X op Y --> X, if we know X, Y are ordered appropriately
3943 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3944 --i;
3945 --e;
3946 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3947 Ops[i + 1])) {
3948 // X op Y --> Y, if we know X, Y are ordered appropriately
3949 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3950 --i;
3951 --e;
3952 }
3953 }
3954
3955 if (Ops.size() == 1) return Ops[0];
3956
3957 assert(!Ops.empty() && "Reduced smax down to nothing!");
3958
3959 // Okay, it looks like we really DO need an expr. Check to see if we
3960 // already have one, otherwise create a new one.
3962 ID.AddInteger(Kind);
3963 for (SCEVUse Op : Ops)
3964 ID.AddPointer(Op.getOpaqueValue());
3966 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3967 if (ExistingSCEV)
3968 return ExistingSCEV;
3969 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3971 SCEV *S = new (SCEVAllocator)
3972 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3973
3974 UniqueSCEVs.insert(S, Token);
3975 S->computeAndSetCanonical(*this);
3976 registerUser(S, Ops);
3977 return S;
3978}
3979
3980namespace {
3981
3982class SCEVSequentialMinMaxDeduplicatingVisitor final
3983 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3984 std::optional<const SCEV *>> {
3985 using RetVal = std::optional<const SCEV *>;
3986
3987 ScalarEvolution &SE;
3988 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3989 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3991
3992 bool canRecurseInto(SCEVTypes Kind) const {
3993 // We can only recurse into the SCEV expression of the same effective type
3994 // as the type of our root SCEV expression.
3995 return RootKind == Kind || NonSequentialRootKind == Kind;
3996 };
3997
3998 RetVal visit(const SCEV *S) {
3999 // Has the whole operand been seen already?
4000 if (!SeenOps.insert(S).second)
4001 return std::nullopt;
4003 SCEVTypes Kind = S->getSCEVType();
4004
4005 if (!canRecurseInto(Kind))
4006 return S;
4007
4008 auto *NAry = cast<SCEVNAryExpr>(S);
4009 SmallVector<SCEVUse> NewOps;
4010 bool Changed = visit(Kind, NAry->operands(), NewOps);
4011
4012 if (!Changed)
4013 return S;
4014 if (NewOps.empty())
4015 return std::nullopt;
4016
4018 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4019 : SE.getMinMaxExpr(Kind, NewOps);
4020 }
4021 return S;
4022 }
4023
4024public:
4025 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4026 SCEVTypes RootKind)
4027 : SE(SE), RootKind(RootKind),
4028 NonSequentialRootKind(
4029 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4030 RootKind)) {}
4031
4032 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4033 SmallVectorImpl<SCEVUse> &NewOps) {
4034 bool Changed = false;
4036 Ops.reserve(OrigOps.size());
4037
4038 for (const SCEV *Op : OrigOps) {
4039 RetVal NewOp = visit(Op);
4040 if (NewOp != Op)
4041 Changed = true;
4042 if (NewOp)
4043 Ops.emplace_back(*NewOp);
4044 }
4045
4046 if (Changed)
4047 NewOps = std::move(Ops);
4048 return Changed;
4049 }
4050};
4051
4052} // namespace
4053
4055 switch (Kind) {
4056 case scConstant:
4057 case scVScale:
4058 case scTruncate:
4059 case scZeroExtend:
4060 case scSignExtend:
4061 case scPtrToAddr:
4062 case scAddExpr:
4063 case scMulExpr:
4064 case scUDivExpr:
4065 case scAddRecExpr:
4066 case scUMaxExpr:
4067 case scSMaxExpr:
4068 case scUMinExpr:
4069 case scSMinExpr:
4070 case scUnknown:
4071 // If any operand is poison, the whole expression is poison.
4072 return true;
4074 // FIXME: if the *first* operand is poison, the whole expression is poison.
4075 return false; // Pessimistically, say that it does not propagate poison.
4076 case scCouldNotCompute:
4077 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4078 }
4079 llvm_unreachable("Unknown SCEV kind!");
4080}
4081
4082namespace {
4083// The only way poison may be introduced in a SCEV expression is from a
4084// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4085// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4086// introduce poison -- they encode guaranteed, non-speculated knowledge.
4087//
4088// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4089// with the notable exception of umin_seq, where only poison from the first
4090// operand is (unconditionally) propagated.
4091struct SCEVPoisonCollector {
4092 bool LookThroughMaybePoisonBlocking;
4093 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4094 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4095 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4096
4097 bool follow(const SCEV *S) {
4098 if (!LookThroughMaybePoisonBlocking &&
4100 return false;
4101
4102 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4103 if (!isGuaranteedNotToBePoison(SU->getValue()))
4104 MaybePoison.insert(SU);
4105 }
4106 return true;
4107 }
4108 bool isDone() const { return false; }
4109};
4110} // namespace
4111
4112/// Return true if V is poison given that AssumedPoison is already poison.
4113static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4114 // First collect all SCEVs that might result in AssumedPoison to be poison.
4115 // We need to look through potentially poison-blocking operations here,
4116 // because we want to find all SCEVs that *might* result in poison, not only
4117 // those that are *required* to.
4118 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4119 visitAll(AssumedPoison, PC1);
4120
4121 // AssumedPoison is never poison. As the assumption is false, the implication
4122 // is true. Don't bother walking the other SCEV in this case.
4123 if (PC1.MaybePoison.empty())
4124 return true;
4125
4126 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4127 // as well. We cannot look through potentially poison-blocking operations
4128 // here, as their arguments only *may* make the result poison.
4129 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4130 visitAll(S, PC2);
4131
4132 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4133 // it will also make S poison by being part of PC2.MaybePoison.
4134 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4135}
4136
4138 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4139 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4140 visitAll(S, PC);
4141 for (const SCEVUnknown *SU : PC.MaybePoison)
4142 Result.insert(SU->getValue());
4143}
4144
4146 const SCEV *S, Instruction *I,
4147 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4148 // If the instruction cannot be poison, it's always safe to reuse.
4150 return true;
4151
4152 // Otherwise, it is possible that I is more poisonous that S. Collect the
4153 // poison-contributors of S, and then check whether I has any additional
4154 // poison-contributors. Poison that is contributed through poison-generating
4155 // flags is handled by dropping those flags instead.
4157 getPoisonGeneratingValues(PoisonVals, S);
4158
4159 SmallVector<Value *> Worklist;
4161 Worklist.push_back(I);
4162 unsigned NumVisitedInsts = 0;
4163 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4164 while (!Worklist.empty()) {
4165 Value *V = Worklist.pop_back_val();
4166 if (!Visited.insert(V).second)
4167 continue;
4168
4169 // Either the value can't be poison, or the S would also be poison if it
4170 // is.
4171 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4172 continue;
4173
4174 // Avoid walking large instruction graphs.
4175 if (++NumVisitedInsts > InstLimit)
4176 return false;
4177
4178 auto *I = dyn_cast<Instruction>(V);
4179 if (!I)
4180 return false;
4181
4182 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4183 // can't replace an arbitrary add with disjoint or, even if we drop the
4184 // flag. We would need to convert the or into an add.
4185 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4186 if (PDI->isDisjoint())
4187 return false;
4188
4189 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4190 // because SCEV currently assumes it can't be poison. Remove this special
4191 // case once we proper model when vscale can be poison.
4192 if (auto *II = dyn_cast<IntrinsicInst>(I);
4193 II && II->getIntrinsicID() == Intrinsic::vscale)
4194 continue;
4195
4196 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4197 return false;
4198
4199 // If the instruction can't create poison, we can recurse to its operands.
4200 if (I->hasPoisonGeneratingAnnotations())
4201 DropPoisonGeneratingInsts.push_back(I);
4202
4203 llvm::append_range(Worklist, I->operands());
4204 }
4205 return true;
4206}
4207
4208const SCEV *
4211 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4212 "Not a SCEVSequentialMinMaxExpr!");
4213 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4214 if (Ops.size() == 1)
4215 return Ops[0];
4216#ifndef NDEBUG
4217 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4218 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4219 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4220 "Operand types don't match!");
4221 assert(Ops[0]->getType()->isPointerTy() ==
4222 Ops[i]->getType()->isPointerTy() &&
4223 "min/max should be consistently pointerish");
4224 }
4225#endif
4226
4227 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4228 // so we can *NOT* do any kind of sorting of the expressions!
4229
4230 // Check if we have created the same expression before.
4231 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4232 return S;
4233
4234 // FIXME: there are *some* simplifications that we can do here.
4235
4236 // Keep only the first instance of an operand.
4237 {
4238 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4239 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4240 if (Changed)
4241 return getSequentialMinMaxExpr(Kind, Ops);
4242 }
4243
4244 // Check to see if one of the operands is of the same kind. If so, expand its
4245 // operands onto our operand list, and recurse to simplify.
4246 {
4247 unsigned Idx = 0;
4248 bool DeletedAny = false;
4249 while (Idx < Ops.size()) {
4250 if (Ops[Idx]->getSCEVType() != Kind) {
4251 ++Idx;
4252 continue;
4253 }
4254 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4255 Ops.erase(Ops.begin() + Idx);
4256 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4257 SMME->operands().end());
4258 DeletedAny = true;
4259 }
4260
4261 if (DeletedAny)
4262 return getSequentialMinMaxExpr(Kind, Ops);
4263 }
4264
4265 const SCEV *SaturationPoint;
4267 switch (Kind) {
4269 SaturationPoint = getZero(Ops[0]->getType());
4270 Pred = ICmpInst::ICMP_ULE;
4271 break;
4272 default:
4273 llvm_unreachable("Not a sequential min/max type.");
4274 }
4275
4276 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4277 if (!isGuaranteedNotToCauseUB(Ops[i]))
4278 continue;
4279 // We can replace %x umin_seq %y with %x umin %y if either:
4280 // * %y being poison implies %x is also poison.
4281 // * %x cannot be the saturating value (e.g. zero for umin).
4282 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4283 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4284 SaturationPoint)) {
4285 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4286 Ops[i - 1] = getMinMaxExpr(
4288 SeqOps);
4289 Ops.erase(Ops.begin() + i);
4290 return getSequentialMinMaxExpr(Kind, Ops);
4291 }
4292 // Fold %x umin_seq %y to %x if %x ule %y.
4293 // TODO: We might be able to prove the predicate for a later operand.
4294 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4295 Ops.erase(Ops.begin() + i);
4296 return getSequentialMinMaxExpr(Kind, Ops);
4297 }
4298 }
4299
4300 // Okay, it looks like we really DO need an expr. Check to see if we
4301 // already have one, otherwise create a new one.
4303 ID.AddInteger(Kind);
4304 for (SCEVUse Op : Ops)
4305 ID.AddPointer(Op.getOpaqueValue());
4307 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4308 if (ExistingSCEV)
4309 return ExistingSCEV;
4310
4311 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4313 SCEV *S = new (SCEVAllocator)
4314 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4315
4316 UniqueSCEVs.insert(S, Token);
4317 S->computeAndSetCanonical(*this);
4318 registerUser(S, Ops);
4319 return S;
4320}
4321
4326
4330
4335
4339
4344
4348
4350 bool Sequential) {
4351 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4352 return getUMinExpr(Ops, Sequential);
4353}
4354
4360
4361const SCEV *
4363 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4364 if (Size.isScalable())
4365 Res = getMulExpr(Res, getVScale(IntTy));
4366 return Res;
4367}
4368
4370 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4371}
4372
4374 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4375}
4376
4378 StructType *STy,
4379 unsigned FieldNo) {
4380 // We can bypass creating a target-independent constant expression and then
4381 // folding it back into a ConstantInt. This is just a compile-time
4382 // optimization.
4383 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4384 assert(!SL->getSizeInBits().isScalable() &&
4385 "Cannot get offset for structure containing scalable vector types");
4386 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4387}
4388
4390 // Don't attempt to do anything other than create a SCEVUnknown object
4391 // here. createSCEV only calls getUnknown after checking for all other
4392 // interesting possibilities, and any other code that calls getUnknown
4393 // is doing so in order to hide a value from SCEV canonicalization.
4394
4397 ID.AddPointer(V);
4399 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4400 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4401 "Stale SCEVUnknown in uniquing map!");
4402 return S;
4403 }
4404 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4405 FirstUnknown, NextUnknownOrderID++);
4406 FirstUnknown = cast<SCEVUnknown>(S);
4407 UniqueSCEVs.insert(S, Token);
4408 S->computeAndSetCanonical(*this);
4409 return S;
4410}
4411
4412//===----------------------------------------------------------------------===//
4413// Basic SCEV Analysis and PHI Idiom Recognition Code
4414//
4415
4416/// Test if values of the given type are analyzable within the SCEV
4417/// framework. This primarily includes integer types, and it can optionally
4418/// include pointer types if the ScalarEvolution class has access to
4419/// target-specific information.
4421 // Integers and pointers are always SCEVable.
4422 return Ty->isIntOrPtrTy();
4423}
4424
4425/// Return the size in bits of the specified type, for which isSCEVable must
4426/// return true.
4428 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4429 if (Ty->isPointerTy())
4431 return getDataLayout().getTypeSizeInBits(Ty);
4432}
4433
4434/// Return a type with the same bitwidth as the given type and which represents
4435/// how SCEV will treat the given type, for which isSCEVable must return
4436/// true. For pointer types, this is the pointer index sized integer type.
4438 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4439
4440 if (Ty->isIntegerTy())
4441 return Ty;
4442
4443 // The only other support type is pointer.
4444 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4445 return getDataLayout().getIndexType(Ty);
4446}
4447
4449 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4450}
4451
4453 const SCEV *B) {
4454 /// For a valid use point to exist, the defining scope of one operand
4455 /// must dominate the other.
4456 bool PreciseA, PreciseB;
4457 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4458 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4459 if (!PreciseA || !PreciseB)
4460 // Can't tell.
4461 return false;
4462 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4463 DT.dominates(ScopeB, ScopeA);
4464}
4465
4467 return CouldNotCompute.get();
4468}
4469
4470bool ScalarEvolution::checkValidity(const SCEV *S) const {
4471 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4472 auto *SU = dyn_cast<SCEVUnknown>(S);
4473 return SU && SU->getValue() == nullptr;
4474 });
4475
4476 return !ContainsNulls;
4477}
4478
4480 HasRecMapType::iterator I = HasRecMap.find(S);
4481 if (I != HasRecMap.end())
4482 return I->second;
4483
4484 bool FoundAddRec =
4485 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4486 HasRecMap.insert({S, FoundAddRec});
4487 return FoundAddRec;
4488}
4489
4490/// Return the ValueOffsetPair set for \p S. \p S can be represented
4491/// by the value and offset from any ValueOffsetPair in the set.
4492ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4493 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4494 if (SI == ExprValueMap.end())
4495 return {};
4496 return SI->second.getArrayRef();
4497}
4498
4499/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4500/// cannot be used separately. eraseValueFromMap should be used to remove
4501/// V from ValueExprMap and ExprValueMap at the same time.
4502void ScalarEvolution::eraseValueFromMap(Value *V) {
4503 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4504 if (I != ValueExprMap.end()) {
4505 auto EVIt = ExprValueMap.find(I->second);
4506 bool Removed = EVIt->second.remove(V);
4507 (void) Removed;
4508 assert(Removed && "Value not in ExprValueMap?");
4509 ValueExprMap.erase(I);
4510 }
4511}
4512
4513void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4514 // A recursive query may have already computed the SCEV. It should be
4515 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4516 // inferred nowrap flags.
4517 auto It = ValueExprMap.find_as(V);
4518 if (It == ValueExprMap.end()) {
4519 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4520 ExprValueMap[S].insert(V);
4521 }
4522}
4523
4524/// Return an existing SCEV if it exists, otherwise analyze the expression and
4525/// create a new one.
4527 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4528
4529 if (const SCEV *S = getExistingSCEV(V))
4530 return S;
4531 return createSCEVIter(V);
4532}
4533
4535 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4536
4537 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4538 if (I != ValueExprMap.end()) {
4539 const SCEV *S = I->second;
4540 assert(checkValidity(S) &&
4541 "existing SCEV has not been properly invalidated");
4542 return S;
4543 }
4544 return nullptr;
4545}
4546
4547/// Return a SCEV corresponding to -V = -1*V
4549 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4550 return getConstant(
4551 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4552
4553 Type *Ty = V->getType();
4554 Ty = getEffectiveSCEVType(Ty);
4555 return getMulExpr(V, getMinusOne(Ty), Flags);
4556}
4557
4558/// If Expr computes ~A, return A else return nullptr
4559static const SCEV *MatchNotExpr(const SCEV *Expr) {
4560 const SCEV *MulOp;
4561 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4562 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4563 return MulOp;
4564 return nullptr;
4565}
4566
4567/// Return a SCEV corresponding to ~V = -1-V
4569 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4570
4571 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4572 return getConstant(
4573 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4574
4575 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4576 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4577 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4578 SmallVector<SCEVUse, 2> MatchedOperands;
4579 for (const SCEV *Operand : MME->operands()) {
4580 const SCEV *Matched = MatchNotExpr(Operand);
4581 if (!Matched)
4582 return (const SCEV *)nullptr;
4583 MatchedOperands.push_back(Matched);
4584 }
4585 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4586 MatchedOperands);
4587 };
4588 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4589 return Replaced;
4590 }
4591
4592 Type *Ty = V->getType();
4593 Ty = getEffectiveSCEVType(Ty);
4594 return getMinusSCEV(getMinusOne(Ty), V);
4595}
4596
4598 assert(P->getType()->isPointerTy());
4599
4600 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4601 // The base of an AddRec is the first operand.
4602 SmallVector<SCEVUse> Ops{AddRec->operands()};
4603 Ops[0] = removePointerBase(Ops[0]);
4604 // Don't try to transfer nowrap flags for now. We could in some cases
4605 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4606 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4607 }
4608 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4609 // The base of an Add is the pointer operand.
4610 SmallVector<SCEVUse> Ops{Add->operands()};
4611 SCEVUse *PtrOp = nullptr;
4612 for (SCEVUse &AddOp : Ops) {
4613 if (AddOp->getType()->isPointerTy()) {
4614 assert(!PtrOp && "Cannot have multiple pointer ops");
4615 PtrOp = &AddOp;
4616 }
4617 }
4618 *PtrOp = removePointerBase(*PtrOp);
4619 // Don't try to transfer nowrap flags for now. We could in some cases
4620 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4621 return getAddExpr(Ops);
4622 }
4623 // Any other expression must be a pointer base.
4624 return getZero(P->getType());
4625}
4626
4628 SCEVFlags Flags, unsigned Depth) {
4629 // Fast path: X - X --> 0.
4630 if (LHS == RHS)
4631 return getZero(LHS->getType());
4632
4633 // If we subtract two pointers with different pointer bases, bail.
4634 // Eventually, we're going to add an assertion to getMulExpr that we
4635 // can't multiply by a pointer.
4636 if (RHS->getType()->isPointerTy()) {
4637 if (!LHS->getType()->isPointerTy() ||
4638 getPointerBase(LHS) != getPointerBase(RHS))
4639 return getCouldNotCompute();
4640 LHS = removePointerBase(LHS);
4641 RHS = removePointerBase(RHS);
4642 }
4643
4644 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4645 // makes it so that we cannot make much use of NUW.
4646 auto AddFlags = SCEV::FlagNone;
4647 const bool RHSIsNotMinSigned =
4649 if (hasFlags(Flags, SCEV::FlagNSW)) {
4650 // Let M be the minimum representable signed value. Then (-1)*RHS
4651 // signed-wraps if and only if RHS is M. That can happen even for
4652 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4653 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4654 // (-1)*RHS, we need to prove that RHS != M.
4655 //
4656 // If LHS is non-negative and we know that LHS - RHS does not
4657 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4658 // either by proving that RHS > M or that LHS >= 0.
4659 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4660 AddFlags = SCEV::FlagNSW;
4661 }
4662 }
4663
4664 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4665 // RHS is NSW and LHS >= 0.
4666 //
4667 // The difficulty here is that the NSW flag may have been proven
4668 // relative to a loop that is to be found in a recurrence in LHS and
4669 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4670 // larger scope than intended.
4671 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4672
4673 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4674}
4675
4677 unsigned Depth) {
4678 Type *SrcTy = V->getType();
4679 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4680 "Cannot truncate or zero extend with non-integer arguments!");
4681 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4682 return V; // No conversion
4683 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4684 return getTruncateExpr(V, Ty, Depth);
4685 return getZeroExtendExpr(V, Ty, Depth);
4686}
4687
4689 unsigned Depth) {
4690 Type *SrcTy = V->getType();
4691 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4692 "Cannot truncate or zero extend with non-integer arguments!");
4693 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4694 return V; // No conversion
4695 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4696 return getTruncateExpr(V, Ty, Depth);
4697 return getSignExtendExpr(V, Ty, Depth);
4698}
4699
4701 Type *SrcTy = V->getType();
4702 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4703 "Cannot noop or zero extend with non-integer arguments!");
4705 "getNoopOrZeroExtend cannot truncate!");
4706 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4707 return V; // No conversion
4708 return getZeroExtendExpr(V, Ty);
4709}
4710
4712 Type *SrcTy = V->getType();
4713 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4714 "Cannot noop or sign extend with non-integer arguments!");
4716 "getNoopOrSignExtend cannot truncate!");
4717 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4718 return V; // No conversion
4719 return getSignExtendExpr(V, Ty);
4720}
4721
4723 Type *SrcTy = V->getType();
4724 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4725 "Cannot noop or any extend with non-integer arguments!");
4727 "getNoopOrAnyExtend cannot truncate!");
4728 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4729 return V; // No conversion
4730 return getAnyExtendExpr(V, Ty);
4731}
4732
4734 Type *SrcTy = V->getType();
4735 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4736 "Cannot truncate or noop with non-integer arguments!");
4738 "getTruncateOrNoop cannot extend!");
4739 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4740 return V; // No conversion
4741 return getTruncateExpr(V, Ty);
4742}
4743
4745 const SCEV *RHS) {
4746 const SCEV *PromotedLHS = LHS;
4747 const SCEV *PromotedRHS = RHS;
4748
4749 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4750 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4751 else
4752 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4753
4754 return getUMaxExpr(PromotedLHS, PromotedRHS);
4755}
4756
4758 const SCEV *RHS,
4759 bool Sequential) {
4760 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4761 return getUMinFromMismatchedTypes(Ops, Sequential);
4762}
4763
4764const SCEV *
4766 bool Sequential) {
4767 assert(!Ops.empty() && "At least one operand must be!");
4768 // Trivial case.
4769 if (Ops.size() == 1)
4770 return Ops[0];
4771
4772 // Find the max type first.
4773 Type *MaxType = nullptr;
4774 for (SCEVUse S : Ops)
4775 if (MaxType)
4776 MaxType = getWiderType(MaxType, S->getType());
4777 else
4778 MaxType = S->getType();
4779 assert(MaxType && "Failed to find maximum type!");
4780
4781 // Extend all ops to max type.
4782 SmallVector<SCEVUse, 2> PromotedOps;
4783 for (SCEVUse S : Ops)
4784 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4785
4786 // Generate umin.
4787 return getUMinExpr(PromotedOps, Sequential);
4788}
4789
4791 // A pointer operand may evaluate to a nonpointer expression, such as null.
4792 if (!V->getType()->isPointerTy())
4793 return V;
4794
4795 while (true) {
4796 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4797 V = AddRec->getStart();
4798 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4799 const SCEV *PtrOp = nullptr;
4800 for (const SCEV *AddOp : Add->operands()) {
4801 if (AddOp->getType()->isPointerTy()) {
4802 assert(!PtrOp && "Cannot have multiple pointer ops");
4803 PtrOp = AddOp;
4804 }
4805 }
4806 assert(PtrOp && "Must have pointer op");
4807 V = PtrOp;
4808 } else // Not something we can look further into.
4809 return V;
4810 }
4811}
4812
4813/// Push users of the given Instruction onto the given Worklist.
4817 // Push the def-use children onto the Worklist stack.
4818 for (User *U : I->users()) {
4819 auto *UserInsn = cast<Instruction>(U);
4820 if (Visited.insert(UserInsn).second)
4821 Worklist.push_back(UserInsn);
4822 }
4823}
4824
4825namespace {
4826
4827/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4828/// expression in case its Loop is L. If it is not L then
4829/// if IgnoreOtherLoops is true then use AddRec itself
4830/// otherwise rewrite cannot be done.
4831/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4832class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4833public:
4834 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4835 bool IgnoreOtherLoops = true) {
4836 SCEVInitRewriter Rewriter(L, SE);
4837 const SCEV *Result = Rewriter.visit(S);
4838 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4839 return SE.getCouldNotCompute();
4840 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4841 ? SE.getCouldNotCompute()
4842 : Result;
4843 }
4844
4845 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4846 if (!SE.isLoopInvariant(Expr, L))
4847 SeenLoopVariantSCEVUnknown = true;
4848 return Expr;
4849 }
4850
4851 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4852 // Only re-write AddRecExprs for this loop.
4853 if (Expr->getLoop() == L)
4854 return Expr->getStart();
4855 SeenOtherLoops = true;
4856 return Expr;
4857 }
4858
4859 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4860
4861 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4862
4863private:
4864 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4865 : SCEVRewriteVisitor(SE), L(L) {}
4866
4867 const Loop *L;
4868 bool SeenLoopVariantSCEVUnknown = false;
4869 bool SeenOtherLoops = false;
4870};
4871
4872/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4873/// increment expression in case its Loop is L. If it is not L then
4874/// use AddRec itself.
4875/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4876class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4877public:
4878 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4879 SCEVPostIncRewriter Rewriter(L, SE);
4880 const SCEV *Result = Rewriter.visit(S);
4881 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4882 ? SE.getCouldNotCompute()
4883 : Result;
4884 }
4885
4886 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4887 if (!SE.isLoopInvariant(Expr, L))
4888 SeenLoopVariantSCEVUnknown = true;
4889 return Expr;
4890 }
4891
4892 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4893 // Only re-write AddRecExprs for this loop.
4894 if (Expr->getLoop() == L)
4895 return Expr->getPostIncExpr(SE);
4896 SeenOtherLoops = true;
4897 return Expr;
4898 }
4899
4900 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4901
4902 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4903
4904private:
4905 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4906 : SCEVRewriteVisitor(SE), L(L) {}
4907
4908 const Loop *L;
4909 bool SeenLoopVariantSCEVUnknown = false;
4910 bool SeenOtherLoops = false;
4911};
4912
4913/// This class evaluates the compare condition by matching it against the
4914/// condition of loop latch. If there is a match we assume a true value
4915/// for the condition while building SCEV nodes.
4916class SCEVBackedgeConditionFolder
4917 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4918public:
4919 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4920 ScalarEvolution &SE) {
4921 bool IsPosBECond = false;
4922 Value *BECond = nullptr;
4923 if (BasicBlock *Latch = L->getLoopLatch()) {
4924 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4925 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4926 "Both outgoing branches should not target same header!");
4927 BECond = BI->getCondition();
4928 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4929 } else {
4930 return S;
4931 }
4932 }
4933 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4934 return Rewriter.visit(S);
4935 }
4936
4937 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4938 const SCEV *Result = Expr;
4939 bool InvariantF = SE.isLoopInvariant(Expr, L);
4940
4941 if (!InvariantF) {
4943 switch (I->getOpcode()) {
4944 case Instruction::Select: {
4945 SelectInst *SI = cast<SelectInst>(I);
4946 std::optional<const SCEV *> Res =
4947 compareWithBackedgeCondition(SI->getCondition());
4948 if (Res) {
4949 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4950 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4951 }
4952 break;
4953 }
4954 default: {
4955 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4956 if (Res)
4957 Result = *Res;
4958 break;
4959 }
4960 }
4961 }
4962 return Result;
4963 }
4964
4965private:
4966 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4967 bool IsPosBECond, ScalarEvolution &SE)
4968 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4969 IsPositiveBECond(IsPosBECond) {}
4970
4971 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4972
4973 const Loop *L;
4974 /// Loop back condition.
4975 Value *BackedgeCond = nullptr;
4976 /// Set to true if loop back is on positive branch condition.
4977 bool IsPositiveBECond;
4978};
4979
4980std::optional<const SCEV *>
4981SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4982
4983 // If value matches the backedge condition for loop latch,
4984 // then return a constant evolution node based on loopback
4985 // branch taken.
4986 if (BackedgeCond == IC)
4987 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4989 return std::nullopt;
4990}
4991
4992class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4993public:
4994 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4995 ScalarEvolution &SE) {
4996 SCEVShiftRewriter Rewriter(L, SE);
4997 const SCEV *Result = Rewriter.visit(S);
4998 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4999 }
5000
5001 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5002 // Only allow AddRecExprs for this loop.
5003 if (!SE.isLoopInvariant(Expr, L))
5004 Valid = false;
5005 return Expr;
5006 }
5007
5008 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5009 if (Expr->getLoop() == L && Expr->isAffine())
5010 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5011 Valid = false;
5012 return Expr;
5013 }
5014
5015 bool isValid() { return Valid; }
5016
5017private:
5018 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5019 : SCEVRewriteVisitor(SE), L(L) {}
5020
5021 const Loop *L;
5022 bool Valid = true;
5023};
5024
5025} // end anonymous namespace
5026
5027void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5028 if (!AR->isAffine())
5029 return;
5030
5031 // Force computation of ranges, which will also perform range-based flag
5032 // inference.
5033 if (!AR->hasNoSignedWrap())
5034 (void)getSignedRange(AR);
5035
5036 if (!AR->hasNoUnsignedWrap())
5037 (void)getUnsignedRange(AR);
5038
5039 if (!AR->hasNoSelfWrap()) {
5040 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5041 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5042 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5043 const APInt &BECountAP = BECountMax->getAPInt();
5044 unsigned NoOverflowBitWidth =
5045 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5046 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5047 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5048 }
5049 }
5050}
5051
5053ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5055
5056 if (AR->hasNoSignedWrap())
5057 return Result;
5058
5059 if (!AR->isAffine())
5060 return Result;
5061
5062 // This function can be expensive, only try to prove NSW once per AddRec.
5063 if (!SignedWrapViaInductionTried.insert(AR).second)
5064 return Result;
5065
5066 const SCEV *Step = AR->getStepRecurrence(*this);
5067 const Loop *L = AR->getLoop();
5068
5069 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5070 // Note that this serves two purposes: It filters out loops that are
5071 // simply not analyzable, and it covers the case where this code is
5072 // being called from within backedge-taken count analysis, such that
5073 // attempting to ask for the backedge-taken count would likely result
5074 // in infinite recursion. In the later case, the analysis code will
5075 // cope with a conservative value, and it will take care to purge
5076 // that value once it has finished.
5077 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5078
5079 // Normally, in the cases we can prove no-overflow via a
5080 // backedge guarding condition, we can also compute a backedge
5081 // taken count for the loop. The exceptions are assumptions and
5082 // guards present in the loop -- SCEV is not great at exploiting
5083 // these to compute max backedge taken counts, but can still use
5084 // these to prove lack of overflow. Use this fact to avoid
5085 // doing extra work that may not pay off.
5086
5087 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5088 AC.assumptions().empty())
5089 return Result;
5090
5091 // If the backedge is guarded by a comparison with the pre-inc value the
5092 // addrec is safe. Also, if the entry is guarded by a comparison with the
5093 // start value and the backedge is guarded by a comparison with the post-inc
5094 // value, the addrec is safe.
5096 const SCEV *OverflowLimit =
5097 getSignedOverflowLimitForStep(Step, &Pred, this);
5098 if (OverflowLimit &&
5099 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5100 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5101 Result = setFlags(Result, SCEV::FlagNSW);
5102 }
5103 return Result;
5104}
5106ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5108
5109 if (AR->hasNoUnsignedWrap())
5110 return Result;
5111
5112 if (!AR->isAffine())
5113 return Result;
5114
5115 // This function can be expensive, only try to prove NUW once per AddRec.
5116 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5117 return Result;
5118
5119 const SCEV *Step = AR->getStepRecurrence(*this);
5120 const Loop *L = AR->getLoop();
5121
5122 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5123 // Note that this serves two purposes: It filters out loops that are
5124 // simply not analyzable, and it covers the case where this code is
5125 // being called from within backedge-taken count analysis, such that
5126 // attempting to ask for the backedge-taken count would likely result
5127 // in infinite recursion. In the later case, the analysis code will
5128 // cope with a conservative value, and it will take care to purge
5129 // that value once it has finished.
5130 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5131
5132 // Normally, in the cases we can prove no-overflow via a
5133 // backedge guarding condition, we can also compute a backedge
5134 // taken count for the loop. The exceptions are assumptions and
5135 // guards present in the loop -- SCEV is not great at exploiting
5136 // these to compute max backedge taken counts, but can still use
5137 // these to prove lack of overflow. Use this fact to avoid
5138 // doing extra work that may not pay off.
5139
5140 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5141 AC.assumptions().empty())
5142 return Result;
5143
5144 // If the backedge is guarded by a comparison with the pre-inc value the
5145 // addrec is safe. Also, if the entry is guarded by a comparison with the
5146 // start value and the backedge is guarded by a comparison with the post-inc
5147 // value, the addrec is safe.
5148 if (isKnownPositive(Step)) {
5150 const SCEV *OverflowLimit =
5151 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5152 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5153 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5154 Result = setFlags(Result, SCEV::FlagNUW);
5155 }
5156 return Result;
5157}
5158
5159namespace {
5160
5161/// Represents an abstract binary operation. This may exist as a
5162/// normal instruction or constant expression, or may have been
5163/// derived from an expression tree.
5164struct BinaryOp {
5165 unsigned Opcode;
5166 Value *LHS;
5167 Value *RHS;
5168 bool IsNSW = false;
5169 bool IsNUW = false;
5170
5171 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5172 /// constant expression.
5173 Operator *Op = nullptr;
5174
5175 explicit BinaryOp(Operator *Op)
5176 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5177 Op(Op) {
5178 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5179 IsNSW = OBO->hasNoSignedWrap();
5180 IsNUW = OBO->hasNoUnsignedWrap();
5181 }
5182 }
5183
5184 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5185 bool IsNUW = false)
5186 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5187};
5188
5189} // end anonymous namespace
5190
5191/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5192static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5193 AssumptionCache &AC,
5194 const DominatorTree &DT,
5195 const Instruction *CtxI) {
5196 auto *Op = dyn_cast<Operator>(V);
5197 if (!Op)
5198 return std::nullopt;
5199
5200 // Implementation detail: all the cleverness here should happen without
5201 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5202 // SCEV expressions when possible, and we should not break that.
5203
5204 switch (Op->getOpcode()) {
5205 case Instruction::Add:
5206 case Instruction::Sub:
5207 case Instruction::Mul:
5208 case Instruction::UDiv:
5209 case Instruction::URem:
5210 case Instruction::And:
5211 case Instruction::AShr:
5212 case Instruction::Shl:
5213 return BinaryOp(Op);
5214
5215 case Instruction::Or: {
5216 // Convert or disjoint into add nuw nsw.
5217 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5218 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5219 /*IsNSW=*/true, /*IsNUW=*/true);
5220 // Keep the reference to the original instruction so that we can later
5221 // check whether it can produce poison value or not.
5222 BinOp.Op = Op;
5223 return BinOp;
5224 }
5225 return BinaryOp(Op);
5226 }
5227
5228 case Instruction::Xor:
5229 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5230 // If the RHS of the xor is a signmask, then this is just an add.
5231 // Instcombine turns add of signmask into xor as a strength reduction step.
5232 if (RHSC->getValue().isSignMask())
5233 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5234 // Binary `xor` is a bit-wise `add`.
5235 if (V->getType()->isIntegerTy(1))
5236 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5237 return BinaryOp(Op);
5238
5239 case Instruction::LShr:
5240 // Turn logical shift right of a constant into a unsigned divide.
5241 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5242 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5243
5244 // If the shift count is not less than the bitwidth, the result of
5245 // the shift is undefined. Don't try to analyze it, because the
5246 // resolution chosen here may differ from the resolution chosen in
5247 // other parts of the compiler.
5248 if (SA->getValue().ult(BitWidth)) {
5249 Constant *X =
5250 ConstantInt::get(SA->getContext(),
5251 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5252 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5253 }
5254 }
5255 return BinaryOp(Op);
5256
5257 case Instruction::ExtractValue: {
5258 auto *EVI = cast<ExtractValueInst>(Op);
5259 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5260 break;
5261
5262 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5263 if (!WO)
5264 break;
5265
5266 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5267 bool Signed = WO->isSigned();
5268 // TODO: Should add nuw/nsw flags for mul as well.
5269 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5270 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5271
5272 // Now that we know that all uses of the arithmetic-result component of
5273 // CI are guarded by the overflow check, we can go ahead and pretend
5274 // that the arithmetic is non-overflowing.
5275 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5276 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5277 }
5278
5279 default:
5280 break;
5281 }
5282
5283 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5284 // semantics as a Sub, return a binary sub expression.
5285 if (auto *II = dyn_cast<IntrinsicInst>(V))
5286 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5287 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5288
5289 return std::nullopt;
5290}
5291
5292/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5293/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5294/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5295/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5296/// follows one of the following patterns:
5297/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5298/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5299/// If the SCEV expression of \p Op conforms with one of the expected patterns
5300/// we return the type of the truncation operation, and indicate whether the
5301/// truncated type should be treated as signed/unsigned by setting
5302/// \p Signed to true/false, respectively.
5303static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5304 bool &Signed, ScalarEvolution &SE) {
5305 // The case where Op == SymbolicPHI (that is, with no type conversions on
5306 // the way) is handled by the regular add recurrence creating logic and
5307 // would have already been triggered in createAddRecForPHI. Reaching it here
5308 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5309 // because one of the other operands of the SCEVAddExpr updating this PHI is
5310 // not invariant).
5311 //
5312 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5313 // this case predicates that allow us to prove that Op == SymbolicPHI will
5314 // be added.
5315 if (Op == SymbolicPHI)
5316 return nullptr;
5317
5318 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5319 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5320 if (SourceBits != NewBits)
5321 return nullptr;
5322
5323 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5324 Signed = true;
5325 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5326 }
5327 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5328 Signed = false;
5329 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5330 }
5331 return nullptr;
5332}
5333
5334static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5335 if (!PN->getType()->isIntegerTy())
5336 return nullptr;
5337 const Loop *L = LI.getLoopFor(PN->getParent());
5338 if (!L || L->getHeader() != PN->getParent())
5339 return nullptr;
5340 return L;
5341}
5342
5343// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5344// computation that updates the phi follows the following pattern:
5345// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5346// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5347// If so, try to see if it can be rewritten as an AddRecExpr under some
5348// Predicates. If successful, return them as a pair. Also cache the results
5349// of the analysis.
5350//
5351// Example usage scenario:
5352// Say the Rewriter is called for the following SCEV:
5353// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5354// where:
5355// %X = phi i64 (%Start, %BEValue)
5356// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5357// and call this function with %SymbolicPHI = %X.
5358//
5359// The analysis will find that the value coming around the backedge has
5360// the following SCEV:
5361// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5362// Upon concluding that this matches the desired pattern, the function
5363// will return the pair {NewAddRec, SmallPredsVec} where:
5364// NewAddRec = {%Start,+,%Step}
5365// SmallPredsVec = {P1, P2, P3} as follows:
5366// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5367// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5368// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5369// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5370// under the predicates {P1,P2,P3}.
5371// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5372// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5373//
5374// TODO's:
5375//
5376// 1) Extend the Induction descriptor to also support inductions that involve
5377// casts: When needed (namely, when we are called in the context of the
5378// vectorizer induction analysis), a Set of cast instructions will be
5379// populated by this method, and provided back to isInductionPHI. This is
5380// needed to allow the vectorizer to properly record them to be ignored by
5381// the cost model and to avoid vectorizing them (otherwise these casts,
5382// which are redundant under the runtime overflow checks, will be
5383// vectorized, which can be costly).
5384//
5385// 2) Support additional induction/PHISCEV patterns: We also want to support
5386// inductions where the sext-trunc / zext-trunc operations (partly) occur
5387// after the induction update operation (the induction increment):
5388//
5389// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5390// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5391//
5392// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5393// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5394//
5395// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5396std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5397ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5399
5400 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5401 // return an AddRec expression under some predicate.
5402
5403 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5404 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5405 assert(L && "Expecting an integer loop header phi");
5406
5407 // The loop may have multiple entrances or multiple exits; we can analyze
5408 // this phi as an addrec if it has a unique entry value and a unique
5409 // backedge value.
5410 Value *BEValueV = nullptr, *StartValueV = nullptr;
5411 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5412 Value *V = PN->getIncomingValue(i);
5413 if (L->contains(PN->getIncomingBlock(i))) {
5414 if (!BEValueV) {
5415 BEValueV = V;
5416 } else if (BEValueV != V) {
5417 BEValueV = nullptr;
5418 break;
5419 }
5420 } else if (!StartValueV) {
5421 StartValueV = V;
5422 } else if (StartValueV != V) {
5423 StartValueV = nullptr;
5424 break;
5425 }
5426 }
5427 if (!BEValueV || !StartValueV)
5428 return std::nullopt;
5429
5430 const SCEV *BEValue = getSCEV(BEValueV);
5431
5432 // If the value coming around the backedge is an add with the symbolic
5433 // value we just inserted, possibly with casts that we can ignore under
5434 // an appropriate runtime guard, then we found a simple induction variable!
5435 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5436 if (!Add)
5437 return std::nullopt;
5438
5439 // If there is a single occurrence of the symbolic value, possibly
5440 // casted, replace it with a recurrence.
5441 unsigned FoundIndex = Add->getNumOperands();
5442 Type *TruncTy = nullptr;
5443 bool Signed;
5444 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5445 if ((TruncTy =
5446 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5447 if (FoundIndex == e) {
5448 FoundIndex = i;
5449 break;
5450 }
5451
5452 if (FoundIndex == Add->getNumOperands())
5453 return std::nullopt;
5454
5455 // Create an add with everything but the specified operand.
5457 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5458 if (i != FoundIndex)
5459 Ops.push_back(Add->getOperand(i));
5460 const SCEV *Accum = getAddExpr(Ops);
5461
5462 // The runtime checks will not be valid if the step amount is
5463 // varying inside the loop.
5464 if (!isLoopInvariant(Accum, L))
5465 return std::nullopt;
5466
5467 // *** Part2: Create the predicates
5468
5469 // Analysis was successful: we have a phi-with-cast pattern for which we
5470 // can return an AddRec expression under the following predicates:
5471 //
5472 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5473 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5474 // P2: An Equal predicate that guarantees that
5475 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5476 // P3: An Equal predicate that guarantees that
5477 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5478 //
5479 // As we next prove, the above predicates guarantee that:
5480 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5481 //
5482 //
5483 // More formally, we want to prove that:
5484 // Expr(i+1) = Start + (i+1) * Accum
5485 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5486 //
5487 // Given that:
5488 // 1) Expr(0) = Start
5489 // 2) Expr(1) = Start + Accum
5490 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5491 // 3) Induction hypothesis (step i):
5492 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5493 //
5494 // Proof:
5495 // Expr(i+1) =
5496 // = Start + (i+1)*Accum
5497 // = (Start + i*Accum) + Accum
5498 // = Expr(i) + Accum
5499 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5500 // :: from step i
5501 //
5502 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5503 //
5504 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5505 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5506 // + Accum :: from P3
5507 //
5508 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5509 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5510 //
5511 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5512 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5513 //
5514 // By induction, the same applies to all iterations 1<=i<n:
5515 //
5516
5517 // Create a truncated addrec for which we will add a no overflow check (P1).
5518 const SCEV *StartVal = getSCEV(StartValueV);
5519 const SCEV *PHISCEV =
5520 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5521 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5522
5523 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5524 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5525 // will be constant.
5526 //
5527 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5528 // add P1.
5529 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5533 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5534 Predicates.push_back(AddRecPred);
5535 }
5536
5537 // Create the Equal Predicates P2,P3:
5538
5539 // It is possible that the predicates P2 and/or P3 are computable at
5540 // compile time due to StartVal and/or Accum being constants.
5541 // If either one is, then we can check that now and escape if either P2
5542 // or P3 is false.
5543
5544 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5545 // for each of StartVal and Accum
5546 auto getExtendedExpr = [&](const SCEV *Expr,
5547 bool CreateSignExtend) -> const SCEV * {
5548 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5549 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5550 const SCEV *ExtendedExpr =
5551 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5552 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5553 return ExtendedExpr;
5554 };
5555
5556 // Given:
5557 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5558 // = getExtendedExpr(Expr)
5559 // Determine whether the predicate P: Expr == ExtendedExpr
5560 // is known to be false at compile time
5561 auto PredIsKnownFalse = [&](const SCEV *Expr,
5562 const SCEV *ExtendedExpr) -> bool {
5563 return Expr != ExtendedExpr &&
5564 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5565 };
5566
5567 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5568 if (PredIsKnownFalse(StartVal, StartExtended)) {
5569 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5570 return std::nullopt;
5571 }
5572
5573 // The Step is always Signed (because the overflow checks are either
5574 // NSSW or NUSW)
5575 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5576 if (PredIsKnownFalse(Accum, AccumExtended)) {
5577 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5578 return std::nullopt;
5579 }
5580
5581 auto AppendPredicate = [&](const SCEV *Expr,
5582 const SCEV *ExtendedExpr) -> void {
5583 if (Expr != ExtendedExpr &&
5584 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5585 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5586 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5587 Predicates.push_back(Pred);
5588 }
5589 };
5590
5591 AppendPredicate(StartVal, StartExtended);
5592 AppendPredicate(Accum, AccumExtended);
5593
5594 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5595 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5596 // into NewAR if it will also add the runtime overflow checks specified in
5597 // Predicates.
5598 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5599
5600 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5601 std::make_pair(NewAR, Predicates);
5602 // Remember the result of the analysis for this SCEV at this locayyytion.
5603 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5604 return PredRewrite;
5605}
5606
5607std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5609 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5610 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5611 if (!L)
5612 return std::nullopt;
5613
5614 // Check to see if we already analyzed this PHI.
5615 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5616 if (I != PredicatedSCEVRewrites.end()) {
5617 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5618 I->second;
5619 // Analysis was done before and failed to create an AddRec:
5620 if (Rewrite.first == SymbolicPHI)
5621 return std::nullopt;
5622 // Analysis was done before and succeeded to create an AddRec under
5623 // a predicate:
5624 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5625 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5626 return Rewrite;
5627 }
5628
5629 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5630 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5631
5632 // Record in the cache that the analysis failed
5633 if (!Rewrite) {
5635 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5636 return std::nullopt;
5637 }
5638
5639 return Rewrite;
5640}
5641
5642// FIXME: This utility is currently required because the Rewriter currently
5643// does not rewrite this expression:
5644// {0, +, (sext ix (trunc iy to ix) to iy)}
5645// into {0, +, %step},
5646// even when the following Equal predicate exists:
5647// "%step == (sext ix (trunc iy to ix) to iy)".
5649 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5650 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5651 if (AR1 == AR2)
5652 return true;
5653
5654 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5655 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5656 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5657 if (Expr1 != Expr2 &&
5658 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5659 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5660 return false;
5661 return true;
5662 };
5663
5664 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5665 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5666 return false;
5667 return true;
5668}
5669
5671 ScalarEvolution &SE) {
5672 SCEVFlags Flags = SCEV::FlagNone;
5673 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5674 // If the increment has any nowrap flags, then we know the address
5675 // space cannot be wrapped around.
5676 if (NW != GEPNoWrapFlags::none())
5678 // If the GEP is nuw or nusw with non-negative offset, we know that
5679 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5680 // offset is treated as signed, while the base is unsigned.
5681 if (NW.hasNoUnsignedWrap() ||
5682 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5684
5685 return Flags;
5686}
5687
5688/// A helper function for createAddRecFromPHI to handle simple cases.
5689///
5690/// This function tries to find an AddRec expression for the simplest (yet most
5691/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5692/// If it fails, createAddRecFromPHI will use a more general, but slow,
5693/// technique for finding the AddRec expression.
5694const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5695 Value *BEValueV,
5696 Value *StartValueV) {
5697 const Loop *L = LI.getLoopFor(PN->getParent());
5698 assert(L && L->getHeader() == PN->getParent());
5699 assert(BEValueV && StartValueV);
5700
5701 const SCEV *Accum = nullptr;
5703 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5704 if (BO->Opcode != Instruction::Add)
5705 return nullptr;
5706
5707 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5708 Accum = getSCEV(BO->RHS);
5709 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5710 Accum = getSCEV(BO->LHS);
5711
5712 if (!Accum)
5713 return nullptr;
5714
5715 if (BO->IsNUW)
5716 Flags = setFlags(Flags, SCEV::FlagNUW);
5717 if (BO->IsNSW)
5718 Flags = setFlags(Flags, SCEV::FlagNSW);
5719 } else {
5720 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5721 // LoopInvariant).
5722 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5723 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5724 return nullptr;
5725 Value *Idx = *GEP->idx_begin();
5726 if (!L->isLoopInvariant(Idx))
5727 return nullptr;
5728
5729 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5730 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5731 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5732 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5733 }
5734
5735 const SCEV *StartVal = getSCEV(StartValueV);
5736 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5737 insertValueToMap(PN, PHISCEV);
5738
5739 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5740 inferNoWrapViaConstantRanges(AR);
5741
5742 // We can add Flags to the post-inc expression only if we
5743 // know that it is *undefined behavior* for BEValueV to
5744 // overflow.
5745 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5746 assert(isLoopInvariant(Accum, L) &&
5747 "Accum is defined outside L, but is not invariant?");
5748 if (isAddRecNeverPoison(BEInst, L))
5749 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5750 }
5751
5752 return PHISCEV;
5753}
5754
5755const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5756 const Loop *L = LI.getLoopFor(PN->getParent());
5757 if (!L || L->getHeader() != PN->getParent())
5758 return nullptr;
5759
5760 // The loop may have multiple entrances or multiple exits; we can analyze
5761 // this phi as an addrec if it has a unique entry value and a unique
5762 // backedge value.
5763 Value *BEValueV = nullptr, *StartValueV = nullptr;
5764 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5765 Value *V = PN->getIncomingValue(i);
5766 if (L->contains(PN->getIncomingBlock(i))) {
5767 if (!BEValueV) {
5768 BEValueV = V;
5769 } else if (BEValueV != V) {
5770 BEValueV = nullptr;
5771 break;
5772 }
5773 } else if (!StartValueV) {
5774 StartValueV = V;
5775 } else if (StartValueV != V) {
5776 StartValueV = nullptr;
5777 break;
5778 }
5779 }
5780 if (!BEValueV || !StartValueV)
5781 return nullptr;
5782
5783 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5784 "PHI node already processed?");
5785
5786 // First, try to find AddRec expression without creating a fictituos symbolic
5787 // value for PN.
5788 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5789 return S;
5790
5791 // Handle PHI node value symbolically.
5792 const SCEV *SymbolicName = getUnknown(PN);
5793 insertValueToMap(PN, SymbolicName);
5794
5795 // Using this symbolic name for the PHI, analyze the value coming around
5796 // the back-edge.
5797 const SCEV *BEValue = getSCEV(BEValueV);
5798
5799 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5800 // has a special value for the first iteration of the loop.
5801
5802 // If the value coming around the backedge is an add with the symbolic
5803 // value we just inserted, then we found a simple induction variable!
5804 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5805 // If there is a single occurrence of the symbolic value, replace it
5806 // with a recurrence.
5807 unsigned FoundIndex = Add->getNumOperands();
5808 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5809 if (Add->getOperand(i) == SymbolicName)
5810 if (FoundIndex == e) {
5811 FoundIndex = i;
5812 break;
5813 }
5814
5815 if (FoundIndex != Add->getNumOperands()) {
5816 // Create an add with everything but the specified operand.
5818 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5819 if (i != FoundIndex)
5820 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5821 L, *this));
5822 const SCEV *Accum = getAddExpr(Ops);
5823
5824 // This is not a valid addrec if the step amount is varying each
5825 // loop iteration, but is not itself an addrec in this loop.
5826 if (isLoopInvariant(Accum, L) ||
5827 (isa<SCEVAddRecExpr>(Accum) &&
5828 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5830
5831 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5832 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5833 if (BO->IsNUW)
5834 Flags = setFlags(Flags, SCEV::FlagNUW);
5835 if (BO->IsNSW)
5836 Flags = setFlags(Flags, SCEV::FlagNSW);
5837 }
5838 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5839 if (GEP->getOperand(0) == PN)
5840 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5841
5842 // We cannot transfer nuw and nsw flags from subtraction
5843 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5844 // for instance.
5845 }
5846
5847 const SCEV *StartVal = getSCEV(StartValueV);
5848 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5849
5850 // Okay, for the entire analysis of this edge we assumed the PHI
5851 // to be symbolic. We now need to go back and purge all of the
5852 // entries for the scalars that use the symbolic expression.
5853 forgetMemoizedResults({SymbolicName});
5854 insertValueToMap(PN, PHISCEV);
5855
5856 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5857 inferNoWrapViaConstantRanges(AR);
5858
5859 // We can add Flags to the post-inc expression only if we
5860 // know that it is *undefined behavior* for BEValueV to
5861 // overflow.
5862 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5863 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5864 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5865
5866 return PHISCEV;
5867 }
5868 }
5869 } else {
5870 // Otherwise, this could be a loop like this:
5871 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5872 // In this case, j = {1,+,1} and BEValue is j.
5873 // Because the other in-value of i (0) fits the evolution of BEValue
5874 // i really is an addrec evolution.
5875 //
5876 // We can generalize this saying that i is the shifted value of BEValue
5877 // by one iteration:
5878 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5879
5880 // Do not allow refinement in rewriting of BEValue.
5881 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5882 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5883 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5884 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5885 const SCEV *StartVal = getSCEV(StartValueV);
5886 if (Start == StartVal) {
5887 // Okay, for the entire analysis of this edge we assumed the PHI
5888 // to be symbolic. We now need to go back and purge all of the
5889 // entries for the scalars that use the symbolic expression.
5890 forgetMemoizedResults({SymbolicName});
5891 insertValueToMap(PN, Shifted);
5892 return Shifted;
5893 }
5894 }
5895 }
5896
5897 // Remove the temporary PHI node SCEV that has been inserted while intending
5898 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5899 // as it will prevent later (possibly simpler) SCEV expressions to be added
5900 // to the ValueExprMap.
5901 eraseValueFromMap(PN);
5902
5903 return nullptr;
5904}
5905
5906// Try to match a control flow sequence that branches out at BI and merges back
5907// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5908// match.
5910 Value *&C, Value *&LHS, Value *&RHS) {
5911 C = BI->getCondition();
5912
5913 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5914 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5915
5916 Use &LeftUse = Merge->getOperandUse(0);
5917 Use &RightUse = Merge->getOperandUse(1);
5918
5919 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5920 LHS = LeftUse;
5921 RHS = RightUse;
5922 return true;
5923 }
5924
5925 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5926 LHS = RightUse;
5927 RHS = LeftUse;
5928 return true;
5929 }
5930
5931 return false;
5932}
5933
5935 Value *&Cond, Value *&LHS,
5936 Value *&RHS) {
5937 auto IsReachable =
5938 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5939 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5940 // Try to match
5941 //
5942 // br %cond, label %left, label %right
5943 // left:
5944 // br label %merge
5945 // right:
5946 // br label %merge
5947 // merge:
5948 // V = phi [ %x, %left ], [ %y, %right ]
5949 //
5950 // as "select %cond, %x, %y"
5951
5952 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5953 assert(IDom && "At least the entry block should dominate PN");
5954
5955 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5956 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5957 }
5958 return false;
5959}
5960
5961const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5962 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5963 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5966 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5967
5968 return nullptr;
5969}
5970
5972 BinaryOperator *CommonInst = nullptr;
5973 // Check if instructions are identical.
5974 for (Value *Incoming : PN->incoming_values()) {
5975 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5976 if (!IncomingInst)
5977 return nullptr;
5978 if (CommonInst) {
5979 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5980 return nullptr; // Not identical, give up
5981 } else {
5982 // Remember binary operator
5983 CommonInst = IncomingInst;
5984 }
5985 }
5986 return CommonInst;
5987}
5988
5989/// Returns SCEV for the first operand of a phi if all phi operands have
5990/// identical opcodes and operands
5991/// eg.
5992/// a: %add = %a + %b
5993/// br %c
5994/// b: %add1 = %a + %b
5995/// br %c
5996/// c: %phi = phi [%add, a], [%add1, b]
5997/// scev(%phi) => scev(%add)
5998const SCEV *
5999ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6000 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6001 if (!CommonInst)
6002 return nullptr;
6003
6004 // Check if SCEV exprs for instructions are identical.
6005 const SCEV *CommonSCEV = getSCEV(CommonInst);
6006 bool SCEVExprsIdentical =
6008 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6009 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6010}
6011
6012const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6013 if (const SCEV *S = createAddRecFromPHI(PN))
6014 return S;
6015
6016 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6017 // phi node for X.
6018 if (Value *V = simplifyInstruction(
6019 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6020 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6021 return getSCEV(V);
6022
6023 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6024 return S;
6025
6026 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6027 return S;
6028
6029 // If it's not a loop phi, we can't handle it yet.
6030 return getUnknown(PN);
6031}
6032
6033bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6034 SCEVTypes RootKind) {
6035 struct FindClosure {
6036 const SCEV *OperandToFind;
6037 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6038 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6039
6040 bool Found = false;
6041
6042 bool canRecurseInto(SCEVTypes Kind) const {
6043 // We can only recurse into the SCEV expression of the same effective type
6044 // as the type of our root SCEV expression, and into zero-extensions.
6045 return RootKind == Kind || NonSequentialRootKind == Kind ||
6046 scZeroExtend == Kind;
6047 };
6048
6049 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6050 : OperandToFind(OperandToFind), RootKind(RootKind),
6051 NonSequentialRootKind(
6053 RootKind)) {}
6054
6055 bool follow(const SCEV *S) {
6056 Found = S == OperandToFind;
6057
6058 return !isDone() && canRecurseInto(S->getSCEVType());
6059 }
6060
6061 bool isDone() const { return Found; }
6062 };
6063
6064 FindClosure FC(OperandToFind, RootKind);
6065 visitAll(Root, FC);
6066 return FC.Found;
6067}
6068
6069std::optional<const SCEV *>
6070ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6071 ICmpInst *Cond,
6072 Value *TrueVal,
6073 Value *FalseVal) {
6074 // Try to match some simple smax or umax patterns.
6075 auto *ICI = Cond;
6076
6077 Value *LHS = ICI->getOperand(0);
6078 Value *RHS = ICI->getOperand(1);
6079
6080 switch (ICI->getPredicate()) {
6081 case ICmpInst::ICMP_SLT:
6082 case ICmpInst::ICMP_SLE:
6083 case ICmpInst::ICMP_ULT:
6084 case ICmpInst::ICMP_ULE:
6085 std::swap(LHS, RHS);
6086 [[fallthrough]];
6087 case ICmpInst::ICMP_SGT:
6088 case ICmpInst::ICMP_SGE:
6089 case ICmpInst::ICMP_UGT:
6090 case ICmpInst::ICMP_UGE:
6091 // a > b ? a+x : b+x -> max(a, b)+x
6092 // a > b ? b+x : a+x -> min(a, b)+x
6094 bool Signed = ICI->isSigned();
6095 const SCEV *LA = getSCEV(TrueVal);
6096 const SCEV *RA = getSCEV(FalseVal);
6097 const SCEV *LS = getSCEV(LHS);
6098 const SCEV *RS = getSCEV(RHS);
6099 if (LA->getType()->isPointerTy()) {
6100 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6101 // Need to make sure we can't produce weird expressions involving
6102 // negated pointers.
6103 if (LA == LS && RA == RS)
6104 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6105 if (LA == RS && RA == LS)
6106 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6107 }
6108 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6109 if (Op->getType()->isPointerTy()) {
6112 return Op;
6113 }
6114 if (Signed)
6115 Op = getNoopOrSignExtend(Op, Ty);
6116 else
6117 Op = getNoopOrZeroExtend(Op, Ty);
6118 return Op;
6119 };
6120 LS = CoerceOperand(LS);
6121 RS = CoerceOperand(RS);
6123 break;
6124 const SCEV *LDiff = getMinusSCEV(LA, LS);
6125 const SCEV *RDiff = getMinusSCEV(RA, RS);
6126 if (LDiff == RDiff)
6127 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6128 LDiff);
6129 LDiff = getMinusSCEV(LA, RS);
6130 RDiff = getMinusSCEV(RA, LS);
6131 if (LDiff == RDiff)
6132 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6133 LDiff);
6134 }
6135 break;
6136 case ICmpInst::ICMP_NE:
6137 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6138 std::swap(TrueVal, FalseVal);
6139 [[fallthrough]];
6140 case ICmpInst::ICMP_EQ:
6141 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6144 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6145 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6146 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6147 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6148 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6149 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6150 return getAddExpr(getUMaxExpr(X, C), Y);
6151 }
6152 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6153 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6154 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6155 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6157 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6158 const SCEV *X = getSCEV(LHS);
6159 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6160 X = ZExt->getOperand();
6161 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6162 const SCEV *FalseValExpr = getSCEV(FalseVal);
6163 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6164 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6165 /*Sequential=*/true);
6166 }
6167 }
6168 break;
6169 default:
6170 break;
6171 }
6172
6173 return std::nullopt;
6174}
6175
6176static std::optional<const SCEV *>
6178 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6179 assert(CondExpr->getType()->isIntegerTy(1) &&
6180 TrueExpr->getType() == FalseExpr->getType() &&
6181 TrueExpr->getType()->isIntegerTy(1) &&
6182 "Unexpected operands of a select.");
6183
6184 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6185 // --> C + (umin_seq cond, x - C)
6186 //
6187 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6188 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6189 // --> C + (umin_seq ~cond, x - C)
6190
6191 // FIXME: while we can't legally model the case where both of the hands
6192 // are fully variable, we only require that the *difference* is constant.
6193 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6194 return std::nullopt;
6195
6196 const SCEV *X, *C;
6197 if (isa<SCEVConstant>(TrueExpr)) {
6198 CondExpr = SE->getNotSCEV(CondExpr);
6199 X = FalseExpr;
6200 C = TrueExpr;
6201 } else {
6202 X = TrueExpr;
6203 C = FalseExpr;
6204 }
6205 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6206 /*Sequential=*/true));
6207}
6208
6209static std::optional<const SCEV *>
6211 Value *FalseVal) {
6212 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6213 return std::nullopt;
6214
6215 const auto *SECond = SE->getSCEV(Cond);
6216 const auto *SETrue = SE->getSCEV(TrueVal);
6217 const auto *SEFalse = SE->getSCEV(FalseVal);
6218 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6219}
6220
6221const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6222 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6223 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6224 assert(TrueVal->getType() == FalseVal->getType() &&
6225 V->getType() == TrueVal->getType() &&
6226 "Types of select hands and of the result must match.");
6227
6228 // For now, only deal with i1-typed `select`s.
6229 if (!V->getType()->isIntegerTy(1))
6230 return getUnknown(V);
6231
6232 if (std::optional<const SCEV *> S =
6233 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6234 return *S;
6235
6236 return getUnknown(V);
6237}
6238
6239const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6240 Value *TrueVal,
6241 Value *FalseVal) {
6242 // Handle "constant" branch or select. This can occur for instance when a
6243 // loop pass transforms an inner loop and moves on to process the outer loop.
6244 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6245 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6246
6247 if (auto *I = dyn_cast<Instruction>(V)) {
6248 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6249 if (std::optional<const SCEV *> S =
6250 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6251 TrueVal, FalseVal))
6252 return *S;
6253 }
6254 }
6255
6256 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6257}
6258
6259/// Expand GEP instructions into add and multiply operations. This allows them
6260/// to be analyzed by regular SCEV code.
6261const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6262 assert(GEP->getSourceElementType()->isSized() &&
6263 "GEP source element type must be sized");
6264
6265 SmallVector<SCEVUse, 4> IndexExprs;
6266 for (Value *Index : GEP->indices())
6267 IndexExprs.push_back(getSCEV(Index));
6268 return getGEPExpr(GEP, IndexExprs);
6269}
6270
6271APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6272 const Instruction *CtxI) {
6274 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6275 return TrailingZeros >= BitWidth
6277 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6278 };
6279 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6280 // The result is GCD of all operands results.
6281 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6282 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6284 Res, getConstantMultiple(N->getOperand(I), CtxI));
6285 return Res;
6286 };
6287
6288 switch (S->getSCEVType()) {
6289 case scConstant:
6290 return cast<SCEVConstant>(S)->getAPInt();
6291 case scPtrToAddr:
6292 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6293 case scUDivExpr:
6294 case scVScale:
6295 return APInt(BitWidth, 1);
6296 case scTruncate: {
6297 // Only multiples that are a power of 2 will hold after truncation.
6298 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6299 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6300 return GetShiftedByZeros(TZ);
6301 }
6302 case scZeroExtend: {
6303 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6304 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6305 }
6306 case scSignExtend: {
6307 // Only multiples that are a power of 2 will hold after sext.
6308 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6309 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6310 return GetShiftedByZeros(TZ);
6311 }
6312 case scMulExpr: {
6313 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6314 if (M->hasNoUnsignedWrap()) {
6315 // The result is the product of all operand results.
6316 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6317 for (const SCEV *Operand : M->operands().drop_front())
6318 Res = Res * getConstantMultiple(Operand, CtxI);
6319 return Res;
6320 }
6321
6322 // If there are no wrap guarentees, find the trailing zeros, which is the
6323 // sum of trailing zeros for all its operands.
6324 uint32_t TZ = 0;
6325 for (const SCEV *Operand : M->operands())
6326 TZ += getMinTrailingZeros(Operand, CtxI);
6327 return GetShiftedByZeros(TZ);
6328 }
6329 case scAddExpr:
6330 case scAddRecExpr: {
6331 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6332 if (N->hasNoUnsignedWrap())
6333 return GetGCDMultiple(N);
6334 // Find the trailing bits, which is the minimum of its operands.
6335 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6336 for (const SCEV *Operand : N->operands().drop_front())
6337 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6338 return GetShiftedByZeros(TZ);
6339 }
6340 case scUMaxExpr:
6341 case scSMaxExpr:
6342 case scUMinExpr:
6343 case scSMinExpr:
6345 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6346 case scUnknown: {
6347 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6348 // the point their underlying IR instruction has been defined. If CtxI was
6349 // not provided, use:
6350 // * the first instruction in the entry block if it is an argument
6351 // * the instruction itself otherwise.
6352 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6353 if (!CtxI) {
6354 if (isa<Argument>(U->getValue()))
6355 CtxI = &*F.getEntryBlock().begin();
6356 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6357 CtxI = I;
6358 }
6359 unsigned Known =
6360 computeKnownBits(U->getValue(),
6361 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6362 .allowEphemerals(true))
6363 .countMinTrailingZeros();
6364 return GetShiftedByZeros(Known);
6365 }
6366 case scCouldNotCompute:
6367 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6368 }
6369 llvm_unreachable("Unknown SCEV kind!");
6370}
6371
6373 const Instruction *CtxI) {
6374 // Skip looking up and updating the cache if there is a context instruction,
6375 // as the result will only be valid in the specified context.
6376 if (CtxI)
6377 return getConstantMultipleImpl(S, CtxI);
6378
6379 auto I = ConstantMultipleCache.find(S);
6380 if (I != ConstantMultipleCache.end())
6381 return I->second;
6382
6383 APInt Result = getConstantMultipleImpl(S, CtxI);
6384 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6385 assert(InsertPair.second && "Should insert a new key");
6386 return InsertPair.first->second;
6387}
6388
6390 APInt Multiple = getConstantMultiple(S);
6391 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6392}
6393
6395 const Instruction *CtxI) {
6396 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6397 (unsigned)getTypeSizeInBits(S->getType()));
6398}
6399
6400/// Helper method to assign a range to V from metadata present in the IR.
6401static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6403 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6404 return getConstantRangeFromMetadata(*MD);
6405 if (const auto *CB = dyn_cast<CallBase>(V))
6406 if (std::optional<ConstantRange> Range = CB->getRange())
6407 return Range;
6408 }
6409 if (auto *A = dyn_cast<Argument>(V))
6410 if (std::optional<ConstantRange> Range = A->getRange())
6411 return Range;
6412
6413 return std::nullopt;
6414}
6415
6417 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6418 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6419 AddRec->setNoWrapFlags(NWFlags);
6420 UnsignedRanges.erase(AddRec);
6421 SignedRanges.erase(AddRec);
6422 ConstantMultipleCache.erase(AddRec);
6423 }
6424}
6425
6426ConstantRange ScalarEvolution::
6427getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6428 const DataLayout &DL = getDataLayout();
6429
6430 unsigned BitWidth = getTypeSizeInBits(U->getType());
6431 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6432
6433 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6434 // use information about the trip count to improve our available range. Note
6435 // that the trip count independent cases are already handled by known bits.
6436 // WARNING: The definition of recurrence used here is subtly different than
6437 // the one used by AddRec (and thus most of this file). Step is allowed to
6438 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6439 // and other addrecs in the same loop (for non-affine addrecs). The code
6440 // below intentionally handles the case where step is not loop invariant.
6441 auto *P = dyn_cast<PHINode>(U->getValue());
6442 if (!P)
6443 return FullSet;
6444
6445 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6446 // even the values that are not available in these blocks may come from them,
6447 // and this leads to false-positive recurrence test.
6448 for (auto *Pred : predecessors(P->getParent()))
6449 if (!DT.isReachableFromEntry(Pred))
6450 return FullSet;
6451
6452 BinaryOperator *BO;
6453 Value *Start, *Step;
6454 if (!matchSimpleRecurrence(P, BO, Start, Step))
6455 return FullSet;
6456
6457 // If we found a recurrence in reachable code, we must be in a loop. Note
6458 // that BO might be in some subloop of L, and that's completely okay.
6459 auto *L = LI.getLoopFor(P->getParent());
6460 assert(L && L->getHeader() == P->getParent());
6461 if (!L->contains(BO->getParent()))
6462 // NOTE: This bailout should be an assert instead. However, asserting
6463 // the condition here exposes a case where LoopFusion is querying SCEV
6464 // with malformed loop information during the midst of the transform.
6465 // There doesn't appear to be an obvious fix, so for the moment bailout
6466 // until the caller issue can be fixed. PR49566 tracks the bug.
6467 return FullSet;
6468
6469 // TODO: Extend to other opcodes such as mul, and div
6470 switch (BO->getOpcode()) {
6471 default:
6472 return FullSet;
6473 case Instruction::AShr:
6474 case Instruction::LShr:
6475 case Instruction::Shl:
6476 break;
6477 };
6478
6479 if (BO->getOperand(0) != P)
6480 // TODO: Handle the power function forms some day.
6481 return FullSet;
6482
6483 unsigned TC = getSmallConstantMaxTripCount(L);
6484 if (!TC || TC >= BitWidth)
6485 return FullSet;
6486
6487 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6488 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6489 assert(KnownStart.getBitWidth() == BitWidth &&
6490 KnownStep.getBitWidth() == BitWidth);
6491
6492 // Compute total shift amount, being careful of overflow and bitwidths.
6493 auto MaxShiftAmt = KnownStep.getMaxValue();
6494 APInt TCAP(BitWidth, TC-1);
6495 bool Overflow = false;
6496 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6497 if (Overflow)
6498 return FullSet;
6499
6500 switch (BO->getOpcode()) {
6501 default:
6502 llvm_unreachable("filtered out above");
6503 case Instruction::AShr: {
6504 // For each ashr, three cases:
6505 // shift = 0 => unchanged value
6506 // saturation => 0 or -1
6507 // other => a value closer to zero (of the same sign)
6508 // Thus, the end value is closer to zero than the start.
6509 auto KnownEnd = KnownBits::ashr(KnownStart,
6510 KnownBits::makeConstant(TotalShift));
6511 if (KnownStart.isNonNegative())
6512 // Analogous to lshr (simply not yet canonicalized)
6513 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6514 KnownStart.getMaxValue() + 1);
6515 if (KnownStart.isNegative())
6516 // End >=u Start && End <=s Start
6517 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6518 KnownEnd.getMaxValue() + 1);
6519 break;
6520 }
6521 case Instruction::LShr: {
6522 // For each lshr, three cases:
6523 // shift = 0 => unchanged value
6524 // saturation => 0
6525 // other => a smaller positive number
6526 // Thus, the low end of the unsigned range is the last value produced.
6527 auto KnownEnd = KnownBits::lshr(KnownStart,
6528 KnownBits::makeConstant(TotalShift));
6529 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6530 KnownStart.getMaxValue() + 1);
6531 }
6532 case Instruction::Shl: {
6533 // Iff no bits are shifted out, value increases on every shift.
6534 auto KnownEnd = KnownBits::shl(KnownStart,
6535 KnownBits::makeConstant(TotalShift));
6536 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6537 return ConstantRange(KnownStart.getMinValue(),
6538 KnownEnd.getMaxValue() + 1);
6539 break;
6540 }
6541 };
6542 return FullSet;
6543}
6544
6545// The goal of this function is to check if recursively visiting the operands
6546// of this PHI might lead to an infinite loop. If we do see such a loop,
6547// there's no good way to break it, so we avoid analyzing such cases.
6548//
6549// getRangeRef previously used a visited set to avoid infinite loops, but this
6550// caused other issues: the result was dependent on the order of getRangeRef
6551// calls, and the interaction with createSCEVIter could cause a stack overflow
6552// in some cases (see issue #148253).
6553//
6554// FIXME: The way this is implemented is overly conservative; this checks
6555// for a few obviously safe patterns, but anything that doesn't lead to
6556// recursion is fine.
6558 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6560 return true;
6561
6562 if (all_of(PHI->operands(),
6563 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6564 return true;
6565
6566 return false;
6567}
6568
6569const ConstantRange &
6570ScalarEvolution::getRangeRefIter(const SCEV *S,
6571 ScalarEvolution::RangeSignHint SignHint) {
6572 DenseMap<const SCEV *, ConstantRange> &Cache =
6573 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6574 : SignedRanges;
6575 SmallVector<SCEVUse> WorkList;
6576 SmallPtrSet<const SCEV *, 8> Seen;
6577
6578 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6579 // SCEVUnknown PHI node.
6580 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6581 if (!Seen.insert(Expr).second)
6582 return;
6583 if (Cache.contains(Expr))
6584 return;
6585 switch (Expr->getSCEVType()) {
6586 case scUnknown:
6588 break;
6589 [[fallthrough]];
6590 case scConstant:
6591 case scVScale:
6592 case scTruncate:
6593 case scZeroExtend:
6594 case scSignExtend:
6595 case scPtrToAddr:
6596 case scAddExpr:
6597 case scMulExpr:
6598 case scUDivExpr:
6599 case scAddRecExpr:
6600 case scUMaxExpr:
6601 case scSMaxExpr:
6602 case scUMinExpr:
6603 case scSMinExpr:
6605 WorkList.push_back(Expr);
6606 break;
6607 case scCouldNotCompute:
6608 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6609 }
6610 };
6611 AddToWorklist(S);
6612
6613 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6614 for (unsigned I = 0; I != WorkList.size(); ++I) {
6615 const SCEV *P = WorkList[I];
6616 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6617 // If it is not a `SCEVUnknown`, just recurse into operands.
6618 if (!UnknownS) {
6619 for (const SCEV *Op : P->operands())
6620 AddToWorklist(Op);
6621 continue;
6622 }
6623 // `SCEVUnknown`'s require special treatment.
6624 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6625 if (!RangeRefPHIAllowedOperands(DT, P))
6626 continue;
6627 for (auto &Op : reverse(P->operands()))
6628 AddToWorklist(getSCEV(Op));
6629 }
6630 }
6631
6632 if (!WorkList.empty()) {
6633 // Use getRangeRef to compute ranges for items in the worklist in reverse
6634 // order. This will force ranges for earlier operands to be computed before
6635 // their users in most cases.
6636 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6637 getRangeRef(P, SignHint);
6638 }
6639 }
6640
6641 return getRangeRef(S, SignHint, 0);
6642}
6643
6644const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6645 if (const auto *C = dyn_cast<SCEVConstant>(S))
6646 return &C->getAPInt();
6647 return nullptr;
6648}
6649
6650/// Determine the range for a particular SCEV. If SignHint is
6651/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6652/// with a "cleaner" unsigned (resp. signed) representation.
6653const ConstantRange &ScalarEvolution::getRangeRef(
6654 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6655 DenseMap<const SCEV *, ConstantRange> &Cache =
6656 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6657 : SignedRanges;
6659 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6661
6662 // See if we've computed this range already.
6663 auto I = Cache.find(S);
6664 if (I != Cache.end())
6665 return I->second;
6666
6667 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6668 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6669
6670 // Switch to iteratively computing the range for S, if it is part of a deeply
6671 // nested expression.
6673 return getRangeRefIter(S, SignHint);
6674
6675 unsigned BitWidth = getTypeSizeInBits(S->getType());
6676 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6677 using OBO = OverflowingBinaryOperator;
6678
6679 // If the value has known zeros, the maximum value will have those known zeros
6680 // as well.
6681 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6682 APInt Multiple = getNonZeroConstantMultiple(S);
6683 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6684 if (!Remainder.isZero())
6685 ConservativeResult =
6686 ConstantRange(APInt::getMinValue(BitWidth),
6687 APInt::getMaxValue(BitWidth) - Remainder + 1);
6688 }
6689 else {
6690 uint32_t TZ = getMinTrailingZeros(S);
6691 if (TZ != 0) {
6692 ConservativeResult = ConstantRange(
6694 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6695 }
6696 }
6697
6698 switch (S->getSCEVType()) {
6699 case scConstant:
6700 llvm_unreachable("Already handled above.");
6701 case scVScale:
6702 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6703 case scTruncate: {
6704 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6705 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6706 return setRange(
6707 Trunc, SignHint,
6708 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6709 }
6710 case scZeroExtend: {
6711 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6712 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6713 return setRange(
6714 ZExt, SignHint,
6715 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6716 }
6717 case scSignExtend: {
6718 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6719 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6720 return setRange(
6721 SExt, SignHint,
6722 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6723 }
6724 case scPtrToAddr: {
6725 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6726 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6727 return setRange(Cast, SignHint, X);
6728 }
6729 case scAddExpr: {
6730 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6731 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6732 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6733 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6734 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6735 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6736 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6737 ConservativeResult =
6738 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6739 }
6740 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6741 unsigned WrapType = OBO::AnyWrap;
6742 if (Add->hasNoSignedWrap())
6743 WrapType |= OBO::NoSignedWrap;
6744 if (Add->hasNoUnsignedWrap())
6745 WrapType |= OBO::NoUnsignedWrap;
6746 for (const SCEV *Op : drop_begin(Add->operands()))
6747 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6748 RangeType);
6749 return setRange(Add, SignHint,
6750 ConservativeResult.intersectWith(X, RangeType));
6751 }
6752 case scMulExpr: {
6753 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6754 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6755 for (const SCEV *Op : drop_begin(Mul->operands()))
6756 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6757 return setRange(Mul, SignHint,
6758 ConservativeResult.intersectWith(X, RangeType));
6759 }
6760 case scUDivExpr: {
6761 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6762 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6763 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6764 return setRange(UDiv, SignHint,
6765 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6766 }
6767 case scAddRecExpr: {
6768 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6769 // If there's no unsigned wrap, the value will never be less than its
6770 // initial value.
6771 if (AddRec->hasNoUnsignedWrap()) {
6772 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6773 if (!UnsignedMinValue.isZero())
6774 ConservativeResult = ConservativeResult.intersectWith(
6775 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6776 }
6777
6778 // If there's no signed wrap, and all the operands except initial value have
6779 // the same sign or zero, the value won't ever be:
6780 // 1: smaller than initial value if operands are non negative,
6781 // 2: bigger than initial value if operands are non positive.
6782 // For both cases, value can not cross signed min/max boundary.
6783 if (AddRec->hasNoSignedWrap()) {
6784 bool AllNonNeg = true;
6785 bool AllNonPos = true;
6786 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6787 if (!isKnownNonNegative(AddRec->getOperand(i)))
6788 AllNonNeg = false;
6789 if (!isKnownNonPositive(AddRec->getOperand(i)))
6790 AllNonPos = false;
6791 }
6792 if (AllNonNeg)
6793 ConservativeResult = ConservativeResult.intersectWith(
6796 RangeType);
6797 else if (AllNonPos)
6798 ConservativeResult = ConservativeResult.intersectWith(
6800 getSignedRangeMax(AddRec->getStart()) +
6801 1),
6802 RangeType);
6803 }
6804
6805 // TODO: non-affine addrec
6806 if (AddRec->isAffine()) {
6807 const SCEV *MaxBEScev =
6809 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6810 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6811
6812 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6813 // MaxBECount's active bits are all <= AddRec's bit width.
6814 if (MaxBECount.getBitWidth() > BitWidth &&
6815 MaxBECount.getActiveBits() <= BitWidth)
6816 MaxBECount = MaxBECount.trunc(BitWidth);
6817 else if (MaxBECount.getBitWidth() < BitWidth)
6818 MaxBECount = MaxBECount.zext(BitWidth);
6819
6820 if (MaxBECount.getBitWidth() == BitWidth) {
6821 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6822 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6823 ConservativeResult =
6824 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6825 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6826
6827 auto RangeFromFactoring = getRangeViaFactoring(
6828 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6829 ConservativeResult =
6830 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6831 }
6832 }
6833
6834 // Now try symbolic BE count and more powerful methods.
6836 const SCEV *SymbolicMaxBECount =
6838 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6839 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6840 AddRec->hasNoSelfWrap()) {
6841 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6842 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6843 ConservativeResult =
6844 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6845 }
6846 }
6847 }
6848
6849 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6850 }
6851 case scUMaxExpr:
6852 case scSMaxExpr:
6853 case scUMinExpr:
6854 case scSMinExpr:
6855 case scSequentialUMinExpr: {
6857 switch (S->getSCEVType()) {
6858 case scUMaxExpr:
6859 ID = Intrinsic::umax;
6860 break;
6861 case scSMaxExpr:
6862 ID = Intrinsic::smax;
6863 break;
6864 case scUMinExpr:
6866 ID = Intrinsic::umin;
6867 break;
6868 case scSMinExpr:
6869 ID = Intrinsic::smin;
6870 break;
6871 default:
6872 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6873 }
6874
6875 const auto *NAry = cast<SCEVNAryExpr>(S);
6876 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6877 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6878 X = X.intrinsic(
6879 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6880 return setRange(S, SignHint,
6881 ConservativeResult.intersectWith(X, RangeType));
6882 }
6883 case scUnknown: {
6884 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6885 Value *V = U->getValue();
6886
6887 // Check if the IR explicitly contains !range metadata.
6888 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6889 if (MDRange)
6890 ConservativeResult =
6891 ConservativeResult.intersectWith(*MDRange, RangeType);
6892
6893 // Use facts about recurrences in the underlying IR. Note that add
6894 // recurrences are AddRecExprs and thus don't hit this path. This
6895 // primarily handles shift recurrences.
6896 auto CR = getRangeForUnknownRecurrence(U);
6897 ConservativeResult = ConservativeResult.intersectWith(CR);
6898
6899 // See if ValueTracking can give us a useful range.
6900 const DataLayout &DL = getDataLayout();
6901 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6902 if (Known.getBitWidth() != BitWidth)
6903 Known = Known.zextOrTrunc(BitWidth);
6904
6905 // ValueTracking may be able to compute a tighter result for the number of
6906 // sign bits than for the value of those sign bits.
6907 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6908 if (U->getType()->isPointerTy()) {
6909 // NS counts the sign bits of the whole pointer; drop those above the
6910 // index bits.
6911 unsigned PtrIdxDiff =
6912 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6913 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6914 }
6915
6916 if (NS > 1) {
6917 // If we know any of the sign bits, we know all of the sign bits.
6918 if (!Known.Zero.getHiBits(NS).isZero())
6919 Known.Zero.setHighBits(NS);
6920 if (!Known.One.getHiBits(NS).isZero())
6921 Known.One.setHighBits(NS);
6922 }
6923
6924 if (Known.getMinValue() != Known.getMaxValue() + 1)
6925 ConservativeResult = ConservativeResult.intersectWith(
6926 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6927 RangeType);
6928 if (NS > 1)
6929 ConservativeResult = ConservativeResult.intersectWith(
6930 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6931 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6932 RangeType);
6933
6934 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6935 // Strengthen the range if the underlying IR value is a
6936 // global/alloca/heap allocation using the size of the object.
6937 bool CanBeNull;
6938 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6939 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6940 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6941 // The highest address the object can start is DerefBytes bytes before
6942 // the end (unsigned max value). If this value is not a multiple of the
6943 // alignment, the last possible start value is the next lowest multiple
6944 // of the alignment. Note: The computations below cannot overflow,
6945 // because if they would there's no possible start address for the
6946 // object.
6947 APInt MaxVal =
6948 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6949 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6950 uint64_t Rem = MaxVal.urem(Align);
6951 MaxVal -= APInt(BitWidth, Rem);
6952 APInt MinVal = APInt::getZero(BitWidth);
6953 if (llvm::isKnownNonZero(V, DL))
6954 MinVal = Align;
6955 ConservativeResult = ConservativeResult.intersectWith(
6956 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6957 }
6958 }
6959
6960 // A range of Phi is a subset of union of all ranges of its input.
6961 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6962 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6963 // AddRecs; return the range for the corresponding AddRec.
6964 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6965 return getRangeRef(AR, SignHint, Depth + 1);
6966
6967 // Make sure that we do not run over cycled Phis.
6968 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6969 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6970
6971 for (const auto &Op : Phi->operands()) {
6972 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6973 RangeFromOps = RangeFromOps.unionWith(OpRange);
6974 // No point to continue if we already have a full set.
6975 if (RangeFromOps.isFullSet())
6976 break;
6977 }
6978 ConservativeResult =
6979 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6980 }
6981 }
6982
6983 // vscale can't be equal to zero
6984 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6985 if (II->getIntrinsicID() == Intrinsic::vscale) {
6986 ConstantRange Disallowed = APInt::getZero(BitWidth);
6987 ConservativeResult = ConservativeResult.difference(Disallowed);
6988 }
6989
6990 return setRange(U, SignHint, std::move(ConservativeResult));
6991 }
6992 case scCouldNotCompute:
6993 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6994 }
6995
6996 return setRange(S, SignHint, std::move(ConservativeResult));
6997}
6998
6999// Given a StartRange, Step and MaxBECount for an expression compute a range of
7000// values that the expression can take. Initially, the expression has a value
7001// from StartRange and then is changed by Step up to MaxBECount times. Signed
7002// argument defines if we treat Step as signed or unsigned. The second return
7003// value indicates that no wrapping occurred.
7004static std::pair<ConstantRange, bool>
7006 const APInt &MaxBECount, bool Signed) {
7007 unsigned BitWidth = Step.getBitWidth();
7008 assert(BitWidth == StartRange.getBitWidth() &&
7009 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7010 // If either Step or MaxBECount is 0, then the expression won't change, and we
7011 // just need to return the initial range.
7012 if (Step == 0 || MaxBECount == 0)
7013 return {StartRange, true};
7014
7015 // If we don't know anything about the initial value (i.e. StartRange is
7016 // FullRange), then we don't know anything about the final range either.
7017 // Return FullRange.
7018 if (StartRange.isFullSet())
7019 return {ConstantRange::getFull(BitWidth), false};
7020
7021 // If Step is signed and negative, then we use its absolute value, but we also
7022 // note that we're moving in the opposite direction.
7023 bool Descending = Signed && Step.isNegative();
7024
7025 if (Signed)
7026 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7027 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7028 // This equations hold true due to the well-defined wrap-around behavior of
7029 // APInt.
7030 Step = Step.abs();
7031
7032 // Check if Offset is more than full span of BitWidth. If it is, the
7033 // expression is guaranteed to overflow.
7034 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7035 return {ConstantRange::getFull(BitWidth), false};
7036
7037 // Offset is by how much the expression can change. Checks above guarantee no
7038 // overflow here.
7039 APInt Offset = Step * MaxBECount;
7040
7041 // Minimum value of the final range will match the minimal value of StartRange
7042 // if the expression is increasing and will be decreased by Offset otherwise.
7043 // Maximum value of the final range will match the maximal value of StartRange
7044 // if the expression is decreasing and will be increased by Offset otherwise.
7045 APInt StartLower = StartRange.getLower();
7046 APInt StartUpper = StartRange.getUpper() - 1;
7047 bool Overflow;
7048 APInt MovedBoundary;
7049 if (Signed) {
7050 // This does not use sadd_ov, as we want to check overflow for a signed
7051 // start with an unsigned offset.
7052 if (Descending) {
7053 MovedBoundary = StartLower - std::move(Offset);
7054 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7055 } else {
7056 MovedBoundary = StartUpper + std::move(Offset);
7057 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7058 }
7059 } else {
7060 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7061 Overflow |= StartRange.isWrappedSet();
7062 }
7063
7064 // It's possible that the new minimum/maximum value will fall into the initial
7065 // range (due to wrap around). This means that the expression can take any
7066 // value in this bitwidth, and we have to return full range.
7067 if (StartRange.contains(MovedBoundary))
7068 return {ConstantRange::getFull(BitWidth), false};
7069
7070 APInt NewLower =
7071 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7072 APInt NewUpper =
7073 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7074 NewUpper += 1;
7075
7076 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7077 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7078 !Overflow};
7079}
7080
7081std::pair<ConstantRange, SCEVFlags>
7082ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7083 const APInt &MaxBECount) {
7084 assert(getTypeSizeInBits(Start->getType()) ==
7085 getTypeSizeInBits(Step->getType()) &&
7086 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7087 "mismatched bit widths");
7088
7089 // First, consider step signed.
7090 ConstantRange StartSRange = getSignedRange(Start);
7091 ConstantRange StepSRange = getSignedRange(Step);
7092
7093 // If Step can be both positive and negative, we need to find ranges for the
7094 // maximum absolute step values in both directions and union them.
7095 auto [SR1, NSW1] = getRangeForAffineARHelper(
7096 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7097 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7098 StartSRange, MaxBECount,
7099 /*Signed=*/true);
7100 ConstantRange SR = SR1.unionWith(SR2);
7101
7102 // Next, consider step unsigned.
7103 auto [UR, NUW] = getRangeForAffineARHelper(
7104 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7105 /*Signed=*/false);
7106
7108 if (NUW)
7110 if (NSW1 && NSW2)
7112
7113 // Finally, intersect signed and unsigned ranges.
7115}
7116
7117ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7118 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7119 ScalarEvolution::RangeSignHint SignHint) {
7120 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7121 assert(AddRec->hasNoSelfWrap() &&
7122 "This only works for non-self-wrapping AddRecs!");
7123 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7124 const SCEV *Step = AddRec->getStepRecurrence(*this);
7125 // Only deal with constant step to save compile time.
7126 if (!isa<SCEVConstant>(Step))
7127 return ConstantRange::getFull(BitWidth);
7128 // Let's make sure that we can prove that we do not self-wrap during
7129 // MaxBECount iterations. We need this because MaxBECount is a maximum
7130 // iteration count estimate, and we might infer nw from some exit for which we
7131 // do not know max exit count (or any other side reasoning).
7132 // TODO: Turn into assert at some point.
7133 if (getTypeSizeInBits(MaxBECount->getType()) >
7134 getTypeSizeInBits(AddRec->getType()))
7135 return ConstantRange::getFull(BitWidth);
7136 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7137 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7138 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7139 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7140 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7141 MaxItersWithoutWrap))
7142 return ConstantRange::getFull(BitWidth);
7143
7144 ICmpInst::Predicate LEPred =
7146 ICmpInst::Predicate GEPred =
7148 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7149
7150 // We know that there is no self-wrap. Let's take Start and End values and
7151 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7152 // the iteration. They either lie inside the range [Min(Start, End),
7153 // Max(Start, End)] or outside it:
7154 //
7155 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7156 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7157 //
7158 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7159 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7160 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7161 // Start <= End and step is positive, or Start >= End and step is negative.
7162 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7163 ConstantRange StartRange = getRangeRef(Start, SignHint);
7164 ConstantRange EndRange = getRangeRef(End, SignHint);
7165 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7166 // If they already cover full iteration space, we will know nothing useful
7167 // even if we prove what we want to prove.
7168 if (RangeBetween.isFullSet())
7169 return RangeBetween;
7170 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7171 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7172 : RangeBetween.isWrappedSet();
7173 if (IsWrappedSet)
7174 return ConstantRange::getFull(BitWidth);
7175
7176 if (isKnownPositive(Step) &&
7177 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7178 return RangeBetween;
7179 if (isKnownNegative(Step) &&
7180 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7181 return RangeBetween;
7182 return ConstantRange::getFull(BitWidth);
7183}
7184
7185ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7186 const SCEV *Step,
7187 const APInt &MaxBECount) {
7188 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7189 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7190
7191 unsigned BitWidth = MaxBECount.getBitWidth();
7192 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7193 getTypeSizeInBits(Step->getType()) == BitWidth &&
7194 "mismatched bit widths");
7195
7196 struct SelectPattern {
7197 Value *Condition = nullptr;
7198 APInt TrueValue;
7199 APInt FalseValue;
7200
7201 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7202 const SCEV *S) {
7203 std::optional<unsigned> CastOp;
7204 APInt Offset(BitWidth, 0);
7205
7207 "Should be!");
7208
7209 // Peel off a constant offset. In the future we could consider being
7210 // smarter here and handle {Start+Step,+,Step} too.
7211 const APInt *Off;
7212 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7213 Offset = *Off;
7214
7215 // Peel off a cast operation
7216 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7217 CastOp = SCast->getSCEVType();
7218 S = SCast->getOperand();
7219 }
7220
7221 using namespace llvm::PatternMatch;
7222
7223 auto *SU = dyn_cast<SCEVUnknown>(S);
7224 const APInt *TrueVal, *FalseVal;
7225 if (!SU ||
7226 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7227 m_APInt(FalseVal)))) {
7228 Condition = nullptr;
7229 return;
7230 }
7231
7232 TrueValue = *TrueVal;
7233 FalseValue = *FalseVal;
7234
7235 // Re-apply the cast we peeled off earlier
7236 if (CastOp)
7237 switch (*CastOp) {
7238 default:
7239 llvm_unreachable("Unknown SCEV cast type!");
7240
7241 case scTruncate:
7242 TrueValue = TrueValue.trunc(BitWidth);
7243 FalseValue = FalseValue.trunc(BitWidth);
7244 break;
7245 case scZeroExtend:
7246 TrueValue = TrueValue.zext(BitWidth);
7247 FalseValue = FalseValue.zext(BitWidth);
7248 break;
7249 case scSignExtend:
7250 TrueValue = TrueValue.sext(BitWidth);
7251 FalseValue = FalseValue.sext(BitWidth);
7252 break;
7253 }
7254
7255 // Re-apply the constant offset we peeled off earlier
7256 TrueValue += Offset;
7257 FalseValue += Offset;
7258 }
7259
7260 bool isRecognized() { return Condition != nullptr; }
7261 };
7262
7263 SelectPattern StartPattern(*this, BitWidth, Start);
7264 if (!StartPattern.isRecognized())
7265 return ConstantRange::getFull(BitWidth);
7266
7267 SelectPattern StepPattern(*this, BitWidth, Step);
7268 if (!StepPattern.isRecognized())
7269 return ConstantRange::getFull(BitWidth);
7270
7271 if (StartPattern.Condition != StepPattern.Condition) {
7272 // We don't handle this case today; but we could, by considering four
7273 // possibilities below instead of two. I'm not sure if there are cases where
7274 // that will help over what getRange already does, though.
7275 return ConstantRange::getFull(BitWidth);
7276 }
7277
7278 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7279 // construct arbitrary general SCEV expressions here. This function is called
7280 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7281 // say) can end up caching a suboptimal value.
7282
7283 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7284 // C2352 and C2512 (otherwise it isn't needed).
7285
7286 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7287 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7288 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7289 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7290
7291 ConstantRange TrueRange =
7292 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7293 ConstantRange FalseRange =
7294 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7295
7296 return TrueRange.unionWith(FalseRange);
7297}
7298
7299SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7300 if (isa<ConstantExpr>(V))
7301 return SCEV::FlagNone;
7302 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7303
7304 // Return early if there are no flags to propagate to the SCEV.
7306 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7307 PDI && PDI->isDisjoint()) {
7309 } else {
7310 if (BinOp->hasNoUnsignedWrap())
7312 if (BinOp->hasNoSignedWrap())
7314 }
7315 if (Flags == SCEV::FlagNone)
7316 return SCEV::FlagNone;
7317
7318 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7319}
7320
7321const Instruction *
7322ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7323 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7324 return &*AddRec->getLoop()->getHeader()->begin();
7325 if (auto *U = dyn_cast<SCEVUnknown>(S))
7326 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7327 return I;
7328 return nullptr;
7329}
7330
7331const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7332 bool &Precise) {
7333 Precise = true;
7334 // Do a bounded search of the def relation of the requested SCEVs.
7335 SmallPtrSet<const SCEV *, 16> Visited;
7336 SmallVector<SCEVUse> Worklist;
7337 auto pushOp = [&](const SCEV *S) {
7338 if (!Visited.insert(S).second)
7339 return;
7340 // Threshold of 30 here is arbitrary.
7341 if (Visited.size() > 30) {
7342 Precise = false;
7343 return;
7344 }
7345 Worklist.push_back(S);
7346 };
7347
7348 for (SCEVUse S : Ops)
7349 pushOp(S);
7350
7351 const Instruction *Bound = nullptr;
7352 while (!Worklist.empty()) {
7353 SCEVUse S = Worklist.pop_back_val();
7354 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7355 if (!Bound || DT.dominates(Bound, DefI))
7356 Bound = DefI;
7357 } else {
7358 for (SCEVUse Op : S->operands())
7359 pushOp(Op);
7360 }
7361 }
7362 return Bound ? Bound : &*F.getEntryBlock().begin();
7363}
7364
7365const Instruction *
7366ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7367 bool Discard;
7368 return getDefiningScopeBound(Ops, Discard);
7369}
7370
7371bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7372 const Instruction *B) {
7373 if (A->getParent() == B->getParent() &&
7375 B->getIterator()))
7376 return true;
7377
7378 auto *BLoop = LI.getLoopFor(B->getParent());
7379 if (BLoop && BLoop->getHeader() == B->getParent() &&
7380 BLoop->getLoopPreheader() == A->getParent() &&
7382 A->getParent()->end()) &&
7383 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7384 B->getIterator()))
7385 return true;
7386 return false;
7387}
7388
7390 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7391 visitAll(Op, PC);
7392 return PC.MaybePoison.empty();
7393}
7394
7395bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7396 return !SCEVExprContains(Op, [this](const SCEV *S) {
7397 const SCEV *Op1;
7398 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7399 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7400 // is a non-zero constant, we have to assume the UDiv may be UB.
7401 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7402 });
7403}
7404
7405bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7406 // Only proceed if we can prove that I does not yield poison.
7408 return false;
7409
7410 // At this point we know that if I is executed, then it does not wrap
7411 // according to at least one of NSW or NUW. If I is not executed, then we do
7412 // not know if the calculation that I represents would wrap. Multiple
7413 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7414 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7415 // derived from other instructions that map to the same SCEV. We cannot make
7416 // that guarantee for cases where I is not executed. So we need to find a
7417 // upper bound on the defining scope for the SCEV, and prove that I is
7418 // executed every time we enter that scope. When the bounding scope is a
7419 // loop (the common case), this is equivalent to proving I executes on every
7420 // iteration of that loop.
7421 SmallVector<SCEVUse> SCEVOps;
7422 for (const Use &Op : I->operands()) {
7423 // I could be an extractvalue from a call to an overflow intrinsic.
7424 // TODO: We can do better here in some cases.
7425 if (isSCEVable(Op->getType()))
7426 SCEVOps.push_back(getSCEV(Op));
7427 }
7428 auto *DefI = getDefiningScopeBound(SCEVOps);
7429 return isGuaranteedToTransferExecutionTo(DefI, I);
7430}
7431
7432bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7433 // If we know that \c I can never be poison period, then that's enough.
7434 if (isSCEVExprNeverPoison(I))
7435 return true;
7436
7437 // If the loop only has one exit, then we know that, if the loop is entered,
7438 // any instruction dominating that exit will be executed. If any such
7439 // instruction would result in UB, the addrec cannot be poison.
7440 //
7441 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7442 // also handles uses outside the loop header (they just need to dominate the
7443 // single exit).
7444
7445 auto *ExitingBB = L->getExitingBlock();
7446 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7447 return false;
7448
7449 SmallPtrSet<const Value *, 16> KnownPoison;
7451
7452 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7453 // things that are known to be poison under that assumption go on the
7454 // Worklist.
7455 KnownPoison.insert(I);
7456 Worklist.push_back(I);
7457
7458 while (!Worklist.empty()) {
7459 const Instruction *Poison = Worklist.pop_back_val();
7460
7461 for (const Use &U : Poison->uses()) {
7462 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7463 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7464 DT.dominates(PoisonUser->getParent(), ExitingBB))
7465 return true;
7466
7467 if (propagatesPoison(U) && L->contains(PoisonUser))
7468 if (KnownPoison.insert(PoisonUser).second)
7469 Worklist.push_back(PoisonUser);
7470 }
7471 }
7472
7473 return false;
7474}
7475
7476ScalarEvolution::LoopProperties
7477ScalarEvolution::getLoopProperties(const Loop *L) {
7478 using LoopProperties = ScalarEvolution::LoopProperties;
7479
7480 auto Itr = LoopPropertiesCache.find(L);
7481 if (Itr == LoopPropertiesCache.end()) {
7482 auto HasSideEffects = [](Instruction *I) {
7483 if (auto *SI = dyn_cast<StoreInst>(I))
7484 return !SI->isSimple();
7485
7486 if (I->mayThrow())
7487 return true;
7488
7489 // Non-volatile memset / memcpy do not count as side-effect for forward
7490 // progress.
7491 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7492 return false;
7493
7494 return I->mayWriteToMemory();
7495 };
7496
7497 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7498 /*HasNoSideEffects*/ true};
7499
7500 for (auto *BB : L->getBlocks())
7501 for (auto &I : *BB) {
7503 LP.HasNoAbnormalExits = false;
7504 if (HasSideEffects(&I))
7505 LP.HasNoSideEffects = false;
7506 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7507 break; // We're already as pessimistic as we can get.
7508 }
7509
7510 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7511 assert(InsertPair.second && "We just checked!");
7512 Itr = InsertPair.first;
7513 }
7514
7515 return Itr->second;
7516}
7517
7519 // A mustprogress loop without side effects must be finite.
7520 // TODO: The check used here is very conservative. It's only *specific*
7521 // side effects which are well defined in infinite loops.
7522 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7523}
7524
7525const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7526 // Worklist item with a Value and a bool indicating whether all operands have
7527 // been visited already.
7530
7531 Stack.emplace_back(V, false);
7532 while (!Stack.empty()) {
7533 auto E = Stack.back();
7534 Value *CurV = E.getPointer();
7535
7536 if (getExistingSCEV(CurV)) {
7537 Stack.pop_back();
7538 continue;
7539 }
7540
7542 const SCEV *CreatedSCEV = nullptr;
7543 // If all operands have been visited already, create the SCEV.
7544 if (E.getInt()) {
7545 CreatedSCEV = createSCEV(CurV);
7546 } else {
7547 // Otherwise get the operands we need to create SCEV's for before creating
7548 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7549 // just use it.
7550 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7551 }
7552
7553 if (CreatedSCEV) {
7554 insertValueToMap(CurV, CreatedSCEV);
7555 Stack.pop_back();
7556 } else {
7557 Stack.back().setInt(true);
7558 // Queue its operands which need to be constructed.
7559 for (Value *Op : Ops)
7560 Stack.emplace_back(Op, false);
7561 }
7562 }
7563
7564 return getExistingSCEV(V);
7565}
7566
7567const SCEV *
7568ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7569 if (!isSCEVable(V->getType()))
7570 return getUnknown(V);
7571
7572 if (Instruction *I = dyn_cast<Instruction>(V)) {
7573 // Don't attempt to analyze instructions in blocks that aren't
7574 // reachable. Such instructions don't matter, and they aren't required
7575 // to obey basic rules for definitions dominating uses which this
7576 // analysis depends on.
7577 if (!DT.isReachableFromEntry(I->getParent()))
7578 return getUnknown(PoisonValue::get(V->getType()));
7579 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7580 return getConstant(CI);
7581 else if (isa<GlobalAlias>(V))
7582 return getUnknown(V);
7583 else if (!isa<ConstantExpr>(V))
7584 return getUnknown(V);
7585
7587 if (auto BO =
7589 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7590 switch (BO->Opcode) {
7591 case Instruction::Add:
7592 case Instruction::Mul: {
7593 // For additions and multiplications, traverse add/mul chains for which we
7594 // can potentially create a single SCEV, to reduce the number of
7595 // get{Add,Mul}Expr calls.
7596 do {
7597 if (BO->Op) {
7598 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7599 Ops.push_back(BO->Op);
7600 break;
7601 }
7602 }
7603 Ops.push_back(BO->RHS);
7604 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7606 if (!NewBO ||
7607 (BO->Opcode == Instruction::Add &&
7608 (NewBO->Opcode != Instruction::Add &&
7609 NewBO->Opcode != Instruction::Sub)) ||
7610 (BO->Opcode == Instruction::Mul &&
7611 NewBO->Opcode != Instruction::Mul)) {
7612 Ops.push_back(BO->LHS);
7613 break;
7614 }
7615 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7616 // requires a SCEV for the LHS.
7617 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7618 auto *I = dyn_cast<Instruction>(BO->Op);
7619 if (I && programUndefinedIfPoison(I)) {
7620 Ops.push_back(BO->LHS);
7621 break;
7622 }
7623 }
7624 BO = NewBO;
7625 } while (true);
7626 return nullptr;
7627 }
7628 case Instruction::Sub:
7629 case Instruction::UDiv:
7630 case Instruction::URem:
7631 break;
7632 case Instruction::AShr:
7633 case Instruction::Shl:
7634 case Instruction::Xor:
7635 if (!IsConstArg)
7636 return nullptr;
7637 break;
7638 case Instruction::And:
7639 case Instruction::Or:
7640 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7641 return nullptr;
7642 break;
7643 case Instruction::LShr:
7644 return getUnknown(V);
7645 default:
7646 llvm_unreachable("Unhandled binop");
7647 break;
7648 }
7649
7650 Ops.push_back(BO->LHS);
7651 Ops.push_back(BO->RHS);
7652 return nullptr;
7653 }
7654
7655 switch (U->getOpcode()) {
7656 case Instruction::Trunc:
7657 case Instruction::ZExt:
7658 case Instruction::SExt:
7659 case Instruction::PtrToAddr:
7660 case Instruction::PtrToInt:
7661 Ops.push_back(U->getOperand(0));
7662 return nullptr;
7663
7664 case Instruction::BitCast:
7665 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7666 Ops.push_back(U->getOperand(0));
7667 return nullptr;
7668 }
7669 return getUnknown(V);
7670
7671 case Instruction::SDiv:
7672 case Instruction::SRem:
7673 Ops.push_back(U->getOperand(0));
7674 Ops.push_back(U->getOperand(1));
7675 return nullptr;
7676
7677 case Instruction::GetElementPtr:
7678 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7679 "GEP source element type must be sized");
7680 llvm::append_range(Ops, U->operands());
7681 return nullptr;
7682
7683 case Instruction::IntToPtr:
7684 return getUnknown(V);
7685
7686 case Instruction::PHI:
7687 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7688 // relevant nodes for each of them.
7689 //
7690 // The first is just to call simplifyInstruction, and get something back
7691 // that isn't a PHI.
7692 if (Value *V = simplifyInstruction(
7693 cast<PHINode>(U),
7694 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7695 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7696 assert(V);
7697 Ops.push_back(V);
7698 return nullptr;
7699 }
7700 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7701 // operands which all perform the same operation, but haven't been
7702 // CSE'ed for whatever reason.
7703 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7704 assert(BO);
7705 Ops.push_back(BO);
7706 return nullptr;
7707 }
7708 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7709 // is equivalent to a select, and analyzes it like a select.
7710 {
7711 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7713 assert(Cond);
7714 assert(LHS);
7715 assert(RHS);
7716 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7717 Ops.push_back(CondICmp->getOperand(0));
7718 Ops.push_back(CondICmp->getOperand(1));
7719 }
7720 Ops.push_back(Cond);
7721 Ops.push_back(LHS);
7722 Ops.push_back(RHS);
7723 return nullptr;
7724 }
7725 }
7726 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7727 // so just construct it recursively.
7728 //
7729 // In addition to getNodeForPHI, also construct nodes which might be needed
7730 // by getRangeRef.
7732 for (Value *V : cast<PHINode>(U)->operands())
7733 Ops.push_back(V);
7734 return nullptr;
7735 }
7736 return nullptr;
7737
7738 case Instruction::Select: {
7739 // Check if U is a select that can be simplified to a SCEVUnknown.
7740 auto CanSimplifyToUnknown = [this, U]() {
7741 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7742 return false;
7743
7744 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7745 if (!ICI)
7746 return false;
7747 Value *LHS = ICI->getOperand(0);
7748 Value *RHS = ICI->getOperand(1);
7749 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7750 ICI->getPredicate() == CmpInst::ICMP_NE) {
7752 return true;
7753 } else if (getTypeSizeInBits(LHS->getType()) >
7754 getTypeSizeInBits(U->getType()))
7755 return true;
7756 return false;
7757 };
7758 if (CanSimplifyToUnknown())
7759 return getUnknown(U);
7760
7761 llvm::append_range(Ops, U->operands());
7762 return nullptr;
7763 break;
7764 }
7765 case Instruction::Call:
7766 case Instruction::Invoke:
7767 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7768 Ops.push_back(RV);
7769 return nullptr;
7770 }
7771
7772 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7773 switch (II->getIntrinsicID()) {
7774 case Intrinsic::abs:
7775 Ops.push_back(II->getArgOperand(0));
7776 return nullptr;
7777 case Intrinsic::umax:
7778 case Intrinsic::umin:
7779 case Intrinsic::smax:
7780 case Intrinsic::smin:
7781 case Intrinsic::usub_sat:
7782 case Intrinsic::uadd_sat:
7783 Ops.push_back(II->getArgOperand(0));
7784 Ops.push_back(II->getArgOperand(1));
7785 return nullptr;
7786 case Intrinsic::start_loop_iterations:
7787 case Intrinsic::annotation:
7788 case Intrinsic::ptr_annotation:
7789 Ops.push_back(II->getArgOperand(0));
7790 return nullptr;
7791 default:
7792 break;
7793 }
7794 }
7795 break;
7796 }
7797
7798 return nullptr;
7799}
7800
7801const SCEV *ScalarEvolution::createSCEV(Value *V) {
7802 if (!isSCEVable(V->getType()))
7803 return getUnknown(V);
7804
7805 if (Instruction *I = dyn_cast<Instruction>(V)) {
7806 // Don't attempt to analyze instructions in blocks that aren't
7807 // reachable. Such instructions don't matter, and they aren't required
7808 // to obey basic rules for definitions dominating uses which this
7809 // analysis depends on.
7810 if (!DT.isReachableFromEntry(I->getParent()))
7811 return getUnknown(PoisonValue::get(V->getType()));
7812 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7813 return getConstant(CI);
7814 else if (isa<GlobalAlias>(V))
7815 return getUnknown(V);
7816 else if (!isa<ConstantExpr>(V))
7817 return getUnknown(V);
7818
7819 const SCEV *LHS;
7820 const SCEV *RHS;
7821
7823 if (auto BO =
7825 switch (BO->Opcode) {
7826 case Instruction::Add: {
7827 // The simple thing to do would be to just call getSCEV on both operands
7828 // and call getAddExpr with the result. However if we're looking at a
7829 // bunch of things all added together, this can be quite inefficient,
7830 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7831 // Instead, gather up all the operands and make a single getAddExpr call.
7832 // LLVM IR canonical form means we need only traverse the left operands.
7834 do {
7835 if (BO->Op) {
7836 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7837 AddOps.push_back(OpSCEV);
7838 break;
7839 }
7840
7841 // If a NUW or NSW flag can be applied to the SCEV for this
7842 // addition, then compute the SCEV for this addition by itself
7843 // with a separate call to getAddExpr. We need to do that
7844 // instead of pushing the operands of the addition onto AddOps,
7845 // since the flags are only known to apply to this particular
7846 // addition - they may not apply to other additions that can be
7847 // formed with operands from AddOps.
7848 const SCEV *RHS = getSCEV(BO->RHS);
7849 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7850 if (Flags != SCEV::FlagNone) {
7851 const SCEV *LHS = getSCEV(BO->LHS);
7852 if (BO->Opcode == Instruction::Sub)
7853 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7854 else
7855 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7856 break;
7857 }
7858 }
7859
7860 if (BO->Opcode == Instruction::Sub)
7861 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7862 else
7863 AddOps.push_back(getSCEV(BO->RHS));
7864
7865 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7867 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7868 NewBO->Opcode != Instruction::Sub)) {
7869 AddOps.push_back(getSCEV(BO->LHS));
7870 break;
7871 }
7872 BO = NewBO;
7873 } while (true);
7874
7875 return getAddExpr(AddOps);
7876 }
7877
7878 case Instruction::Mul: {
7880 do {
7881 if (BO->Op) {
7882 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7883 MulOps.push_back(OpSCEV);
7884 break;
7885 }
7886
7887 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7888 if (Flags != SCEV::FlagNone) {
7889 LHS = getSCEV(BO->LHS);
7890 RHS = getSCEV(BO->RHS);
7891 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7892 break;
7893 }
7894 }
7895
7896 MulOps.push_back(getSCEV(BO->RHS));
7897 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7899 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7900 MulOps.push_back(getSCEV(BO->LHS));
7901 break;
7902 }
7903 BO = NewBO;
7904 } while (true);
7905
7906 return getMulExpr(MulOps);
7907 }
7908 case Instruction::UDiv:
7909 LHS = getSCEV(BO->LHS);
7910 RHS = getSCEV(BO->RHS);
7911 return getUDivExpr(LHS, RHS);
7912 case Instruction::URem:
7913 LHS = getSCEV(BO->LHS);
7914 RHS = getSCEV(BO->RHS);
7915 return getURemExpr(LHS, RHS);
7916 case Instruction::Sub: {
7918 if (BO->Op)
7919 Flags = getNoWrapFlagsFromUB(BO->Op);
7920
7921 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7922 // operand. While we don't model ptrtoint directly in SCEV, the
7923 // difference between two pointer addresses is well-defined.
7924 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7925 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7926 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7927 if (HasPtrLHS || HasPtrRHS) {
7928 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7929 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7930 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7931 // useful structure.
7932 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7933 bool BothPtr) -> const SCEV * {
7934 if (!HasPtr)
7935 return getSCEV(OrigOp);
7936 const SCEV *PtrSCEV = getSCEV(PtrOp);
7937 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7938 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7939 if (!isa<SCEVCouldNotCompute>(Addr) &&
7940 getTypeSizeInBits(OrigOp->getType()) <=
7941 getTypeSizeInBits(Addr->getType()))
7942 return getTruncateOrNoop(Addr, OrigOp->getType());
7943 }
7944 return getSCEV(OrigOp);
7945 };
7946 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7947 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7948 return getMinusSCEV(L, R, Flags);
7949 }
7950
7951 LHS = getSCEV(BO->LHS);
7952 RHS = getSCEV(BO->RHS);
7953 return getMinusSCEV(LHS, RHS, Flags);
7954 }
7955 case Instruction::And:
7956 // For an expression like x&255 that merely masks off the high bits,
7957 // use zext(trunc(x)) as the SCEV expression.
7958 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7959 if (CI->isZero())
7960 return getSCEV(BO->RHS);
7961 if (CI->isMinusOne())
7962 return getSCEV(BO->LHS);
7963 const APInt &A = CI->getValue();
7964
7965 // Instcombine's ShrinkDemandedConstant may strip bits out of
7966 // constants, obscuring what would otherwise be a low-bits mask.
7967 // Use computeKnownBits to compute what ShrinkDemandedConstant
7968 // knew about to reconstruct a low-bits mask value.
7969 unsigned LZ = A.countl_zero();
7970 unsigned TZ = A.countr_zero();
7971 unsigned BitWidth = A.getBitWidth();
7972 KnownBits Known(BitWidth);
7973 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7974
7975 APInt EffectiveMask =
7976 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7977 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7978 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7979 const SCEV *LHS = getSCEV(BO->LHS);
7980 const SCEV *ShiftedLHS = nullptr;
7981 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7982 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7983 // For an expression like (x * 8) & 8, simplify the multiply.
7984 unsigned MulZeros = OpC->getAPInt().countr_zero();
7985 unsigned GCD = std::min(MulZeros, TZ);
7986 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7988 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7989 append_range(MulOps, LHSMul->operands().drop_front());
7990 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7991 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
7992 }
7993 }
7994 if (!ShiftedLHS)
7995 ShiftedLHS = getUDivExpr(LHS, MulCount);
7996 return getMulExpr(
7998 getTruncateExpr(ShiftedLHS,
7999 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8000 BO->LHS->getType()),
8001 MulCount);
8002 }
8003 }
8004 // Binary `and` is a bit-wise `umin`.
8005 if (BO->LHS->getType()->isIntegerTy(1)) {
8006 LHS = getSCEV(BO->LHS);
8007 RHS = getSCEV(BO->RHS);
8008 return getUMinExpr(LHS, RHS);
8009 }
8010 break;
8011
8012 case Instruction::Or:
8013 // Binary `or` is a bit-wise `umax`.
8014 if (BO->LHS->getType()->isIntegerTy(1)) {
8015 LHS = getSCEV(BO->LHS);
8016 RHS = getSCEV(BO->RHS);
8017 return getUMaxExpr(LHS, RHS);
8018 }
8019 break;
8020
8021 case Instruction::Xor:
8022 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8023 // If the RHS of xor is -1, then this is a not operation.
8024 if (CI->isMinusOne())
8025 return getNotSCEV(getSCEV(BO->LHS));
8026
8027 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8028 // This is a variant of the check for xor with -1, and it handles
8029 // the case where instcombine has trimmed non-demanded bits out
8030 // of an xor with -1.
8031 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8032 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8033 if (LBO->getOpcode() == Instruction::And &&
8034 LCI->getValue() == CI->getValue())
8035 if (const SCEVZeroExtendExpr *Z =
8037 Type *UTy = BO->LHS->getType();
8038 const SCEV *Z0 = Z->getOperand();
8039 Type *Z0Ty = Z0->getType();
8040 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8041
8042 // If C is a low-bits mask, the zero extend is serving to
8043 // mask off the high bits. Complement the operand and
8044 // re-apply the zext.
8045 if (CI->getValue().isMask(Z0TySize))
8046 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8047
8048 // If C is a single bit, it may be in the sign-bit position
8049 // before the zero-extend. In this case, represent the xor
8050 // using an add, which is equivalent, and re-apply the zext.
8051 APInt Trunc = CI->getValue().trunc(Z0TySize);
8052 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8053 Trunc.isSignMask())
8054 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8055 UTy);
8056 }
8057 }
8058 break;
8059
8060 case Instruction::Shl:
8061 // Turn shift left of a constant amount into a multiply.
8062 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8063 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8064
8065 // If the shift count is not less than the bitwidth, the result of
8066 // the shift is undefined. Don't try to analyze it, because the
8067 // resolution chosen here may differ from the resolution chosen in
8068 // other parts of the compiler.
8069 if (SA->getValue().uge(BitWidth))
8070 break;
8071
8072 // We can safely preserve the nuw flag in all cases. It's also safe to
8073 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8074 // requires special handling. It can be preserved as long as we're not
8075 // left shifting by bitwidth - 1.
8076 auto Flags = SCEV::FlagNone;
8077 if (BO->Op) {
8078 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8079 if (any(MulFlags & SCEV::FlagNSW) &&
8080 (any(MulFlags & SCEV::FlagNUW) ||
8081 SA->getValue().ult(BitWidth - 1)))
8083 if (any(MulFlags & SCEV::FlagNUW))
8085 }
8086
8087 ConstantInt *X = ConstantInt::get(
8088 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8089 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8090 }
8091 break;
8092
8093 case Instruction::AShr:
8094 // AShr X, C, where C is a constant.
8095 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8096 if (!CI)
8097 break;
8098
8099 Type *OuterTy = BO->LHS->getType();
8101 // If the shift count is not less than the bitwidth, the result of
8102 // the shift is undefined. Don't try to analyze it, because the
8103 // resolution chosen here may differ from the resolution chosen in
8104 // other parts of the compiler.
8105 if (CI->getValue().uge(BitWidth))
8106 break;
8107
8108 if (CI->isZero())
8109 return getSCEV(BO->LHS); // shift by zero --> noop
8110
8111 uint64_t AShrAmt = CI->getZExtValue();
8112 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8113
8114 Operator *L = dyn_cast<Operator>(BO->LHS);
8115 const SCEV *AddTruncateExpr = nullptr;
8116 ConstantInt *ShlAmtCI = nullptr;
8117 const SCEV *AddConstant = nullptr;
8118
8119 if (L && L->getOpcode() == Instruction::Add) {
8120 // X = Shl A, n
8121 // Y = Add X, c
8122 // Z = AShr Y, m
8123 // n, c and m are constants.
8124
8125 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8126 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8127 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8128 if (AddOperandCI) {
8129 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8130 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8131 // since we truncate to TruncTy, the AddConstant should be of the
8132 // same type, so create a new Constant with type same as TruncTy.
8133 // Also, the Add constant should be shifted right by AShr amount.
8134 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8135 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8136 // we model the expression as sext(add(trunc(A), c << n)), since the
8137 // sext(trunc) part is already handled below, we create a
8138 // AddExpr(TruncExp) which will be used later.
8139 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8140 }
8141 }
8142 } else if (L && L->getOpcode() == Instruction::Shl) {
8143 // X = Shl A, n
8144 // Y = AShr X, m
8145 // Both n and m are constant.
8146
8147 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8148 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8149 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8150 }
8151
8152 if (AddTruncateExpr && ShlAmtCI) {
8153 // We can merge the two given cases into a single SCEV statement,
8154 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8155 // a simpler case. The following code handles the two cases:
8156 //
8157 // 1) For a two-shift sext-inreg, i.e. n = m,
8158 // use sext(trunc(x)) as the SCEV expression.
8159 //
8160 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8161 // expression. We already checked that ShlAmt < BitWidth, so
8162 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8163 // ShlAmt - AShrAmt < Amt.
8164 const APInt &ShlAmt = ShlAmtCI->getValue();
8165 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8166 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8167 ShlAmtCI->getZExtValue() - AShrAmt);
8168 const SCEV *CompositeExpr =
8169 getMulExpr(AddTruncateExpr, getConstant(Mul));
8170 if (L->getOpcode() != Instruction::Shl)
8171 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8172
8173 return getSignExtendExpr(CompositeExpr, OuterTy);
8174 }
8175 }
8176 break;
8177 }
8178 }
8179
8180 switch (U->getOpcode()) {
8181 case Instruction::Trunc:
8182 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8183
8184 case Instruction::ZExt:
8185 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8186
8187 case Instruction::SExt:
8188 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8190 // The NSW flag of a subtract does not always survive the conversion to
8191 // A + (-1)*B. By pushing sign extension onto its operands we are much
8192 // more likely to preserve NSW and allow later AddRec optimisations.
8193 //
8194 // NOTE: This is effectively duplicating this logic from getSignExtend:
8195 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8196 // but by that point the NSW information has potentially been lost.
8197 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8198 Type *Ty = U->getType();
8199 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8200 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8201 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8202 }
8203 }
8204 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8205
8206 case Instruction::BitCast:
8207 // BitCasts are no-op casts so we just eliminate the cast.
8208 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8209 return getSCEV(U->getOperand(0));
8210 break;
8211
8212 case Instruction::PtrToAddr: {
8213 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8214 if (isa<SCEVCouldNotCompute>(IntOp))
8215 return getUnknown(V);
8216 return IntOp;
8217 }
8218
8219 case Instruction::PtrToInt:
8220 // SCEV only models ptrtoaddr.
8221 return getUnknown(V);
8222
8223 case Instruction::IntToPtr:
8224 // Just don't deal with inttoptr casts.
8225 return getUnknown(V);
8226
8227 case Instruction::SDiv:
8228 // If both operands are non-negative, this is just an udiv.
8229 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8230 isKnownNonNegative(getSCEV(U->getOperand(1))))
8231 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8232 break;
8233
8234 case Instruction::SRem:
8235 // If both operands are non-negative, this is just an urem.
8236 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8237 isKnownNonNegative(getSCEV(U->getOperand(1))))
8238 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8239 break;
8240
8241 case Instruction::GetElementPtr:
8242 return createNodeForGEP(cast<GEPOperator>(U));
8243
8244 case Instruction::PHI:
8245 return createNodeForPHI(cast<PHINode>(U));
8246
8247 case Instruction::Select:
8248 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8249 U->getOperand(2));
8250
8251 case Instruction::Call:
8252 case Instruction::Invoke:
8253 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8254 return getSCEV(RV);
8255
8256 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8257 switch (II->getIntrinsicID()) {
8258 case Intrinsic::abs:
8259 return getAbsExpr(
8260 getSCEV(II->getArgOperand(0)),
8261 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8262 case Intrinsic::umax:
8263 LHS = getSCEV(II->getArgOperand(0));
8264 RHS = getSCEV(II->getArgOperand(1));
8265 return getUMaxExpr(LHS, RHS);
8266 case Intrinsic::umin:
8267 LHS = getSCEV(II->getArgOperand(0));
8268 RHS = getSCEV(II->getArgOperand(1));
8269 return getUMinExpr(LHS, RHS);
8270 case Intrinsic::smax:
8271 LHS = getSCEV(II->getArgOperand(0));
8272 RHS = getSCEV(II->getArgOperand(1));
8273 return getSMaxExpr(LHS, RHS);
8274 case Intrinsic::smin:
8275 LHS = getSCEV(II->getArgOperand(0));
8276 RHS = getSCEV(II->getArgOperand(1));
8277 return getSMinExpr(LHS, RHS);
8278 case Intrinsic::usub_sat: {
8279 const SCEV *X = getSCEV(II->getArgOperand(0));
8280 const SCEV *Y = getSCEV(II->getArgOperand(1));
8281 const SCEV *ClampedY = getUMinExpr(X, Y);
8282 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8283 }
8284 case Intrinsic::uadd_sat: {
8285 const SCEV *X = getSCEV(II->getArgOperand(0));
8286 const SCEV *Y = getSCEV(II->getArgOperand(1));
8287 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8288 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8289 }
8290 case Intrinsic::start_loop_iterations:
8291 case Intrinsic::annotation:
8292 case Intrinsic::ptr_annotation:
8293 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8294 // just eqivalent to the first operand for SCEV purposes.
8295 return getSCEV(II->getArgOperand(0));
8296 case Intrinsic::vscale:
8297 return getVScale(II->getType());
8298 default:
8299 break;
8300 }
8301 }
8302 break;
8303 }
8304
8305 return getUnknown(V);
8306}
8307
8308//===----------------------------------------------------------------------===//
8309// Iteration Count Computation Code
8310//
8311
8313 if (isa<SCEVCouldNotCompute>(ExitCount))
8314 return getCouldNotCompute();
8315
8316 auto *ExitCountType = ExitCount->getType();
8317 assert(ExitCountType->isIntegerTy());
8318 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8319 1 + ExitCountType->getScalarSizeInBits());
8320 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8321}
8322
8324 Type *EvalTy,
8325 const Loop *L) {
8326 if (isa<SCEVCouldNotCompute>(ExitCount))
8327 return getCouldNotCompute();
8328
8329 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8330 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8331
8332 auto CanAddOneWithoutOverflow = [&]() {
8333 ConstantRange ExitCountRange =
8334 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8335 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8336 return true;
8337
8338 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8339 getMinusOne(ExitCount->getType()));
8340 };
8341
8342 // If we need to zero extend the backedge count, check if we can add one to
8343 // it prior to zero extending without overflow. Provided this is safe, it
8344 // allows better simplification of the +1.
8345 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8346 return getZeroExtendExpr(
8347 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8348
8349 // Get the total trip count from the count by adding 1. This may wrap.
8350 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8351}
8352
8353static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8354 if (!ExitCount)
8355 return 0;
8356
8357 ConstantInt *ExitConst = ExitCount->getValue();
8358
8359 // Guard against huge trip counts.
8360 if (ExitConst->getValue().getActiveBits() > 32)
8361 return 0;
8362
8363 // In case of integer overflow, this returns 0, which is correct.
8364 return ((unsigned)ExitConst->getZExtValue()) + 1;
8365}
8366
8368 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8369 return getConstantTripCount(ExitCount);
8370}
8371
8372unsigned
8374 const BasicBlock *ExitingBlock) {
8375 assert(ExitingBlock && "Must pass a non-null exiting block!");
8376 assert(L->isLoopExiting(ExitingBlock) &&
8377 "Exiting block must actually branch out of the loop!");
8378 const SCEVConstant *ExitCount =
8379 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8380 return getConstantTripCount(ExitCount);
8381}
8382
8384 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8385
8386 const auto *MaxExitCount =
8387 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8389 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8390}
8391
8393 SmallVector<BasicBlock *, 8> ExitingBlocks;
8394 L->getExitingBlocks(ExitingBlocks);
8395
8396 // An exit with an uncomputable exit count makes the result 1.
8397 if (ExitingBlocks.empty() ||
8398 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8399 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8400 }))
8401 return 1;
8402
8403 LoopGuards Guards = LoopGuards::collect(L, *this);
8404 unsigned Res = 0;
8405 for (BasicBlock *ExitingBB : ExitingBlocks)
8406 Res = std::gcd(
8407 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8408 return Res;
8409}
8410
8411unsigned
8413 const LoopGuards &Guards) {
8414 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8415
8416 // Get the trip count
8417 const SCEV *TCExpr =
8418 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8419
8420 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8421 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8422 // the greatest power of 2 divisor less than 2^32.
8423 return Multiple.getActiveBits() > 32
8424 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8425 : (unsigned)Multiple.getZExtValue();
8426}
8427
8429 const SCEV *ExitCount) {
8430 if (isa<SCEVCouldNotCompute>(ExitCount))
8431 return 1;
8432
8433 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8434}
8435
8436/// Returns the largest constant divisor of the trip count of this loop as a
8437/// normal unsigned value, if possible. This means that the actual trip count is
8438/// always a multiple of the returned value (don't forget the trip count could
8439/// very well be zero as well!).
8440///
8441/// Returns 1 if the trip count is unknown or not guaranteed to be the
8442/// multiple of a constant (which is also the case if the trip count is simply
8443/// constant, use getSmallConstantTripCount for that case), Will also return 1
8444/// if the trip count is very large (>= 2^32).
8445///
8446/// As explained in the comments for getSmallConstantTripCount, this assumes
8447/// that control exits the loop via ExitingBlock.
8448unsigned
8450 const BasicBlock *ExitingBlock) {
8451 assert(ExitingBlock && "Must pass a non-null exiting block!");
8452 assert(L->isLoopExiting(ExitingBlock) &&
8453 "Exiting block must actually branch out of the loop!");
8454 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8455 return getSmallConstantTripMultiple(L, ExitCount);
8456}
8457
8459 const BasicBlock *ExitingBlock,
8460 ExitCountKind Kind) {
8461 switch (Kind) {
8462 case Exact:
8463 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8464 case SymbolicMaximum:
8465 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8466 case ConstantMaximum:
8467 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8468 };
8469 llvm_unreachable("Invalid ExitCountKind!");
8470}
8471
8473 const Loop *L, const BasicBlock *ExitingBlock,
8475 switch (Kind) {
8476 case Exact:
8477 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8478 Predicates);
8479 case SymbolicMaximum:
8480 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8481 Predicates);
8482 case ConstantMaximum:
8483 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8484 Predicates);
8485 };
8486 llvm_unreachable("Invalid ExitCountKind!");
8487}
8488
8491 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8492}
8493
8495 ExitCountKind Kind) {
8496 switch (Kind) {
8497 case Exact:
8498 return getBackedgeTakenInfo(L).getExact(L, this);
8499 case ConstantMaximum:
8500 return getBackedgeTakenInfo(L).getConstantMax(this);
8501 case SymbolicMaximum:
8502 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8503 };
8504 llvm_unreachable("Invalid ExitCountKind!");
8505}
8506
8509 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8510}
8511
8514 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8515}
8516
8518 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8519}
8520
8521/// Push PHI nodes in the header of the given loop onto the given Worklist.
8522static void PushLoopPHIs(const Loop *L,
8525 BasicBlock *Header = L->getHeader();
8526
8527 // Push all Loop-header PHIs onto the Worklist stack.
8528 for (PHINode &PN : Header->phis())
8529 if (Visited.insert(&PN).second)
8530 Worklist.push_back(&PN);
8531}
8532
8533ScalarEvolution::BackedgeTakenInfo &
8534ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8535 auto &BTI = getBackedgeTakenInfo(L);
8536 if (BTI.hasFullInfo())
8537 return BTI;
8538
8539 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8540
8541 if (!Pair.second)
8542 return Pair.first->second;
8543
8544 BackedgeTakenInfo Result =
8545 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8546
8547 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8548}
8549
8550ScalarEvolution::BackedgeTakenInfo &
8551ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8552 // Initially insert an invalid entry for this loop. If the insertion
8553 // succeeds, proceed to actually compute a backedge-taken count and
8554 // update the value. The temporary CouldNotCompute value tells SCEV
8555 // code elsewhere that it shouldn't attempt to request a new
8556 // backedge-taken count, which could result in infinite recursion.
8557 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8558 BackedgeTakenCounts.try_emplace(L);
8559 if (!Pair.second)
8560 return Pair.first->second;
8561
8562 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8563 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8564 // must be cleared in this scope.
8565 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8566
8567 // Now that we know more about the trip count for this loop, forget any
8568 // existing SCEV values for PHI nodes in this loop since they are only
8569 // conservative estimates made without the benefit of trip count
8570 // information. This invalidation is not necessary for correctness, and is
8571 // only done to produce more precise results.
8572 if (Result.hasAnyInfo()) {
8573 // Invalidate any expression using an addrec in this loop.
8574 SmallVector<SCEVUse, 8> ToForget;
8575 auto LoopUsersIt = LoopUsers.find(L);
8576 if (LoopUsersIt != LoopUsers.end())
8577 append_range(ToForget, LoopUsersIt->second);
8578 forgetMemoizedResults(ToForget);
8579
8580 // Invalidate constant-evolved loop header phis.
8581 for (PHINode &PN : L->getHeader()->phis())
8582 ConstantEvolutionLoopExitValue.erase(&PN);
8583 }
8584
8585 // Re-lookup the insert position, since the call to
8586 // computeBackedgeTakenCount above could result in a
8587 // recusive call to getBackedgeTakenInfo (on a different
8588 // loop), which would invalidate the iterator computed
8589 // earlier.
8590 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8591}
8592
8594 // This method is intended to forget all info about loops. It should
8595 // invalidate caches as if the following happened:
8596 // - The trip counts of all loops have changed arbitrarily
8597 // - Every llvm::Value has been updated in place to produce a different
8598 // result.
8599 BackedgeTakenCounts.clear();
8600 PredicatedBackedgeTakenCounts.clear();
8601 BECountUsers.clear();
8602 LoopPropertiesCache.clear();
8603 ConstantEvolutionLoopExitValue.clear();
8604 ValueExprMap.clear();
8605 ValuesAtScopes.clear();
8606 ValuesAtScopesUsers.clear();
8607 LoopDispositions.clear();
8608 BlockDispositions.clear();
8609 UnsignedRanges.clear();
8610 SignedRanges.clear();
8611 ExprValueMap.clear();
8612 HasRecMap.clear();
8613 ConstantMultipleCache.clear();
8614 PredicatedSCEVRewrites.clear();
8615 FoldCache.clear();
8616 FoldCacheUser.clear();
8617}
8618void ScalarEvolution::visitAndClearUsers(
8621 SmallVectorImpl<SCEVUse> &ToForget) {
8622 // Nothing can be invalidated if no value has a SCEV yet.
8623 if (ValueExprMap.empty()) {
8624 Worklist.clear();
8625 return;
8626 }
8627 while (!Worklist.empty()) {
8628 Instruction *I = Worklist.pop_back_val();
8629 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8630 continue;
8631
8633 ValueExprMap.find_as(static_cast<Value *>(I));
8634 if (It != ValueExprMap.end()) {
8635 ToForget.push_back(It->second);
8636 eraseValueFromMap(It->first);
8637 if (PHINode *PN = dyn_cast<PHINode>(I))
8638 ConstantEvolutionLoopExitValue.erase(PN);
8639 }
8640
8641 PushDefUseChildren(I, Worklist, Visited);
8642 }
8643}
8644
8646 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8649 SmallVector<SCEVUse, 16> ToForget;
8650
8651 // Iterate over all the loops and sub-loops to drop SCEV information.
8652 while (!LoopWorklist.empty()) {
8653 auto *CurrL = LoopWorklist.pop_back_val();
8654
8655 // Drop any stored trip count value.
8656 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8657 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8658
8659 // Drop information about predicated SCEV rewrites for this loop.
8660 PredicatedSCEVRewrites.remove_if(
8661 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8662
8663 auto LoopUsersItr = LoopUsers.find(CurrL);
8664 if (LoopUsersItr != LoopUsers.end())
8665 llvm::append_range(ToForget, LoopUsersItr->second);
8666
8667 // Drop information about expressions based on loop-header PHIs.
8668 PushLoopPHIs(CurrL, Worklist, Visited);
8669 visitAndClearUsers(Worklist, Visited, ToForget);
8670
8671 LoopPropertiesCache.erase(CurrL);
8672 // Forget all contained loops too, to avoid dangling entries in the
8673 // ValuesAtScopes map.
8674 LoopWorklist.append(CurrL->begin(), CurrL->end());
8675 }
8676 forgetMemoizedResults(ToForget);
8677}
8678
8680 forgetLoop(L->getOutermostLoop());
8681}
8682
8685 if (!I) return;
8686
8687 // Drop information about expressions based on loop-header PHIs.
8690 SmallVector<SCEVUse, 8> ToForget;
8691 Worklist.push_back(I);
8692 Visited.insert(I);
8693 visitAndClearUsers(Worklist, Visited, ToForget);
8694
8695 forgetMemoizedResults(ToForget);
8696}
8697
8701 SmallVector<SCEVUse, 8> ToForget;
8702 for (Value *V : Values)
8703 if (auto *I = dyn_cast<Instruction>(V))
8704 if (Visited.insert(I).second)
8705 Worklist.push_back(I);
8706 visitAndClearUsers(Worklist, Visited, ToForget);
8707
8708 forgetMemoizedResults(ToForget);
8709}
8710
8712 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8713 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8714 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8715 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8716 auto InvalidateValue = [&](Value *Val) {
8717 if (!isSCEVable(Val->getType()))
8718 return;
8719 if (const SCEV *S = getExistingSCEV(Val)) {
8720 struct InvalidationRootCollector {
8721 Loop *L;
8723
8724 InvalidationRootCollector(Loop *L) : L(L) {}
8725
8726 bool follow(const SCEV *S) {
8727 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8728 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8729 if (L->contains(I))
8730 Roots.push_back(S);
8731 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8732 if (L->contains(AddRec->getLoop()))
8733 Roots.push_back(S);
8734 }
8735 return true;
8736 }
8737 bool isDone() const { return false; }
8738 };
8739
8740 InvalidationRootCollector C(L);
8741 visitAll(S, C);
8742 forgetMemoizedResults(C.Roots);
8743 }
8744 };
8745
8746 InvalidateValue(V);
8747
8748 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8749 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8750 // expressions referencing loop-internal values.
8751 if (!isSCEVable(V->getType()) &&
8752 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8753 for (User *U : V->users())
8754 InvalidateValue(U);
8755 // Also perform the normal invalidation.
8756 forgetValue(V);
8757}
8758
8759void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8760
8762 // Unless a specific value is passed to invalidation, completely clear both
8763 // caches.
8764 if (!V) {
8765 BlockDispositions.clear();
8766 LoopDispositions.clear();
8767 return;
8768 }
8769
8770 if (!isSCEVable(V->getType()))
8771 return;
8772
8773 const SCEV *S = getExistingSCEV(V);
8774 if (!S)
8775 return;
8776
8777 // Invalidate the block and loop dispositions cached for S. Dispositions of
8778 // S's users may change if S's disposition changes (i.e. a user may change to
8779 // loop-invariant, if S changes to loop invariant), so also invalidate
8780 // dispositions of S's users recursively.
8781 SmallVector<SCEVUse, 8> Worklist = {S};
8783 while (!Worklist.empty()) {
8784 const SCEV *Curr = Worklist.pop_back_val();
8785 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8786 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8787 if (!LoopDispoRemoved && !BlockDispoRemoved)
8788 continue;
8789 auto Users = SCEVUsers.find(Curr);
8790 if (Users != SCEVUsers.end())
8791 for (const auto *User : Users->second)
8792 if (Seen.insert(User).second)
8793 Worklist.push_back(User);
8794 }
8795}
8796
8797/// Get the exact loop backedge taken count considering all loop exits. A
8798/// computable result can only be returned for loops with all exiting blocks
8799/// dominating the latch. howFarToZero assumes that the limit of each loop test
8800/// is never skipped. This is a valid assumption as long as the loop exits via
8801/// that test. For precise results, it is the caller's responsibility to specify
8802/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8803const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8804 const Loop *L, ScalarEvolution *SE,
8806 // If any exits were not computable, the loop is not computable.
8807 if (!isComplete() || ExitNotTaken.empty())
8808 return SE->getCouldNotCompute();
8809
8810 const BasicBlock *Latch = L->getLoopLatch();
8811 // All exiting blocks we have collected must dominate the only backedge.
8812 if (!Latch)
8813 return SE->getCouldNotCompute();
8814
8815 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8816 // count is simply a minimum out of all these calculated exit counts.
8818 for (const auto &ENT : ExitNotTaken) {
8819 const SCEV *BECount = ENT.ExactNotTaken;
8820 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8821 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8822 "We should only have known counts for exiting blocks that dominate "
8823 "latch!");
8824
8825 Ops.push_back(BECount);
8826
8827 if (Preds)
8828 append_range(*Preds, ENT.Predicates);
8829
8830 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8831 "Predicate should be always true!");
8832 }
8833
8834 // If an earlier exit exits on the first iteration (exit count zero), then
8835 // a later poison exit count should not propagate into the result. This are
8836 // exactly the semantics provided by umin_seq.
8837 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8838}
8839
8840const ScalarEvolution::ExitNotTakenInfo *
8841ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8842 const BasicBlock *ExitingBlock,
8843 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8844 for (const auto &ENT : ExitNotTaken)
8845 if (ENT.ExitingBlock == ExitingBlock) {
8846 if (ENT.hasAlwaysTruePredicate())
8847 return &ENT;
8848 else if (Predicates) {
8849 append_range(*Predicates, ENT.Predicates);
8850 return &ENT;
8851 }
8852 }
8853
8854 return nullptr;
8855}
8856
8857/// getConstantMax - Get the constant max backedge taken count for the loop.
8858const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8859 ScalarEvolution *SE,
8860 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8861 if (!getConstantMax())
8862 return SE->getCouldNotCompute();
8863
8864 for (const auto &ENT : ExitNotTaken)
8865 if (!ENT.hasAlwaysTruePredicate()) {
8866 if (!Predicates)
8867 return SE->getCouldNotCompute();
8868 append_range(*Predicates, ENT.Predicates);
8869 }
8870
8871 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8872 isa<SCEVConstant>(getConstantMax())) &&
8873 "No point in having a non-constant max backedge taken count!");
8874 return getConstantMax();
8875}
8876
8877const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8878 const Loop *L, ScalarEvolution *SE,
8879 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8880 if (!SymbolicMax) {
8881 // Form an expression for the maximum exit count possible for this loop. We
8882 // merge the max and exact information to approximate a version of
8883 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8884 // constants.
8885 SmallVector<SCEVUse, 4> ExitCounts;
8886
8887 for (const auto &ENT : ExitNotTaken) {
8888 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8889 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8890 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8891 "We should only have known counts for exiting blocks that "
8892 "dominate latch!");
8893 ExitCounts.push_back(ExitCount);
8894 if (Predicates)
8895 append_range(*Predicates, ENT.Predicates);
8896
8897 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8898 "Predicate should be always true!");
8899 }
8900 }
8901 if (ExitCounts.empty())
8902 SymbolicMax = SE->getCouldNotCompute();
8903 else
8904 SymbolicMax =
8905 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8906 }
8907 return SymbolicMax;
8908}
8909
8910bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8911 ScalarEvolution *SE) const {
8912 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8913 return !ENT.hasAlwaysTruePredicate();
8914 };
8915 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8916}
8917
8920
8922 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8923 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8927 // If we prove the max count is zero, so is the symbolic bound. This happens
8928 // in practice due to differences in a) how context sensitive we've chosen
8929 // to be and b) how we reason about bounds implied by UB.
8930 if (ConstantMaxNotTaken->isZero()) {
8931 this->ExactNotTaken = E = ConstantMaxNotTaken;
8932 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8933 }
8934
8937 "Exact is not allowed to be less precise than Constant Max");
8940 "Exact is not allowed to be less precise than Symbolic Max");
8943 "Symbolic Max is not allowed to be less precise than Constant Max");
8946 "No point in having a non-constant max backedge taken count!");
8948 for (const auto PredList : PredLists)
8949 for (const auto *P : PredList) {
8950 if (SeenPreds.contains(P))
8951 continue;
8952 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8953 SeenPreds.insert(P);
8954 Predicates.push_back(P);
8955 }
8956 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8957 "Backedge count should be int");
8959 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8960 "Max backedge count should be int");
8961}
8962
8970
8971/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8972/// computable exit into a persistent ExitNotTakenInfo array.
8973ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8975 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8976 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8977 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8978
8979 ExitNotTaken.reserve(ExitCounts.size());
8980 std::transform(ExitCounts.begin(), ExitCounts.end(),
8981 std::back_inserter(ExitNotTaken),
8982 [&](const EdgeExitInfo &EEI) {
8983 BasicBlock *ExitBB = EEI.first;
8984 const ExitLimit &EL = EEI.second;
8985 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8986 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8987 EL.Predicates);
8988 });
8989 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8990 isa<SCEVConstant>(ConstantMax)) &&
8991 "No point in having a non-constant max backedge taken count!");
8992}
8993
8994/// Compute the number of times the backedge of the specified loop will execute.
8995ScalarEvolution::BackedgeTakenInfo
8996ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8997 bool AllowPredicates) {
8998 SmallVector<BasicBlock *, 8> ExitingBlocks;
8999 L->getExitingBlocks(ExitingBlocks);
9000
9001 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9002
9004 bool CouldComputeBECount = true;
9005 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9006 const SCEV *MustExitMaxBECount = nullptr;
9007 const SCEV *MayExitMaxBECount = nullptr;
9008 bool MustExitMaxOrZero = false;
9009 bool IsOnlyExit = ExitingBlocks.size() == 1;
9010
9011 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9012 // and compute maxBECount.
9013 // Do a union of all the predicates here.
9014 for (BasicBlock *ExitBB : ExitingBlocks) {
9015 // We canonicalize untaken exits to br (constant), ignore them so that
9016 // proving an exit untaken doesn't negatively impact our ability to reason
9017 // about the loop as whole.
9018 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9019 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9020 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9021 if (ExitIfTrue == CI->isZero())
9022 continue;
9023 }
9024
9025 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9026
9027 assert((AllowPredicates || EL.Predicates.empty()) &&
9028 "Predicated exit limit when predicates are not allowed!");
9029
9030 // 1. For each exit that can be computed, add an entry to ExitCounts.
9031 // CouldComputeBECount is true only if all exits can be computed.
9032 if (EL.ExactNotTaken != getCouldNotCompute())
9033 ++NumExitCountsComputed;
9034 else
9035 // We couldn't compute an exact value for this exit, so
9036 // we won't be able to compute an exact value for the loop.
9037 CouldComputeBECount = false;
9038 // Remember exit count if either exact or symbolic is known. Because
9039 // Exact always implies symbolic, only check symbolic.
9040 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9041 ExitCounts.emplace_back(ExitBB, EL);
9042 else {
9043 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9044 "Exact is known but symbolic isn't?");
9045 ++NumExitCountsNotComputed;
9046 }
9047
9048 // 2. Derive the loop's MaxBECount from each exit's max number of
9049 // non-exiting iterations. Partition the loop exits into two kinds:
9050 // LoopMustExits and LoopMayExits.
9051 //
9052 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9053 // is a LoopMayExit. If any computable LoopMustExit is found, then
9054 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9055 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9056 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9057 // any
9058 // computable EL.ConstantMaxNotTaken.
9059 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9060 DT.dominates(ExitBB, Latch)) {
9061 if (!MustExitMaxBECount) {
9062 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9063 MustExitMaxOrZero = EL.MaxOrZero;
9064 } else {
9065 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9066 EL.ConstantMaxNotTaken);
9067 }
9068 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9069 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9070 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9071 else {
9072 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9073 EL.ConstantMaxNotTaken);
9074 }
9075 }
9076 }
9077 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9078 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9079 // The loop backedge will be taken the maximum or zero times if there's
9080 // a single exit that must be taken the maximum or zero times.
9081 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9082
9083 // Remember which SCEVs are used in exit limits for invalidation purposes.
9084 // We only care about non-constant SCEVs here, so we can ignore
9085 // EL.ConstantMaxNotTaken
9086 // and MaxBECount, which must be SCEVConstant.
9087 for (const auto &Pair : ExitCounts) {
9088 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9089 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9090 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9091 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9092 {L, AllowPredicates});
9093 }
9094 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9095 MaxBECount, MaxOrZero);
9096}
9097
9098ScalarEvolution::ExitLimit
9099ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9100 bool IsOnlyExit, bool AllowPredicates) {
9101 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9102 // If our exiting block does not dominate the latch, then its connection with
9103 // loop's exit limit may be far from trivial.
9104 const BasicBlock *Latch = L->getLoopLatch();
9105 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9106 return getCouldNotCompute();
9107
9108 Instruction *Term = ExitingBlock->getTerminator();
9109 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9110 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9111 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9112 "It should have one successor in loop and one exit block!");
9113 // Proceed to the next level to examine the exit condition expression.
9114 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9115 /*ControlsOnlyExit=*/IsOnlyExit,
9116 AllowPredicates);
9117 }
9118
9119 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9120 // For switch, make sure that there is a single exit from the loop.
9121 BasicBlock *Exit = nullptr;
9122 for (auto *SBB : successors(ExitingBlock))
9123 if (!L->contains(SBB)) {
9124 if (Exit) // Multiple exit successors.
9125 return getCouldNotCompute();
9126 Exit = SBB;
9127 }
9128 assert(Exit && "Exiting block must have at least one exit");
9129 return computeExitLimitFromSingleExitSwitch(
9130 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9131 }
9132
9133 return getCouldNotCompute();
9134}
9135
9137 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9138 bool AllowPredicates) {
9139 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9140 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9141 ControlsOnlyExit, AllowPredicates);
9142}
9143
9144std::optional<ScalarEvolution::ExitLimit>
9145ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9146 bool ExitIfTrue, bool ControlsOnlyExit,
9147 bool AllowPredicates) {
9148 (void)this->L;
9149 (void)this->ExitIfTrue;
9150 (void)this->AllowPredicates;
9151
9152 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9153 this->AllowPredicates == AllowPredicates &&
9154 "Variance in assumed invariant key components!");
9155 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9156 if (Itr == TripCountMap.end())
9157 return std::nullopt;
9158 return Itr->second;
9159}
9160
9161void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9162 bool ExitIfTrue,
9163 bool ControlsOnlyExit,
9164 bool AllowPredicates,
9165 const ExitLimit &EL) {
9166 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9167 this->AllowPredicates == AllowPredicates &&
9168 "Variance in assumed invariant key components!");
9169
9170 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9171 assert(InsertResult.second && "Expected successful insertion!");
9172 (void)InsertResult;
9173 (void)ExitIfTrue;
9174}
9175
9176ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9177 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9178 bool ControlsOnlyExit, bool AllowPredicates) {
9179
9180 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9181 AllowPredicates))
9182 return *MaybeEL;
9183
9184 ExitLimit EL = computeExitLimitFromCondImpl(
9185 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9186 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9187 return EL;
9188}
9189
9190ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9191 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9192 bool ControlsOnlyExit, bool AllowPredicates) {
9193 // Handle BinOp conditions (And, Or).
9194 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9195 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9196 return *LimitFromBinOp;
9197
9198 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9199 // Proceed to the next level to examine the icmp.
9200 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9201 ExitLimit EL =
9202 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9203 if (EL.hasFullInfo() || !AllowPredicates)
9204 return EL;
9205
9206 // Try again, but use SCEV predicates this time.
9207 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9208 ControlsOnlyExit,
9209 /*AllowPredicates=*/true);
9210 }
9211
9212 // Check for a constant condition. These are normally stripped out by
9213 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9214 // preserve the CFG and is temporarily leaving constant conditions
9215 // in place.
9216 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9217 if (ExitIfTrue == !CI->getZExtValue())
9218 // The backedge is always taken.
9219 return getCouldNotCompute();
9220 // The backedge is never taken.
9221 return getZero(CI->getType());
9222 }
9223
9224 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9225 // with a constant step, we can form an equivalent icmp predicate and figure
9226 // out how many iterations will be taken before we exit.
9227 const WithOverflowInst *WO;
9228 const APInt *C;
9229 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9230 match(WO->getRHS(), m_APInt(C))) {
9231 ConstantRange NWR =
9233 WO->getNoWrapKind());
9234 CmpInst::Predicate Pred;
9235 APInt NewRHSC, Offset;
9236 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9237 if (!ExitIfTrue)
9238 Pred = ICmpInst::getInversePredicate(Pred);
9239 auto *LHS = getSCEV(WO->getLHS());
9240 if (Offset != 0)
9242 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9243 ControlsOnlyExit, AllowPredicates);
9244 if (EL.hasAnyInfo())
9245 return EL;
9246 }
9247
9248 // If it's not an integer or pointer comparison then compute it the hard way.
9249 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9250}
9251
9252std::optional<ScalarEvolution::ExitLimit>
9253ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9254 const Loop *L,
9255 Value *ExitCond,
9256 bool ExitIfTrue,
9257 bool AllowPredicates) {
9258 // Check if the controlling expression for this loop is an And or Or.
9259 Value *Op0, *Op1;
9260 bool IsAnd;
9261 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9262 IsAnd = true;
9263 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9264 IsAnd = false;
9265 else
9266 return std::nullopt;
9267
9268 // A sub-condition of a non-trivial binop never solely controls the exit,
9269 // whether we exit always depends on both conditions.
9270 ExitLimit EL0 = computeExitLimitFromCondCached(
9271 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9272 ExitLimit EL1 = computeExitLimitFromCondCached(
9273 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9274
9275 // EitherMayExit is true in these two cases:
9276 // br (and Op0 Op1), loop, exit
9277 // br (or Op0 Op1), exit, loop
9278 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9279
9280 const SCEV *BECount = getCouldNotCompute();
9281 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9282 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9283 if (EitherMayExit) {
9284 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9285 // Both conditions must be same for the loop to continue executing.
9286 // Choose the less conservative count.
9287 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9288 EL1.ExactNotTaken != getCouldNotCompute()) {
9289 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9290 UseSequentialUMin);
9291 }
9292 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9293 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9294 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9295 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9296 else
9297 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9298 EL1.ConstantMaxNotTaken);
9299 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9300 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9301 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9302 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9303 else
9304 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9305 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9306 } else {
9307 // Both conditions must be same at the same time for the loop to exit.
9308 // For now, be conservative.
9309 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9310 BECount = EL0.ExactNotTaken;
9311 }
9312
9313 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9314 // to be more aggressive when computing BECount than when computing
9315 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9316 // and
9317 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9318 // EL1.ConstantMaxNotTaken to not.
9319 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9320 !isa<SCEVCouldNotCompute>(BECount))
9321 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9322 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9323 SymbolicMaxBECount =
9324 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9325 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9326 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9327}
9328
9329ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9330 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9331 bool AllowPredicates) {
9332 // If the condition was exit on true, convert the condition to exit on false
9333 CmpPredicate Pred;
9334 if (!ExitIfTrue)
9335 Pred = ExitCond->getCmpPredicate();
9336 else
9337 Pred = ExitCond->getInverseCmpPredicate();
9338 const ICmpInst::Predicate OriginalPred = Pred;
9339
9340 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9341 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9342
9343 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9344 AllowPredicates);
9345 if (EL.hasAnyInfo())
9346 return EL;
9347
9348 auto *ExhaustiveCount =
9349 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9350
9351 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9352 return ExhaustiveCount;
9353
9354 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9355 ExitCond->getOperand(1), L, OriginalPred);
9356}
9357ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9358 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9359 bool ControlsOnlyExit, bool AllowPredicates) {
9360
9361 // Try to evaluate any dependencies out of the loop.
9362 LHS = getSCEVAtScope(LHS, L);
9363 RHS = getSCEVAtScope(RHS, L);
9364
9365 // At this point, we would like to compute how many iterations of the
9366 // loop the predicate will return true for these inputs.
9367 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9368 // If there is a loop-invariant, force it into the RHS.
9369 std::swap(LHS, RHS);
9371 }
9372
9373 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9375 // Simplify the operands before analyzing them.
9376 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9377
9378 // If we have a comparison of a chrec against a constant, try to use value
9379 // ranges to answer this query.
9380 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9381 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9382 if (AddRec->getLoop() == L) {
9383 // Form the constant range.
9384 ConstantRange CompRange =
9385 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9386
9387 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9388 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9389 }
9390
9391 // If this loop must exit based on this condition (or execute undefined
9392 // behaviour), see if we can improve wrap flags. This is essentially
9393 // a must execute style proof.
9394 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9395 // If we can prove the test sequence produced must repeat the same values
9396 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9397 // because if it did, we'd have an infinite (undefined) loop.
9398 // TODO: We can peel off any functions which are invertible *in L*. Loop
9399 // invariant terms are effectively constants for our purposes here.
9400 SCEVUse InnerLHS = LHS;
9401 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9402 InnerLHS = ZExt->getOperand();
9403 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9404 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9405 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9406 /*OrNegative=*/true)) {
9407 auto Flags = AR->getNoWrapFlags();
9408 Flags = setFlags(Flags, SCEV::FlagNW);
9411 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9412 }
9413
9414 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9415 // From no-self-wrap, this follows trivially from the fact that every
9416 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9417 // last value before (un)signed wrap. Since we know that last value
9418 // didn't exit, nor will any smaller one.
9419 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9420 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9421 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9422 AR && AR->getLoop() == L && AR->isAffine() &&
9423 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9424 isKnownPositive(AR->getStepRecurrence(*this))) {
9425 auto Flags = AR->getNoWrapFlags();
9426 Flags = setFlags(Flags, WrapType);
9429 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9430 }
9431 }
9432 }
9433
9434 switch (Pred) {
9435 case ICmpInst::ICMP_NE: { // while (X != Y)
9436 // Convert to: while (X-Y != 0)
9437 if (LHS->getType()->isPointerTy()) {
9440 return LHS;
9441 }
9442 if (RHS->getType()->isPointerTy()) {
9445 return RHS;
9446 }
9447 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9448 AllowPredicates);
9449 if (EL.hasAnyInfo())
9450 return EL;
9451 break;
9452 }
9453 case ICmpInst::ICMP_EQ: { // while (X == Y)
9454 // Convert to: while (X-Y == 0)
9455 if (LHS->getType()->isPointerTy()) {
9458 return LHS;
9459 }
9460 if (RHS->getType()->isPointerTy()) {
9463 return RHS;
9464 }
9465 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9466 if (EL.hasAnyInfo()) return EL;
9467 break;
9468 }
9469 case ICmpInst::ICMP_SLE:
9470 case ICmpInst::ICMP_ULE:
9471 // Since the loop is finite, an invariant RHS cannot include the boundary
9472 // value, otherwise it would loop forever.
9473 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9474 !isLoopInvariant(RHS, L)) {
9475 // Otherwise, perform the addition in a wider type, to avoid overflow.
9476 // If the LHS is an addrec with the appropriate nowrap flag, the
9477 // extension will be sunk into it and the exit count can be analyzed.
9478 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9479 if (!OldType)
9480 break;
9481 // Prefer doubling the bitwidth over adding a single bit to make it more
9482 // likely that we use a legal type.
9483 auto *NewType =
9484 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9485 if (ICmpInst::isSigned(Pred)) {
9486 LHS = getSignExtendExpr(LHS, NewType);
9487 RHS = getSignExtendExpr(RHS, NewType);
9488 } else {
9489 LHS = getZeroExtendExpr(LHS, NewType);
9490 RHS = getZeroExtendExpr(RHS, NewType);
9491 }
9492 }
9494 [[fallthrough]];
9495 case ICmpInst::ICMP_SLT:
9496 case ICmpInst::ICMP_ULT: { // while (X < Y)
9497 bool IsSigned = ICmpInst::isSigned(Pred);
9498 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9499 ControlsOnlyExit, AllowPredicates);
9500 if (EL.hasAnyInfo())
9501 return EL;
9502 break;
9503 }
9504 case ICmpInst::ICMP_SGE:
9505 case ICmpInst::ICMP_UGE:
9506 // Since the loop is finite, an invariant RHS cannot include the boundary
9507 // value, otherwise it would loop forever.
9508 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9509 !isLoopInvariant(RHS, L))
9510 break;
9512 [[fallthrough]];
9513 case ICmpInst::ICMP_SGT:
9514 case ICmpInst::ICMP_UGT: { // while (X > Y)
9515 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9516 bool IsSigned = ICmpInst::isSigned(Pred);
9517 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9518 ControlsOnlyExit, AllowPredicates);
9519 if (EL.hasAnyInfo())
9520 return EL;
9521 break;
9522 }
9523 default:
9524 break;
9525 }
9526
9527 return getCouldNotCompute();
9528}
9529
9530ScalarEvolution::ExitLimit
9531ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9532 SwitchInst *Switch,
9533 BasicBlock *ExitingBlock,
9534 bool ControlsOnlyExit) {
9535 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9536
9537 // Give up if the exit is the default dest of a switch.
9538 if (Switch->getDefaultDest() == ExitingBlock)
9539 return getCouldNotCompute();
9540
9541 assert(L->contains(Switch->getDefaultDest()) &&
9542 "Default case must not exit the loop!");
9543 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9544 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9545
9546 // while (X != Y) --> while (X-Y != 0)
9547 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9548 if (EL.hasAnyInfo())
9549 return EL;
9550
9551 return getCouldNotCompute();
9552}
9553
9554static ConstantInt *
9556 ScalarEvolution &SE) {
9557 const SCEV *InVal = SE.getConstant(C);
9558 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9560 "Evaluation of SCEV at constant didn't fold correctly?");
9561 return cast<SCEVConstant>(Val)->getValue();
9562}
9563
9564ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9565 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9566 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9567 if (!RHS)
9568 return getCouldNotCompute();
9569
9570 const BasicBlock *Latch = L->getLoopLatch();
9571 if (!Latch)
9572 return getCouldNotCompute();
9573
9574 const BasicBlock *Predecessor = L->getLoopPredecessor();
9575 if (!Predecessor)
9576 return getCouldNotCompute();
9577
9578 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9579 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9580 // OutShiftAmt.
9581 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9582 Instruction::BinaryOps &OutOpCode,
9583 unsigned &OutShiftAmt) {
9584 using namespace PatternMatch;
9585
9586 ConstantInt *ShiftAmt;
9587 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9588 OutOpCode = Instruction::LShr;
9589 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9590 OutOpCode = Instruction::AShr;
9591 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9592 OutOpCode = Instruction::Shl;
9593 else
9594 return false;
9595
9596 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9597 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9598 return false;
9599 OutShiftAmt = Amt;
9600 return true;
9601 };
9602
9603 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9604 //
9605 // loop:
9606 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9607 // %iv.shifted = lshr i32 %iv, <positive constant>
9608 //
9609 // Return true on a successful match. Return the corresponding PHI node (%iv
9610 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9611 // shift amount in ShiftAmtOut.
9612 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9613 Instruction::BinaryOps &OpCodeOut,
9614 unsigned &ShiftAmtOut) {
9615 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9616
9617 {
9619 Value *V;
9620 unsigned Amt;
9621
9622 // If we encounter a shift instruction, "peel off" the shift operation,
9623 // and remember that we did so. Later when we inspect %iv's backedge
9624 // value, we will make sure that the backedge value uses the same
9625 // operation.
9626 //
9627 // Note: the peeled shift operation does not have to be the same
9628 // instruction as the one feeding into the PHI's backedge value. We only
9629 // really care about it being the same *kind* of shift instruction --
9630 // that's all that is required for our later inferences to hold.
9631 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9632 PostShiftOpCode = OpC;
9633 LHS = V;
9634 }
9635 }
9636
9637 PNOut = dyn_cast<PHINode>(LHS);
9638 if (!PNOut || PNOut->getParent() != L->getHeader())
9639 return false;
9640
9641 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9642 Value *OpLHS;
9643
9644 return
9645 // The backedge value for the PHI node must be a shift by a positive
9646 // amount
9647 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9648
9649 // of the PHI node itself
9650 OpLHS == PNOut &&
9651
9652 // and the kind of shift should be match the kind of shift we peeled
9653 // off, if any.
9654 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9655 };
9656
9657 PHINode *PN;
9659 unsigned ShiftAmt;
9660 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9661 return getCouldNotCompute();
9662
9663 const DataLayout &DL = getDataLayout();
9664
9665 // The key rationale for this optimization is that for some kinds of shift
9666 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9667 // within a finite number of iterations. If the condition guarding the
9668 // backedge (in the sense that the backedge is taken if the condition is true)
9669 // is false for the value the shift recurrence stabilizes to, then we know
9670 // that the backedge is taken only a finite number of times.
9671
9672 ConstantInt *StableValue = nullptr;
9673 switch (OpCode) {
9674 default:
9675 llvm_unreachable("Impossible case!");
9676
9677 case Instruction::AShr: {
9678 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9679 // bitwidth(K) iterations.
9680 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9681 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9682 Predecessor->getTerminator(), &DT);
9683 auto *Ty = cast<IntegerType>(RHS->getType());
9684 if (Known.isNonNegative())
9685 StableValue = ConstantInt::get(Ty, 0);
9686 else if (Known.isNegative())
9687 StableValue = ConstantInt::get(Ty, -1, true);
9688 else
9689 return getCouldNotCompute();
9690
9691 break;
9692 }
9693 case Instruction::LShr:
9694 case Instruction::Shl:
9695 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9696 // stabilize to 0 in at most bitwidth(K) iterations.
9697 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9698 break;
9699 }
9700
9701 auto *Result =
9702 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9703 assert(Result->getType()->isIntegerTy(1) &&
9704 "Otherwise cannot be an operand to a branch instruction");
9705
9706 if (Result->isNullValue()) {
9707 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9708 unsigned MaxBTC = BitWidth;
9709
9710 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9711 // compute a tighter max backedge-taken count from the range of the start
9712 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9713 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9714 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9715 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9716 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9717 const SCEV *StartSCEV = getSCEV(StartValue);
9718 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9719 if (MaxStart.isStrictlyPositive()) {
9720 unsigned ActiveBits = MaxStart.getActiveBits();
9721 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9722 MaxBTC = std::min(MaxBTC, RangeBTC);
9723 }
9724 }
9725
9726 const SCEV *UpperBound =
9728 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9729 }
9730
9731 return getCouldNotCompute();
9732}
9733
9734/// Return true if we can constant fold an instruction of the specified type,
9735/// assuming that all operands were constants.
9736static bool canConstantFold(const Instruction *I,
9737 const TargetLibraryInfo *TLI) {
9741 return true;
9742
9743 if (const CallInst *CI = dyn_cast<CallInst>(I))
9744 if (const Function *F = CI->getCalledFunction())
9745 return canConstantFoldCallTo(CI, F, TLI);
9746 return false;
9747}
9748
9749/// Determine whether this instruction can constant evolve within this loop
9750/// assuming its operands can all constant evolve.
9751static bool canConstantEvolve(Instruction *I, const Loop *L,
9752 const TargetLibraryInfo *TLI) {
9753 // An instruction outside of the loop can't be derived from a loop PHI.
9754 if (!L->contains(I)) return false;
9755
9756 if (isa<PHINode>(I)) {
9757 // We don't currently keep track of the control flow needed to evaluate
9758 // PHIs, so we cannot handle PHIs inside of loops.
9759 return L->getHeader() == I->getParent();
9760 }
9761
9762 // If we won't be able to constant fold this expression even if the operands
9763 // are constants, bail early.
9764 return canConstantFold(I, TLI);
9765}
9766
9767/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9768/// recursing through each instruction operand until reaching a loop header phi.
9769static PHINode *
9772 const TargetLibraryInfo *TLI, unsigned Depth) {
9774 return nullptr;
9775
9776 // Otherwise, we can evaluate this instruction if all of its operands are
9777 // constant or derived from a PHI node themselves.
9778 PHINode *PHI = nullptr;
9779 for (Value *Op : UseInst->operands()) {
9780 if (isa<Constant>(Op)) continue;
9781
9783 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9784 return nullptr;
9785
9786 PHINode *P = dyn_cast<PHINode>(OpInst);
9787 if (!P)
9788 // If this operand is already visited, reuse the prior result.
9789 // We may have P != PHI if this is the deepest point at which the
9790 // inconsistent paths meet.
9791 P = PHIMap.lookup(OpInst);
9792 if (!P) {
9793 // Recurse and memoize the results, whether a phi is found or not.
9794 // This recursive call invalidates pointers into PHIMap.
9795 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9796 PHIMap[OpInst] = P;
9797 }
9798 if (!P)
9799 return nullptr; // Not evolving from PHI
9800 if (PHI && PHI != P)
9801 return nullptr; // Evolving from multiple different PHIs.
9802 PHI = P;
9803 }
9804 // This is a expression evolving from a constant PHI!
9805 return PHI;
9806}
9807
9808/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9809/// in the loop that V is derived from. We allow arbitrary operations along the
9810/// way, but the operands of an operation must either be constants or a value
9811/// derived from a constant PHI. If this expression does not fit with these
9812/// constraints, return null.
9814 const TargetLibraryInfo *TLI) {
9816 if (!I || !canConstantEvolve(I, L, TLI))
9817 return nullptr;
9818
9819 if (PHINode *PN = dyn_cast<PHINode>(I))
9820 return PN;
9821
9822 // Record non-constant instructions contained by the loop.
9824 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9825}
9826
9827/// EvaluateExpression - Given an expression that passes the
9828/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9829/// in the loop has the value PHIVal. If we can't fold this expression for some
9830/// reason, return null.
9833 const DataLayout &DL,
9834 const TargetLibraryInfo *TLI) {
9835 // Convenient constant check, but redundant for recursive calls.
9836 if (Constant *C = dyn_cast<Constant>(V)) return C;
9838 if (!I) return nullptr;
9839
9840 if (Constant *C = Vals.lookup(I)) return C;
9841
9842 // An instruction inside the loop depends on a value outside the loop that we
9843 // weren't given a mapping for, or a value such as a call inside the loop.
9844 if (!canConstantEvolve(I, L, TLI))
9845 return nullptr;
9846
9847 // An unmapped PHI can be due to a branch or another loop inside this loop,
9848 // or due to this not being the initial iteration through a loop where we
9849 // couldn't compute the evolution of this particular PHI last time.
9850 if (isa<PHINode>(I)) return nullptr;
9851
9852 std::vector<Constant*> Operands(I->getNumOperands());
9853
9854 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9855 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9856 if (!Operand) {
9857 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9858 if (!Operands[i]) return nullptr;
9859 continue;
9860 }
9861 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9862 Vals[Operand] = C;
9863 if (!C) return nullptr;
9864 Operands[i] = C;
9865 }
9866
9867 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9868 /*AllowNonDeterministic=*/false);
9869}
9870
9871
9872// If every incoming value to PN except the one for BB is a specific Constant,
9873// return that, else return nullptr.
9875 Constant *IncomingVal = nullptr;
9876
9877 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9878 if (PN->getIncomingBlock(i) == BB)
9879 continue;
9880
9881 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9882 if (!CurrentVal)
9883 return nullptr;
9884
9885 if (IncomingVal != CurrentVal) {
9886 if (IncomingVal)
9887 return nullptr;
9888 IncomingVal = CurrentVal;
9889 }
9890 }
9891
9892 return IncomingVal;
9893}
9894
9895/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9896/// in the header of its containing loop, we know the loop executes a
9897/// constant number of times, and the PHI node is just a recurrence
9898/// involving constants, fold it.
9899Constant *
9900ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9901 const APInt &BEs,
9902 const Loop *L) {
9903 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9904 if (!Inserted)
9905 return I->second;
9906
9908 return nullptr; // Not going to evaluate it.
9909
9910 Constant *&RetVal = I->second;
9911
9912 DenseMap<Instruction *, Constant *> CurrentIterVals;
9913 BasicBlock *Header = L->getHeader();
9914 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9915
9916 BasicBlock *Latch = L->getLoopLatch();
9917 if (!Latch)
9918 return nullptr;
9919
9920 for (PHINode &PHI : Header->phis()) {
9921 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9922 CurrentIterVals[&PHI] = StartCST;
9923 }
9924 if (!CurrentIterVals.count(PN))
9925 return RetVal = nullptr;
9926
9927 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9928
9929 // Execute the loop symbolically to determine the exit value.
9930 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9931 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9932
9933 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9934 unsigned IterationNum = 0;
9935 const DataLayout &DL = getDataLayout();
9936 for (; ; ++IterationNum) {
9937 if (IterationNum == NumIterations)
9938 return RetVal = CurrentIterVals[PN]; // Got exit value!
9939
9940 // Compute the value of the PHIs for the next iteration.
9941 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9942 DenseMap<Instruction *, Constant *> NextIterVals;
9943 Constant *NextPHI =
9944 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9945 if (!NextPHI)
9946 return nullptr; // Couldn't evaluate!
9947 NextIterVals[PN] = NextPHI;
9948
9949 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9950
9951 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9952 // cease to be able to evaluate one of them or if they stop evolving,
9953 // because that doesn't necessarily prevent us from computing PN.
9955 for (const auto &I : CurrentIterVals) {
9956 PHINode *PHI = dyn_cast<PHINode>(I.first);
9957 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9958 PHIsToCompute.emplace_back(PHI, I.second);
9959 }
9960 // We use two distinct loops because EvaluateExpression may invalidate any
9961 // iterators into CurrentIterVals.
9962 for (const auto &I : PHIsToCompute) {
9963 PHINode *PHI = I.first;
9964 Constant *&NextPHI = NextIterVals[PHI];
9965 if (!NextPHI) { // Not already computed.
9966 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9967 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9968 }
9969 if (NextPHI != I.second)
9970 StoppedEvolving = false;
9971 }
9972
9973 // If all entries in CurrentIterVals == NextIterVals then we can stop
9974 // iterating, the loop can't continue to change.
9975 if (StoppedEvolving)
9976 return RetVal = CurrentIterVals[PN];
9977
9978 CurrentIterVals.swap(NextIterVals);
9979 }
9980}
9981
9982const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9983 Value *Cond,
9984 bool ExitWhen) {
9985 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
9986 if (!PN) return getCouldNotCompute();
9987
9988 // If the loop is canonicalized, the PHI will have exactly two entries.
9989 // That's the only form we support here.
9990 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9991
9992 DenseMap<Instruction *, Constant *> CurrentIterVals;
9993 BasicBlock *Header = L->getHeader();
9994 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9995
9996 BasicBlock *Latch = L->getLoopLatch();
9997 assert(Latch && "Should follow from NumIncomingValues == 2!");
9998
9999 for (PHINode &PHI : Header->phis()) {
10000 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10001 CurrentIterVals[&PHI] = StartCST;
10002 }
10003 if (!CurrentIterVals.count(PN))
10004 return getCouldNotCompute();
10005
10006 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10007 // the loop symbolically to determine when the condition gets a value of
10008 // "ExitWhen".
10009 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10010 const DataLayout &DL = getDataLayout();
10011 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10012 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10013 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10014
10015 // Couldn't symbolically evaluate.
10016 if (!CondVal) return getCouldNotCompute();
10017
10018 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10019 ++NumBruteForceTripCountsComputed;
10020 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10021 }
10022
10023 // Update all the PHI nodes for the next iteration.
10024 DenseMap<Instruction *, Constant *> NextIterVals;
10025
10026 // Create a list of which PHIs we need to compute. We want to do this before
10027 // calling EvaluateExpression on them because that may invalidate iterators
10028 // into CurrentIterVals.
10029 SmallVector<PHINode *, 8> PHIsToCompute;
10030 for (const auto &I : CurrentIterVals) {
10031 PHINode *PHI = dyn_cast<PHINode>(I.first);
10032 if (!PHI || PHI->getParent() != Header) continue;
10033 PHIsToCompute.push_back(PHI);
10034 }
10035 for (PHINode *PHI : PHIsToCompute) {
10036 Constant *&NextPHI = NextIterVals[PHI];
10037 if (NextPHI) continue; // Already computed!
10038
10039 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10040 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10041 }
10042 CurrentIterVals.swap(NextIterVals);
10043 }
10044
10045 // Too many iterations were needed to evaluate.
10046 return getCouldNotCompute();
10047}
10048
10050 auto &Values = ValuesAtScopes[V];
10051 // Check to see if we've folded this expression at this loop before.
10052 for (auto &LS : Values)
10053 if (LS.first == L)
10054 return LS.second ? LS.second : SCEVUse(V);
10055
10056 Values.emplace_back(L, nullptr);
10057
10058 // Otherwise compute it.
10059 SCEVUse C = computeSCEVAtScope(V, L);
10060 for (auto &LS : reverse(ValuesAtScopes[V]))
10061 if (LS.first == L) {
10062 LS.second = C;
10063 // Record the dependency under the bare expression: invalidation walks
10064 // expressions, and any use flags on C do not change which expression
10065 // this is the value at scope of.
10066 if (!isa<SCEVConstant>(C))
10067 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10068 break;
10069 }
10070 return C;
10071}
10072
10074 const BasicBlock *ExitingBlock) {
10075 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10076 if (!isLoopInvariant(ExitValue, L)) {
10077 // If we failed to evaluate it in the outer scope, try to evaluate an
10078 // addrec for the specific exit.
10079 // TODO: Generalize this to other expressions.
10080 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10081 if (!isa<SCEVCouldNotCompute>(ExitCount))
10082 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10083 if (AddRec->getLoop() == L)
10084 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10085 }
10086 return ExitValue;
10087}
10088
10089/// This builds up a Constant using the ConstantExpr interface. That way, we
10090/// will return Constants for objects which aren't represented by a
10091/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10092/// Returns NULL if the SCEV isn't representable as a Constant.
10094 switch (V->getSCEVType()) {
10095 case scCouldNotCompute:
10096 case scAddRecExpr:
10097 case scVScale:
10098 return nullptr;
10099 case scConstant:
10100 return cast<SCEVConstant>(V)->getValue();
10101 case scUnknown:
10103 case scPtrToAddr: {
10105 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10106 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10107
10108 return nullptr;
10109 }
10110 case scTruncate: {
10112 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10113 return ConstantExpr::getTrunc(CastOp, ST->getType());
10114 return nullptr;
10115 }
10116 case scAddExpr: {
10117 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10118 Constant *C = nullptr;
10119 for (const SCEV *Op : SA->operands()) {
10121 if (!OpC)
10122 return nullptr;
10123 if (!C) {
10124 C = OpC;
10125 continue;
10126 }
10127 assert(!C->getType()->isPointerTy() &&
10128 "Can only have one pointer, and it must be last");
10129 if (OpC->getType()->isPointerTy()) {
10130 // The offsets have been converted to bytes. We can add bytes using
10131 // an i8 GEP.
10132 C = ConstantExpr::getPtrAdd(OpC, C);
10133 } else {
10134 C = ConstantExpr::getAdd(C, OpC);
10135 }
10136 }
10137 return C;
10138 }
10139 case scMulExpr:
10140 case scSignExtend:
10141 case scZeroExtend:
10142 case scUDivExpr:
10143 case scSMaxExpr:
10144 case scUMaxExpr:
10145 case scSMinExpr:
10146 case scUMinExpr:
10148 return nullptr;
10149 }
10150 llvm_unreachable("Unknown SCEV kind!");
10151}
10152
10153const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10154 SmallVectorImpl<SCEVUse> &NewOps) {
10155 switch (S->getSCEVType()) {
10156 case scTruncate:
10157 case scZeroExtend:
10158 case scSignExtend:
10159 case scPtrToAddr:
10160 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10161 case scAddRecExpr: {
10162 auto *AddRec = cast<SCEVAddRecExpr>(S);
10163 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10164 }
10165 case scAddExpr:
10166 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10167 case scMulExpr:
10168 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10169 case scUDivExpr:
10170 return getUDivExpr(NewOps[0], NewOps[1]);
10171 case scUMaxExpr:
10172 case scSMaxExpr:
10173 case scUMinExpr:
10174 case scSMinExpr:
10175 return getMinMaxExpr(S->getSCEVType(), NewOps);
10177 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10178 case scConstant:
10179 case scVScale:
10180 case scUnknown:
10181 return S;
10182 case scCouldNotCompute:
10183 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10184 }
10185 llvm_unreachable("Unknown SCEV kind!");
10186}
10187
10188SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10189 switch (V->getSCEVType()) {
10190 case scConstant:
10191 case scVScale:
10192 return V;
10193 case scAddRecExpr: {
10194 // If this is a loop recurrence for a loop that does not contain L, then we
10195 // are dealing with the final value computed by the loop.
10196 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10197 // First, attempt to evaluate each operand.
10198 // Avoid performing the look-up in the common case where the specified
10199 // expression has no loop-variant portions.
10200 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10201 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10202 if (OpAtScope == AddRec->getOperand(i))
10203 continue;
10204
10205 // Okay, at least one of these operands is loop variant but might be
10206 // foldable. Build a new instance of the folded commutative expression.
10208 NewOps.reserve(AddRec->getNumOperands());
10209 append_range(NewOps, AddRec->operands().take_front(i));
10210 NewOps.push_back(OpAtScope);
10211 for (++i; i != e; ++i)
10212 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10213
10214 const SCEV *FoldedRec = getAddRecExpr(
10215 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10216 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10217 // The addrec may be folded to a nonrecurrence, for example, if the
10218 // induction variable is multiplied by zero after constant folding. Go
10219 // ahead and return the folded value.
10220 if (!AddRec)
10221 return FoldedRec;
10222 break;
10223 }
10224
10225 // If the scope is outside the addrec's loop, evaluate it by using the
10226 // loop exit value of the addrec.
10227 if (!AddRec->getLoop()->contains(L)) {
10228 SCEVUse ExitValue = AddRec->getExitValue(*this);
10229 if (isa<SCEVCouldNotCompute>(ExitValue))
10230 return AddRec;
10231 return ExitValue;
10232 }
10233
10234 return AddRec;
10235 }
10236 case scTruncate:
10237 case scZeroExtend:
10238 case scSignExtend:
10239 case scPtrToAddr:
10240 case scAddExpr:
10241 case scMulExpr:
10242 case scUDivExpr:
10243 case scUMaxExpr:
10244 case scSMaxExpr:
10245 case scUMinExpr:
10246 case scSMinExpr:
10247 case scSequentialUMinExpr: {
10248 ArrayRef<SCEVUse> Ops = V->operands();
10249 // Avoid performing the look-up in the common case where the specified
10250 // expression has no loop-variant portions.
10251 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10252 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10253 if (OpAtScope != Ops[i].getPointer()) {
10254 // Okay, at least one of these operands is loop variant but might be
10255 // foldable. Build a new instance of the folded commutative expression.
10257 NewOps.reserve(Ops.size());
10258 append_range(NewOps, Ops.take_front(i));
10259 NewOps.push_back(OpAtScope);
10260
10261 for (++i; i != e; ++i) {
10262 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10263 NewOps.push_back(OpAtScope);
10264 }
10265
10266 return getWithOperands(V, NewOps);
10267 }
10268 }
10269 // If we got here, all operands are loop invariant.
10270 return V;
10271 }
10272 case scUnknown: {
10273 // If this instruction is evolved from a constant-evolving PHI, compute the
10274 // exit value from the loop without using SCEVs.
10275 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10277 if (!I)
10278 return V; // This is some other type of SCEVUnknown, just return it.
10279
10280 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10281 const Loop *CurrLoop = this->LI[I->getParent()];
10282 // Looking for loop exit value.
10283 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10284 PN->getParent() == CurrLoop->getHeader()) {
10285 // Okay, there is no closed form solution for the PHI node. Check
10286 // to see if the loop that contains it has a known backedge-taken
10287 // count. If so, we may be able to force computation of the exit
10288 // value.
10289 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10290 // This trivial case can show up in some degenerate cases where
10291 // the incoming IR has not yet been fully simplified.
10292 if (BackedgeTakenCount->isZero()) {
10293 Value *InitValue = nullptr;
10294 bool MultipleInitValues = false;
10295 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10296 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10297 if (!InitValue)
10298 InitValue = PN->getIncomingValue(i);
10299 else if (InitValue != PN->getIncomingValue(i)) {
10300 MultipleInitValues = true;
10301 break;
10302 }
10303 }
10304 }
10305 if (!MultipleInitValues && InitValue)
10306 return getSCEV(InitValue);
10307 }
10308 // Do we have a loop invariant value flowing around the backedge
10309 // for a loop which must execute the backedge?
10310 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10311 isKnownNonZero(BackedgeTakenCount) &&
10312 PN->getNumIncomingValues() == 2) {
10313
10314 unsigned InLoopPred =
10315 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10316 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10317 if (CurrLoop->isLoopInvariant(BackedgeVal))
10318 return getSCEV(BackedgeVal);
10319 }
10320 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10321 // Okay, we know how many times the containing loop executes. If
10322 // this is a constant evolving PHI node, get the final value at
10323 // the specified iteration number.
10324 Constant *RV =
10325 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10326 if (RV)
10327 return getSCEV(RV);
10328 }
10329 }
10330 }
10331
10332 // Okay, this is an expression that we cannot symbolically evaluate
10333 // into a SCEV. Check to see if it's possible to symbolically evaluate
10334 // the arguments into constants, and if so, try to constant propagate the
10335 // result. This is particularly useful for computing loop exit values.
10336 if (!canConstantFold(I, &TLI))
10337 return V; // This is some other type of SCEVUnknown, just return it.
10338
10339 SmallVector<Constant *, 4> Operands;
10340 Operands.reserve(I->getNumOperands());
10341 bool MadeImprovement = false;
10342 for (Value *Op : I->operands()) {
10343 if (Constant *C = dyn_cast<Constant>(Op)) {
10344 Operands.push_back(C);
10345 continue;
10346 }
10347
10348 // If any of the operands is non-constant and if they are
10349 // non-integer and non-pointer, don't even try to analyze them
10350 // with scev techniques.
10351 if (!isSCEVable(Op->getType()))
10352 return V;
10353
10354 const SCEV *OrigV = getSCEV(Op);
10355 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10356 MadeImprovement |= OrigV != OpV;
10357
10359 if (!C)
10360 return V;
10361 assert(C->getType() == Op->getType() && "Type mismatch");
10362 Operands.push_back(C);
10363 }
10364
10365 // Check to see if getSCEVAtScope actually made an improvement.
10366 if (!MadeImprovement)
10367 return V; // This is some other type of SCEVUnknown, just return it.
10368
10369 Constant *C = nullptr;
10370 const DataLayout &DL = getDataLayout();
10371 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10372 /*AllowNonDeterministic=*/false);
10373 if (!C)
10374 return V;
10375 return getSCEV(C);
10376 }
10377 case scCouldNotCompute:
10378 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10379 }
10380 llvm_unreachable("Unknown SCEV type!");
10381}
10382
10384 return getSCEVAtScope(getSCEV(V), L);
10385}
10386
10387const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10389 return stripInjectiveFunctions(ZExt->getOperand());
10391 return stripInjectiveFunctions(SExt->getOperand());
10392 return S;
10393}
10394
10395/// Finds the minimum unsigned root of the following equation:
10396///
10397/// A * X = B (mod N)
10398///
10399/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10400/// A and B isn't important.
10401///
10402/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10403static const SCEV *
10406 ScalarEvolution &SE, const Loop *L) {
10407 uint32_t BW = A.getBitWidth();
10408 assert(BW == SE.getTypeSizeInBits(B->getType()));
10409 assert(A != 0 && "A must be non-zero.");
10410
10411 // 1. D = gcd(A, N)
10412 //
10413 // The gcd of A and N may have only one prime factor: 2. The number of
10414 // trailing zeros in A is its multiplicity
10415 uint32_t Mult2 = A.countr_zero();
10416 // D = 2^Mult2
10417
10418 // 2. Check if B is divisible by D.
10419 //
10420 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10421 // is not less than multiplicity of this prime factor for D.
10422 unsigned MinTZ = SE.getMinTrailingZeros(B);
10423 // Try again with the terminator of the loop predecessor for context-specific
10424 // result, if MinTZ s too small.
10425 if (MinTZ < Mult2 && L->getLoopPredecessor())
10426 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10427 if (MinTZ < Mult2) {
10428 // Check if we can prove there's no remainder using URem.
10429 const SCEV *URem =
10430 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10431 const SCEV *Zero = SE.getZero(B->getType());
10432 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10433 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10434 if (!Predicates)
10435 return SE.getCouldNotCompute();
10436
10437 // Avoid adding a predicate that is known to be false.
10438 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10439 return SE.getCouldNotCompute();
10440 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10441 }
10442 }
10443
10444 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10445 // modulo (N / D).
10446 //
10447 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10448 // (N / D) in general. The inverse itself always fits into BW bits, though,
10449 // so we immediately truncate it.
10450 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10451 APInt I = AD.multiplicativeInverse().zext(BW);
10452
10453 // 4. Compute the minimum unsigned root of the equation:
10454 // I * (B / D) mod (N / D)
10455 // To simplify the computation, we factor out the divide by D:
10456 // (I * B mod N) / D
10457 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10458 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10459}
10460
10461/// For a given quadratic addrec, generate coefficients of the corresponding
10462/// quadratic equation, multiplied by a common value to ensure that they are
10463/// integers.
10464/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10465/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10466/// were multiplied by, and BitWidth is the bit width of the original addrec
10467/// coefficients.
10468/// This function returns std::nullopt if the addrec coefficients are not
10469/// compile- time constants.
10470static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10472 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10473 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10474 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10475 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10476 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10477 << *AddRec << '\n');
10478
10479 // We currently can only solve this if the coefficients are constants.
10480 if (!LC || !MC || !NC) {
10481 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10482 return std::nullopt;
10483 }
10484
10485 APInt L = LC->getAPInt();
10486 APInt M = MC->getAPInt();
10487 APInt N = NC->getAPInt();
10488 assert(!N.isZero() && "This is not a quadratic addrec");
10489
10490 unsigned BitWidth = LC->getAPInt().getBitWidth();
10491 unsigned NewWidth = BitWidth + 1;
10492 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10493 << BitWidth << '\n');
10494 // The sign-extension (as opposed to a zero-extension) here matches the
10495 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10496 N = N.sext(NewWidth);
10497 M = M.sext(NewWidth);
10498 L = L.sext(NewWidth);
10499
10500 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10501 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10502 // L+M, L+2M+N, L+3M+3N, ...
10503 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10504 //
10505 // The equation Acc = 0 is then
10506 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10507 // In a quadratic form it becomes:
10508 // N n^2 + (2M-N) n + 2L = 0.
10509
10510 APInt A = N;
10511 APInt B = 2 * M - A;
10512 APInt C = 2 * L;
10513 APInt T = APInt(NewWidth, 2);
10514 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10515 << "x + " << C << ", coeff bw: " << NewWidth
10516 << ", multiplied by " << T << '\n');
10517 return std::make_tuple(A, B, C, T, BitWidth);
10518}
10519
10520/// Helper function to compare optional APInts:
10521/// (a) if X and Y both exist, return min(X, Y),
10522/// (b) if neither X nor Y exist, return std::nullopt,
10523/// (c) if exactly one of X and Y exists, return that value.
10524static std::optional<APInt> MinOptional(std::optional<APInt> X,
10525 std::optional<APInt> Y) {
10526 if (X && Y) {
10527 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10528 APInt XW = X->sext(W);
10529 APInt YW = Y->sext(W);
10530 return XW.slt(YW) ? *X : *Y;
10531 }
10532 if (!X && !Y)
10533 return std::nullopt;
10534 return X ? *X : *Y;
10535}
10536
10537/// Helper function to truncate an optional APInt to a given BitWidth.
10538/// When solving addrec-related equations, it is preferable to return a value
10539/// that has the same bit width as the original addrec's coefficients. If the
10540/// solution fits in the original bit width, truncate it (except for i1).
10541/// Returning a value of a different bit width may inhibit some optimizations.
10542///
10543/// In general, a solution to a quadratic equation generated from an addrec
10544/// may require BW+1 bits, where BW is the bit width of the addrec's
10545/// coefficients. The reason is that the coefficients of the quadratic
10546/// equation are BW+1 bits wide (to avoid truncation when converting from
10547/// the addrec to the equation).
10548static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10549 unsigned BitWidth) {
10550 if (!X)
10551 return std::nullopt;
10552 unsigned W = X->getBitWidth();
10554 return X->trunc(BitWidth);
10555 return X;
10556}
10557
10558/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10559/// iterations. The values L, M, N are assumed to be signed, and they
10560/// should all have the same bit widths.
10561/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10562/// where BW is the bit width of the addrec's coefficients.
10563/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10564/// returned as such, otherwise the bit width of the returned value may
10565/// be greater than BW.
10566///
10567/// This function returns std::nullopt if
10568/// (a) the addrec coefficients are not constant, or
10569/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10570/// like x^2 = 5, no integer solutions exist, in other cases an integer
10571/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10572static std::optional<APInt>
10574 APInt A, B, C, M;
10575 unsigned BitWidth;
10576 auto T = GetQuadraticEquation(AddRec);
10577 if (!T)
10578 return std::nullopt;
10579
10580 std::tie(A, B, C, M, BitWidth) = *T;
10581 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10582 std::optional<APInt> X =
10584 if (!X)
10585 return std::nullopt;
10586
10587 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10588 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10589 if (!V->isZero())
10590 return std::nullopt;
10591
10592 return TruncIfPossible(X, BitWidth);
10593}
10594
10595/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10596/// iterations. The values M, N are assumed to be signed, and they
10597/// should all have the same bit widths.
10598/// Find the least n such that c(n) does not belong to the given range,
10599/// while c(n-1) does.
10600///
10601/// This function returns std::nullopt if
10602/// (a) the addrec coefficients are not constant, or
10603/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10604/// bounds of the range.
10605static std::optional<APInt>
10607 const ConstantRange &Range, ScalarEvolution &SE) {
10608 assert(AddRec->getOperand(0)->isZero() &&
10609 "Starting value of addrec should be 0");
10610 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10611 << Range << ", addrec " << *AddRec << '\n');
10612 // This case is handled in getNumIterationsInRange. Here we can assume that
10613 // we start in the range.
10614 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10615 "Addrec's initial value should be in range");
10616
10617 APInt A, B, C, M;
10618 unsigned BitWidth;
10619 auto T = GetQuadraticEquation(AddRec);
10620 if (!T)
10621 return std::nullopt;
10622
10623 // Be careful about the return value: there can be two reasons for not
10624 // returning an actual number. First, if no solutions to the equations
10625 // were found, and second, if the solutions don't leave the given range.
10626 // The first case means that the actual solution is "unknown", the second
10627 // means that it's known, but not valid. If the solution is unknown, we
10628 // cannot make any conclusions.
10629 // Return a pair: the optional solution and a flag indicating if the
10630 // solution was found.
10631 auto SolveForBoundary =
10632 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10633 // Solve for signed overflow and unsigned overflow, pick the lower
10634 // solution.
10635 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10636 << Bound << " (before multiplying by " << M << ")\n");
10637 Bound *= M; // The quadratic equation multiplier.
10638
10639 std::optional<APInt> SO;
10640 if (BitWidth > 1) {
10641 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10642 "signed overflow\n");
10644 }
10645 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10646 "unsigned overflow\n");
10647 std::optional<APInt> UO =
10649
10650 auto LeavesRange = [&] (const APInt &X) {
10651 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10652 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10653 if (Range.contains(V0->getValue()))
10654 return false;
10655 // X should be at least 1, so X-1 is non-negative.
10656 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10658 if (Range.contains(V1->getValue()))
10659 return true;
10660 return false;
10661 };
10662
10663 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10664 // can be a solution, but the function failed to find it. We cannot treat it
10665 // as "no solution".
10666 if (!SO || !UO)
10667 return {std::nullopt, false};
10668
10669 // Check the smaller value first to see if it leaves the range.
10670 // At this point, both SO and UO must have values.
10671 std::optional<APInt> Min = MinOptional(SO, UO);
10672 if (LeavesRange(*Min))
10673 return { Min, true };
10674 std::optional<APInt> Max = Min == SO ? UO : SO;
10675 if (LeavesRange(*Max))
10676 return { Max, true };
10677
10678 // Solutions were found, but were eliminated, hence the "true".
10679 return {std::nullopt, true};
10680 };
10681
10682 std::tie(A, B, C, M, BitWidth) = *T;
10683 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10684 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10685 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10686 auto SL = SolveForBoundary(Lower);
10687 auto SU = SolveForBoundary(Upper);
10688 // If any of the solutions was unknown, no meaninigful conclusions can
10689 // be made.
10690 if (!SL.second || !SU.second)
10691 return std::nullopt;
10692
10693 // Claim: The correct solution is not some value between Min and Max.
10694 //
10695 // Justification: Assuming that Min and Max are different values, one of
10696 // them is when the first signed overflow happens, the other is when the
10697 // first unsigned overflow happens. Crossing the range boundary is only
10698 // possible via an overflow (treating 0 as a special case of it, modeling
10699 // an overflow as crossing k*2^W for some k).
10700 //
10701 // The interesting case here is when Min was eliminated as an invalid
10702 // solution, but Max was not. The argument is that if there was another
10703 // overflow between Min and Max, it would also have been eliminated if
10704 // it was considered.
10705 //
10706 // For a given boundary, it is possible to have two overflows of the same
10707 // type (signed/unsigned) without having the other type in between: this
10708 // can happen when the vertex of the parabola is between the iterations
10709 // corresponding to the overflows. This is only possible when the two
10710 // overflows cross k*2^W for the same k. In such case, if the second one
10711 // left the range (and was the first one to do so), the first overflow
10712 // would have to enter the range, which would mean that either we had left
10713 // the range before or that we started outside of it. Both of these cases
10714 // are contradictions.
10715 //
10716 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10717 // solution is not some value between the Max for this boundary and the
10718 // Min of the other boundary.
10719 //
10720 // Justification: Assume that we had such Max_A and Min_B corresponding
10721 // to range boundaries A and B and such that Max_A < Min_B. If there was
10722 // a solution between Max_A and Min_B, it would have to be caused by an
10723 // overflow corresponding to either A or B. It cannot correspond to B,
10724 // since Min_B is the first occurrence of such an overflow. If it
10725 // corresponded to A, it would have to be either a signed or an unsigned
10726 // overflow that is larger than both eliminated overflows for A. But
10727 // between the eliminated overflows and this overflow, the values would
10728 // cover the entire value space, thus crossing the other boundary, which
10729 // is a contradiction.
10730
10731 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10732}
10733
10734ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10735 const Loop *L,
10736 bool ControlsOnlyExit,
10737 bool AllowPredicates) {
10738
10739 // This is only used for loops with a "x != y" exit test. The exit condition
10740 // is now expressed as a single expression, V = x-y. So the exit test is
10741 // effectively V != 0. We know and take advantage of the fact that this
10742 // expression only being used in a comparison by zero context.
10743
10745 // If the value is a constant
10746 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10747 // If the value is already zero, the branch will execute zero times.
10748 if (C->getValue()->isZero()) return C;
10749 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10750 }
10751
10752 const SCEVAddRecExpr *AddRec =
10753 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10754
10755 if (!AddRec && AllowPredicates)
10756 // Try to make this an AddRec using runtime tests, in the first X
10757 // iterations of this loop, where X is the SCEV expression found by the
10758 // algorithm below.
10759 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10760
10761 if (!AddRec || AddRec->getLoop() != L)
10762 return getCouldNotCompute();
10763
10764 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10765 // the quadratic equation to solve it.
10766 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10767 // We can only use this value if the chrec ends up with an exact zero
10768 // value at this index. When solving for "X*X != 5", for example, we
10769 // should not accept a root of 2.
10770 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10771 const auto *R = cast<SCEVConstant>(getConstant(*S));
10772 return ExitLimit(R, R, R, false, Predicates);
10773 }
10774 return getCouldNotCompute();
10775 }
10776
10777 // Otherwise we can only handle this if it is affine.
10778 if (!AddRec->isAffine())
10779 return getCouldNotCompute();
10780
10781 // If this is an affine expression, the execution count of this branch is
10782 // the minimum unsigned root of the following equation:
10783 //
10784 // Start + Step*N = 0 (mod 2^BW)
10785 //
10786 // equivalent to:
10787 //
10788 // Step*N = -Start (mod 2^BW)
10789 //
10790 // where BW is the common bit width of Start and Step.
10791
10792 // Get the initial value for the loop.
10793 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10794 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10795
10796 if (!isLoopInvariant(Step, L))
10797 return getCouldNotCompute();
10798
10799 LoopGuards Guards = LoopGuards::collect(L, *this);
10800 // Specialize step for this loop so we get context sensitive facts below.
10801 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10802
10803 // For positive steps (counting up until unsigned overflow):
10804 // N = -Start/Step (as unsigned)
10805 // For negative steps (counting down to zero):
10806 // N = Start/-Step
10807 // First compute the unsigned distance from zero in the direction of Step.
10808 bool CountDown = isKnownNegative(StepWLG);
10809 if (!CountDown && !isKnownNonNegative(StepWLG))
10810 return getCouldNotCompute();
10811
10812 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10813 // Handle unitary steps, which cannot wraparound.
10814 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10815 // N = Distance (as unsigned)
10816
10817 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10818 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10819 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10820
10821 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10822 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10823 // case, and see if we can improve the bound.
10824 //
10825 // Explicitly handling this here is necessary because getUnsignedRange
10826 // isn't context-sensitive; it doesn't know that we only care about the
10827 // range inside the loop.
10828 const SCEV *Zero = getZero(Distance->getType());
10829 const SCEV *One = getOne(Distance->getType());
10830 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10831 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10832 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10833 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10834 // Distance + 1; the range of Distance itself may be a wrapped set even
10835 // when the guards bound Distance + 1 tightly.
10836 APInt Max = APIntOps::umin(
10837 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10838 getUnsignedRangeMax(DistancePlusOne));
10839 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10840 }
10841 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10842 Predicates);
10843 }
10844
10845 // If the condition controls loop exit (the loop exits only if the expression
10846 // is true) and the addition is no-wrap we can use unsigned divide to
10847 // compute the backedge count. In this case, the step may not divide the
10848 // distance, but we don't care because if the condition is "missed" the loop
10849 // will have undefined behavior due to wrapping.
10850 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10851 loopHasNoAbnormalExits(AddRec->getLoop())) {
10852
10853 // If the stride is zero and the start is non-zero, the loop must be
10854 // infinite. In C++, most loops are finite by assumption, in which case the
10855 // step being zero implies UB must execute if the loop is entered.
10856 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10857 !isKnownNonZero(StepWLG))
10858 return getCouldNotCompute();
10859
10860 const SCEV *Exact =
10861 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10862 const SCEV *ConstantMax = getCouldNotCompute();
10863 if (Exact != getCouldNotCompute()) {
10864 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10865 ConstantMax =
10867 }
10868 const SCEV *SymbolicMax =
10869 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10870 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10871 }
10872
10873 // Solve the general equation.
10874 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10875 if (!StepC || StepC->getValue()->isZero())
10876 return getCouldNotCompute();
10877 const SCEV *E = SolveLinEquationWithOverflow(
10878 StepC->getAPInt(), getNegativeSCEV(Start),
10879 AllowPredicates ? &Predicates : nullptr, *this, L);
10880
10881 const SCEV *M = E;
10882 if (E != getCouldNotCompute()) {
10883 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10884 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10885 }
10886 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10887 return ExitLimit(E, M, S, false, Predicates);
10888}
10889
10890ScalarEvolution::ExitLimit
10891ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10892 // Loops that look like: while (X == 0) are very strange indeed. We don't
10893 // handle them yet except for the trivial case. This could be expanded in the
10894 // future as needed.
10895
10896 // If the value is a constant, check to see if it is known to be non-zero
10897 // already. If so, the backedge will execute zero times.
10898 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10899 if (!C->getValue()->isZero())
10900 return getZero(C->getType());
10901 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10902 }
10903
10904 // We could implement others, but I really doubt anyone writes loops like
10905 // this, and if they did, they would already be constant folded.
10906 return getCouldNotCompute();
10907}
10908
10909std::pair<const BasicBlock *, const BasicBlock *>
10910ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10911 const {
10912 // If the block has a unique predecessor, then there is no path from the
10913 // predecessor to the block that does not go through the direct edge
10914 // from the predecessor to the block.
10915 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10916 return {Pred, BB};
10917
10918 // A loop's header is defined to be a block that dominates the loop.
10919 // If the header has a unique predecessor outside the loop, it must be
10920 // a block that has exactly one successor that can reach the loop.
10921 if (const Loop *L = LI.getLoopFor(BB))
10922 return {L->getLoopPredecessor(), L->getHeader()};
10923
10924 return {nullptr, BB};
10925}
10926
10927/// SCEV structural equivalence is usually sufficient for testing whether two
10928/// expressions are equal, however for the purposes of looking for a condition
10929/// guarding a loop, it can be useful to be a little more general, since a
10930/// front-end may have replicated the controlling expression.
10931static bool HasSameValue(const SCEV *A, const SCEV *B) {
10932 // Quick check to see if they are the same SCEV.
10933 if (A == B) return true;
10934
10935 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10936 // Not all instructions that are "identical" compute the same value. For
10937 // instance, two distinct alloca instructions allocating the same type are
10938 // identical and do not read memory; but compute distinct values.
10939 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10940 };
10941
10942 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10943 // two different instructions with the same value. Check for this case.
10944 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10945 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10946 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10947 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10948 if (ComputesEqualValues(AI, BI))
10949 return true;
10950
10951 // Otherwise assume they may have a different value.
10952 return false;
10953}
10954
10955static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10956 const SCEV *Op0, *Op1;
10957 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10958 return false;
10959 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10960 LHS = Op1;
10961 return true;
10962 }
10963 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10964 LHS = Op0;
10965 return true;
10966 }
10967 return false;
10968}
10969
10971 SCEVUse &RHS, unsigned Depth) {
10972 bool Changed = false;
10973 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10974 // '0 != 0'.
10975 auto TrivialCase = [&](bool TriviallyTrue) {
10977 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10978 return true;
10979 };
10980 // If we hit the max recursion limit bail out.
10981 if (Depth >= 3)
10982 return false;
10983
10984 const SCEV *NewLHS, *NewRHS;
10985 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10986 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10987 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10988 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10989
10990 // (X * vscale) pred (Y * vscale) ==> X pred Y
10991 // when both multiples are NSW.
10992 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10993 // when both multiples are NUW.
10994 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10995 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10996 !ICmpInst::isSigned(Pred))) {
10997 LHS = NewLHS;
10998 RHS = NewRHS;
10999 Changed = true;
11000 }
11001 }
11002
11003 // Canonicalize a constant to the right side.
11004 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11005 // Check for both operands constant.
11006 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11007 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11008 return TrivialCase(false);
11009 return TrivialCase(true);
11010 }
11011 // Otherwise swap the operands to put the constant on the right.
11012 std::swap(LHS, RHS);
11014 Changed = true;
11015 }
11016
11017 // (K + A) pred (K + B) --> A pred B
11018 // For equality, no flags are needed.
11019 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11020 {
11021 const SCEVConstant *C = nullptr;
11022 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11023 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11024 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11025 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11026 if (ICmpInst::isEquality(Pred) ||
11027 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11028 RAdd->hasNoSignedWrap()) ||
11029 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11030 RAdd->hasNoUnsignedWrap())) {
11031 LHS = NewLHS;
11032 RHS = NewRHS;
11033 Changed = true;
11034 }
11035 }
11036 }
11037
11038 // (C * A) pred (C * B) --> A pred B
11039 // For equality predicates, both muls must be NUW or both must be NSW
11040 // (either suffices to make multiplication by C injective; C == 0 is
11041 // impossible because SCEV folds 0 * X to 0).
11042 // For signed ordering, C must be positive and both muls must be NSW.
11043 // For unsigned ordering, both muls must be NUW.
11044 {
11045 const SCEVConstant *C = nullptr;
11046 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11047 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11048 const auto *LMul = cast<SCEVMulExpr>(LHS);
11049 const auto *RMul = cast<SCEVMulExpr>(RHS);
11050 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11051 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11052 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11053 (ICmpInst::isSigned(Pred) && BothNSW &&
11054 C->getAPInt().isStrictlyPositive()) ||
11055 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11056 LHS = NewLHS;
11057 RHS = NewRHS;
11058 Changed = true;
11059 }
11060 }
11061 }
11062
11063 // If we're comparing an addrec with a value which is loop-invariant in the
11064 // addrec's loop, put the addrec on the left. Also make a dominance check,
11065 // as both operands could be addrecs loop-invariant in each other's loop.
11066 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11067 const Loop *L = AR->getLoop();
11068 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11069 std::swap(LHS, RHS);
11071 Changed = true;
11072 }
11073 }
11074
11075 // If there's a constant operand, canonicalize comparisons with boundary
11076 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11077 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11078 const APInt &RA = RC->getAPInt();
11079
11080 bool SimplifiedByConstantRange = false;
11081
11082 if (!ICmpInst::isEquality(Pred)) {
11084 if (ExactCR.isFullSet())
11085 return TrivialCase(true);
11086 if (ExactCR.isEmptySet())
11087 return TrivialCase(false);
11088
11089 APInt NewRHS;
11090 CmpInst::Predicate NewPred;
11091 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11092 ICmpInst::isEquality(NewPred)) {
11093 // We were able to convert an inequality to an equality.
11094 Pred = NewPred;
11095 RHS = getConstant(NewRHS);
11096 Changed = SimplifiedByConstantRange = true;
11097 }
11098 }
11099
11100 if (!SimplifiedByConstantRange) {
11101 switch (Pred) {
11102 default:
11103 break;
11104 case ICmpInst::ICMP_EQ:
11105 case ICmpInst::ICMP_NE:
11106 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11107 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11108 Changed = true;
11109 break;
11110
11111 // The "Should have been caught earlier!" messages refer to the fact
11112 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11113 // should have fired on the corresponding cases, and canonicalized the
11114 // check to trivial case.
11115
11116 case ICmpInst::ICMP_UGE:
11117 assert(!RA.isMinValue() && "Should have been caught earlier!");
11118 Pred = ICmpInst::ICMP_UGT;
11119 RHS = getConstant(RA - 1);
11120 Changed = true;
11121 break;
11122 case ICmpInst::ICMP_ULE:
11123 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11124 Pred = ICmpInst::ICMP_ULT;
11125 RHS = getConstant(RA + 1);
11126 Changed = true;
11127 break;
11128 case ICmpInst::ICMP_SGE:
11129 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11130 Pred = ICmpInst::ICMP_SGT;
11131 RHS = getConstant(RA - 1);
11132 Changed = true;
11133 break;
11134 case ICmpInst::ICMP_SLE:
11135 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11136 Pred = ICmpInst::ICMP_SLT;
11137 RHS = getConstant(RA + 1);
11138 Changed = true;
11139 break;
11140 }
11141 }
11142 }
11143
11144 // a /u b == 0 => a < b
11145 // a /u b != 0 => a >= b
11146 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11147 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11149 Changed = true;
11150 }
11151
11152 // Check for obvious equality.
11153 if (HasSameValue(LHS, RHS)) {
11154 if (ICmpInst::isTrueWhenEqual(Pred))
11155 return TrivialCase(true);
11157 return TrivialCase(false);
11158 }
11159
11160 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11161 // adding or subtracting 1 from one of the operands.
11162 switch (Pred) {
11163 case ICmpInst::ICMP_SLE:
11164 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11165 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11167 Pred = ICmpInst::ICMP_SLT;
11168 Changed = true;
11169 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11170 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11172 Pred = ICmpInst::ICMP_SLT;
11173 Changed = true;
11174 }
11175 break;
11176 case ICmpInst::ICMP_SGE:
11177 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11178 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11180 Pred = ICmpInst::ICMP_SGT;
11181 Changed = true;
11182 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11183 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11185 Pred = ICmpInst::ICMP_SGT;
11186 Changed = true;
11187 }
11188 break;
11189 case ICmpInst::ICMP_ULE:
11190 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11191 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11193 Pred = ICmpInst::ICMP_ULT;
11194 Changed = true;
11195 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11196 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11197 Pred = ICmpInst::ICMP_ULT;
11198 Changed = true;
11199 }
11200 break;
11201 case ICmpInst::ICMP_UGE:
11202 // If RHS is an op we can fold the -1, try that first.
11203 // Otherwise prefer LHS to preserve the nuw flag.
11204 if ((isa<SCEVConstant>(RHS) ||
11206 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11207 !getUnsignedRangeMin(RHS).isMinValue()) {
11208 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11209 Pred = ICmpInst::ICMP_UGT;
11210 Changed = true;
11211 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11212 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11214 Pred = ICmpInst::ICMP_UGT;
11215 Changed = true;
11216 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11217 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11218 Pred = ICmpInst::ICMP_UGT;
11219 Changed = true;
11220 }
11221 break;
11222 default:
11223 break;
11224 }
11225
11226 // TODO: More simplifications are possible here.
11227
11228 // Recursively simplify until we either hit a recursion limit or nothing
11229 // changes.
11230 if (Changed)
11231 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11232
11233 return Changed;
11234}
11235
11237 return getSignedRangeMax(S).isNegative();
11238}
11239
11243
11245 return !getSignedRangeMin(S).isNegative();
11246}
11247
11251
11253 // Query push down for cases where the unsigned range is
11254 // less than sufficient.
11255 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11256 return isKnownNonZero(SExt->getOperand(0));
11257 return getUnsignedRangeMin(S) != 0;
11258}
11259
11261 bool OrNegative) {
11262 auto NonRecursive = [OrNegative](const SCEV *S) {
11263 if (auto *C = dyn_cast<SCEVConstant>(S))
11264 return C->getAPInt().isPowerOf2() ||
11265 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11266
11267 // vscale is a power-of-two.
11268 return isa<SCEVVScale>(S);
11269 };
11270
11271 if (NonRecursive(S))
11272 return true;
11273
11274 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11275 if (!Mul)
11276 return false;
11277 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11278}
11279
11281 const SCEV *S, uint64_t M,
11283 if (M == 0)
11284 return false;
11285 if (M == 1)
11286 return true;
11287
11288 // For a constant, check that "S % M == 0".
11289 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11290 APInt C = Cst->getAPInt();
11291 return C.urem(M) == 0;
11292 }
11293
11294 // Basic tests have failed.
11295 // Check "S % M == 0" at compile time and record runtime Assumptions.
11296 auto *STy = dyn_cast<IntegerType>(S->getType());
11297 const SCEV *SmodM =
11298 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11299 const SCEV *Zero = getZero(STy);
11300
11301 // Check whether "S % M == 0" is known at compile time.
11302 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11303 return true;
11304
11305 // Check whether "S % M != 0" is known at compile time.
11306 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11307 return false;
11308
11309 if (!Predicates)
11310 return false;
11311
11312 // Look through Add and AddRec expressions with nuw to improve the
11313 // precision of added predicates. S is a multiple of M if S starts with a
11314 // multiple of M and at every iteration step S only adds multiples of M.
11317 all_of(S->operands(),
11318 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11319 return true;
11320
11321 // Similarly, look through Mul with nuw, where any operand being a
11322 // known-multiple is sufficient.
11323 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11324 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11325 return isKnownMultipleOf(Op, M, Predicates);
11326 }))
11327 return true;
11328
11329 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11330 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11331 return isKnownMultipleOf(Op, M, Predicates);
11332 }))
11333 return true;
11334
11336
11337 // Detect redundant predicates.
11338 for (auto *A : *Predicates)
11339 if (A->implies(P, *this))
11340 return true;
11341
11342 // Only record non-redundant predicates.
11343 Predicates->push_back(P);
11344 return true;
11345}
11346
11348 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11350}
11351
11352std::pair<const SCEV *, const SCEV *>
11354 // Compute SCEV on entry of loop L.
11355 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11356 if (Start == getCouldNotCompute())
11357 return { Start, Start };
11358 // Compute post increment SCEV for loop L.
11359 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11360 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11361 return { Start, PostInc };
11362}
11363
11365 SCEVUse RHS) {
11366 // First collect all loops.
11368 getUsedLoops(LHS, LoopsUsed);
11369 getUsedLoops(RHS, LoopsUsed);
11370
11371 if (LoopsUsed.empty())
11372 return false;
11373
11374 // Domination relationship must be a linear order on collected loops.
11375#ifndef NDEBUG
11376 for (const auto *L1 : LoopsUsed)
11377 for (const auto *L2 : LoopsUsed)
11378 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11379 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11380 "Domination relationship is not a linear order");
11381#endif
11382
11383 const Loop *MDL =
11384 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11385 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11386 });
11387
11388 // Get init and post increment value for LHS.
11389 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11390 // if LHS contains unknown non-invariant SCEV then bail out.
11391 if (SplitLHS.first == getCouldNotCompute())
11392 return false;
11393 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11394 // Get init and post increment value for RHS.
11395 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11396 // if RHS contains unknown non-invariant SCEV then bail out.
11397 if (SplitRHS.first == getCouldNotCompute())
11398 return false;
11399 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11400 // It is possible that init SCEV contains an invariant load but it does
11401 // not dominate MDL and is not available at MDL loop entry, so we should
11402 // check it here.
11403 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11404 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11405 return false;
11406
11407 // It seems backedge guard check is faster than entry one so in some cases
11408 // it can speed up whole estimation by short circuit
11409 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11410 SplitRHS.second) &&
11411 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11412}
11413
11415 SCEVUse RHS) {
11416 // Canonicalize the inputs first.
11417 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11418
11419 return isKnownViaInduction(Pred, LHS, RHS) ||
11420 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11421 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11422}
11423
11425 const SCEV *LHS,
11426 const SCEV *RHS) {
11427 if (isKnownPredicate(Pred, LHS, RHS))
11428 return true;
11430 return false;
11431 return std::nullopt;
11432}
11433
11435 const SCEV *RHS,
11436 const Instruction *CtxI) {
11437 // TODO: Analyze guards and assumes from Context's block.
11438 return isKnownPredicate(Pred, LHS, RHS) ||
11439 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11440}
11441
11442std::optional<bool>
11444 const SCEV *RHS, const Instruction *CtxI) {
11445 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11446 if (KnownWithoutContext)
11447 return KnownWithoutContext;
11448
11449 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11450 return true;
11452 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11453 return false;
11454 return std::nullopt;
11455}
11456
11458 const SCEVAddRecExpr *LHS,
11459 const SCEV *RHS) {
11460 const Loop *L = LHS->getLoop();
11461 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11462 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11463}
11464
11465std::optional<ScalarEvolution::MonotonicPredicateType>
11467 ICmpInst::Predicate Pred) {
11468 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11469
11470#ifndef NDEBUG
11471 // Verify an invariant: inverting the predicate should turn a monotonically
11472 // increasing change to a monotonically decreasing one, and vice versa.
11473 if (Result) {
11474 auto ResultSwapped =
11475 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11476
11477 assert(*ResultSwapped != *Result &&
11478 "monotonicity should flip as we flip the predicate");
11479 }
11480#endif
11481
11482 return Result;
11483}
11484
11485std::optional<ScalarEvolution::MonotonicPredicateType>
11486ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11487 ICmpInst::Predicate Pred) {
11488 // A zero step value for LHS means the induction variable is essentially a
11489 // loop invariant value. We don't really depend on the predicate actually
11490 // flipping from false to true (for increasing predicates, and the other way
11491 // around for decreasing predicates), all we care about is that *if* the
11492 // predicate changes then it only changes from false to true.
11493 //
11494 // A zero step value in itself is not very useful, but there may be places
11495 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11496 // as general as possible.
11497
11498 // Only handle LE/LT/GE/GT predicates.
11499 if (!ICmpInst::isRelational(Pred))
11500 return std::nullopt;
11501
11502 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11503 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11504 "Should be greater or less!");
11505
11506 // Check that AR does not wrap.
11507 if (ICmpInst::isUnsigned(Pred)) {
11508 if (!LHS->hasNoUnsignedWrap())
11509 return std::nullopt;
11511 }
11512 assert(ICmpInst::isSigned(Pred) &&
11513 "Relational predicate is either signed or unsigned!");
11514 if (!LHS->hasNoSignedWrap())
11515 return std::nullopt;
11516
11517 const SCEV *Step = LHS->getStepRecurrence(*this);
11518
11519 if (isKnownNonNegative(Step))
11521
11522 if (isKnownNonPositive(Step))
11524
11525 return std::nullopt;
11526}
11527
11528std::optional<ScalarEvolution::LoopInvariantPredicate>
11530 const SCEV *RHS, const Loop *L,
11531 const Instruction *CtxI) {
11532 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11533 if (!isLoopInvariant(RHS, L)) {
11534 if (!isLoopInvariant(LHS, L))
11535 return std::nullopt;
11536
11537 std::swap(LHS, RHS);
11539 }
11540
11541 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11542 if (!ArLHS || ArLHS->getLoop() != L)
11543 return std::nullopt;
11544
11545 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11546 if (!MonotonicType)
11547 return std::nullopt;
11548 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11549 // true as the loop iterates, and the backedge is control dependent on
11550 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11551 //
11552 // * if the predicate was false in the first iteration then the predicate
11553 // is never evaluated again, since the loop exits without taking the
11554 // backedge.
11555 // * if the predicate was true in the first iteration then it will
11556 // continue to be true for all future iterations since it is
11557 // monotonically increasing.
11558 //
11559 // For both the above possibilities, we can replace the loop varying
11560 // predicate with its value on the first iteration of the loop (which is
11561 // loop invariant).
11562 //
11563 // A similar reasoning applies for a monotonically decreasing predicate, by
11564 // replacing true with false and false with true in the above two bullets.
11566 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11567
11568 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11570 RHS);
11571
11572 if (!CtxI)
11573 return std::nullopt;
11574 // Try to prove via context.
11575 // TODO: Support other cases.
11576 switch (Pred) {
11577 default:
11578 break;
11579 case ICmpInst::ICMP_ULE:
11580 case ICmpInst::ICMP_ULT: {
11581 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11582 // Given preconditions
11583 // (1) ArLHS does not cross the border of positive and negative parts of
11584 // range because of:
11585 // - Positive step; (TODO: lift this limitation)
11586 // - nuw - does not cross zero boundary;
11587 // - nsw - does not cross SINT_MAX boundary;
11588 // (2) ArLHS <s RHS
11589 // (3) RHS >=s 0
11590 // we can replace the loop variant ArLHS <u RHS condition with loop
11591 // invariant Start(ArLHS) <u RHS.
11592 //
11593 // Because of (1) there are two options:
11594 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11595 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11596 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11597 // Because of (2) ArLHS <u RHS is trivially true.
11598 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11599 // We can strengthen this to Start(ArLHS) <u RHS.
11600 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11601 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11602 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11603 isKnownNonNegative(RHS) &&
11604 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11606 RHS);
11607 }
11608 }
11609
11610 return std::nullopt;
11611}
11612
11613std::optional<ScalarEvolution::LoopInvariantPredicate>
11615 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11616 const Instruction *CtxI, const SCEV *MaxIter) {
11618 Pred, LHS, RHS, L, CtxI, MaxIter))
11619 return LIP;
11620 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11621 // Number of iterations expressed as UMIN isn't always great for expressing
11622 // the value on the last iteration. If the straightforward approach didn't
11623 // work, try the following trick: if the a predicate is invariant for X, it
11624 // is also invariant for umin(X, ...). So try to find something that works
11625 // among subexpressions of MaxIter expressed as umin.
11626 for (SCEVUse Op : UMin->operands())
11628 Pred, LHS, RHS, L, CtxI, Op))
11629 return LIP;
11630 return std::nullopt;
11631}
11632
11633std::optional<ScalarEvolution::LoopInvariantPredicate>
11635 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11636 const Instruction *CtxI, const SCEV *MaxIter) {
11637 // Try to prove the following set of facts:
11638 // - The predicate is monotonic in the iteration space.
11639 // - If the check does not fail on the 1st iteration:
11640 // - No overflow will happen during first MaxIter iterations;
11641 // - It will not fail on the MaxIter'th iteration.
11642 // If the check does fail on the 1st iteration, we leave the loop and no
11643 // other checks matter.
11644
11645 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11646 if (!isLoopInvariant(RHS, L)) {
11647 if (!isLoopInvariant(LHS, L))
11648 return std::nullopt;
11649
11650 std::swap(LHS, RHS);
11652 }
11653
11654 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11655 if (!AR || AR->getLoop() != L)
11656 return std::nullopt;
11657
11658 // Even if both are valid, we need to consistently chose the unsigned or the
11659 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11660 // predicate.
11661 Pred = Pred.dropSameSign();
11662
11663 // The predicate must be relational (i.e. <, <=, >=, >).
11664 if (!ICmpInst::isRelational(Pred))
11665 return std::nullopt;
11666
11667 // TODO: Support steps other than +/- 1.
11668 const SCEV *Step = AR->getStepRecurrence(*this);
11669 auto *One = getOne(Step->getType());
11670 auto *MinusOne = getNegativeSCEV(One);
11671 if (Step != One && Step != MinusOne)
11672 return std::nullopt;
11673
11674 // Type mismatch here means that MaxIter is potentially larger than max
11675 // unsigned value in start type, which mean we cannot prove no wrap for the
11676 // indvar.
11677 if (AR->getType() != MaxIter->getType())
11678 return std::nullopt;
11679
11680 // Value of IV on suggested last iteration.
11681 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11682 // Does it still meet the requirement?
11683 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11684 return std::nullopt;
11685 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11686 // not exceed max unsigned value of this type), this effectively proves
11687 // that there is no wrap during the iteration. To prove that there is no
11688 // signed/unsigned wrap, we need to check that
11689 // Start <= Last for step = 1 or Start >= Last for step = -1.
11690 ICmpInst::Predicate NoOverflowPred =
11692 if (Step == MinusOne)
11693 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11694 const SCEV *Start = AR->getStart();
11695 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11696 return std::nullopt;
11697
11698 // Everything is fine.
11699 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11700}
11701
11702bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11703 SCEVUse LHS,
11704 SCEVUse RHS) {
11705 if (HasSameValue(LHS, RHS))
11706 return ICmpInst::isTrueWhenEqual(Pred);
11707
11708 auto CheckRange = [&](bool IsSigned) {
11709 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11710 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11711 return RangeLHS.icmp(Pred, RangeRHS);
11712 };
11713
11714 // The check at the top of the function catches the case where the values are
11715 // known to be equal.
11716 if (Pred == CmpInst::ICMP_EQ)
11717 return false;
11718
11719 if (Pred == CmpInst::ICMP_NE) {
11720 if (CheckRange(true) || CheckRange(false))
11721 return true;
11722 auto *Diff = getMinusSCEV(LHS, RHS);
11723 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11724 }
11725
11726 return CheckRange(CmpInst::isSigned(Pred));
11727}
11728
11729bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11731 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11732 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11733 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11734 // OutC1 and OutC2.
11735 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11736 APInt &OutC2, SCEVFlags ExpectedFlags) {
11737 SCEVUse XNonConstOp, XConstOp;
11738 SCEVUse YNonConstOp, YConstOp;
11739 SCEVFlags XFlagsPresent;
11740 SCEVFlags YFlagsPresent;
11741
11742 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11743 XConstOp = getZero(X->getType());
11744 XNonConstOp = X;
11745 XFlagsPresent = ExpectedFlags;
11746 }
11747 if (!isa<SCEVConstant>(XConstOp))
11748 return false;
11749
11750 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11751 YConstOp = getZero(Y->getType());
11752 YNonConstOp = Y;
11753 YFlagsPresent = ExpectedFlags;
11754 }
11755
11756 if (YNonConstOp != XNonConstOp)
11757 return false;
11758
11759 if (!isa<SCEVConstant>(YConstOp))
11760 return false;
11761
11762 // When matching ADDs with NUW flags (and unsigned predicates), only the
11763 // second ADD (with the larger constant) requires NUW.
11764 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11765 return false;
11766 if (ExpectedFlags != SCEV::FlagNUW &&
11767 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11768 return false;
11769 }
11770
11771 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11772 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11773
11774 return true;
11775 };
11776
11777 APInt C1;
11778 APInt C2;
11779
11780 switch (Pred) {
11781 default:
11782 break;
11783
11784 case ICmpInst::ICMP_SGE:
11785 std::swap(LHS, RHS);
11786 [[fallthrough]];
11787 case ICmpInst::ICMP_SLE:
11788 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11789 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11790 return true;
11791
11792 break;
11793
11794 case ICmpInst::ICMP_SGT:
11795 std::swap(LHS, RHS);
11796 [[fallthrough]];
11797 case ICmpInst::ICMP_SLT:
11798 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11799 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11800 return true;
11801
11802 break;
11803
11804 case ICmpInst::ICMP_UGE:
11805 std::swap(LHS, RHS);
11806 [[fallthrough]];
11807 case ICmpInst::ICMP_ULE:
11808 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11809 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11810 return true;
11811
11812 break;
11813
11814 case ICmpInst::ICMP_UGT:
11815 std::swap(LHS, RHS);
11816 [[fallthrough]];
11817 case ICmpInst::ICMP_ULT:
11818 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11819 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11820 return true;
11821 break;
11822 }
11823
11824 return false;
11825}
11826
11827bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11829 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11830 return false;
11831
11832 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11833 // the stack can result in exponential time complexity.
11834 SaveAndRestore Restore(ProvingSplitPredicate, true);
11835
11836 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11837 //
11838 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11839 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11840 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11841 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11842 // use isKnownPredicate later if needed.
11843 return isKnownNonNegative(RHS) &&
11846}
11847
11848bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11849 const SCEV *LHS, const SCEV *RHS) {
11850 // No need to even try if we know the module has no guards.
11851 if (!HasGuards)
11852 return false;
11853
11854 return any_of(*BB, [&](const Instruction &I) {
11855 using namespace llvm::PatternMatch;
11856
11857 Value *Condition;
11859 m_Value(Condition))) &&
11860 isImpliedCond(Pred, LHS, RHS, Condition, false);
11861 });
11862}
11863
11864/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11865/// protected by a conditional between LHS and RHS. This is used to
11866/// to eliminate casts.
11868 CmpPredicate Pred,
11869 const SCEV *LHS,
11870 const SCEV *RHS) {
11871 // Interpret a null as meaning no loop, where there is obviously no guard
11872 // (interprocedural conditions notwithstanding). Do not bother about
11873 // unreachable loops.
11874 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11875 return true;
11876
11877 if (VerifyIR)
11878 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11879 "This cannot be done on broken IR!");
11880
11881
11882 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11883 return true;
11884
11885 BasicBlock *Latch = L->getLoopLatch();
11886 if (!Latch)
11887 return false;
11888
11889 CondBrInst *LoopContinuePredicate =
11891 if (LoopContinuePredicate &&
11892 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11893 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11894 return true;
11895
11896 // We don't want more than one activation of the following loops on the stack
11897 // -- that can lead to O(n!) time complexity.
11898 if (WalkingBEDominatingConds)
11899 return false;
11900
11901 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11902
11903 // See if we can exploit a trip count to prove the predicate.
11904 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11905 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11906 if (LatchBECount != getCouldNotCompute()) {
11907 // We know that Latch branches back to the loop header exactly
11908 // LatchBECount times. This means the backdege condition at Latch is
11909 // equivalent to "{0,+,1} u< LatchBECount".
11910 Type *Ty = LatchBECount->getType();
11911 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11912 const SCEV *LoopCounter =
11913 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11914 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11915 LatchBECount))
11916 return true;
11917 }
11918
11919 // Check conditions due to any @llvm.assume intrinsics.
11920 for (auto &AssumeVH : AC.assumptions()) {
11921 if (!AssumeVH)
11922 continue;
11923 auto *CI = cast<CallInst>(AssumeVH);
11924 if (!DT.dominates(CI, Latch->getTerminator()))
11925 continue;
11926
11927 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11928 return true;
11929 }
11930
11931 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11932 return true;
11933
11934 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11935 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11936 assert(DTN && "should reach the loop header before reaching the root!");
11937
11938 BasicBlock *BB = DTN->getBlock();
11939 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11940 return true;
11941
11942 BasicBlock *PBB = BB->getSinglePredecessor();
11943 if (!PBB)
11944 continue;
11945
11947 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11948 continue;
11949
11950 // If we have an edge `E` within the loop body that dominates the only
11951 // latch, the condition guarding `E` also guards the backedge. This
11952 // reasoning works only for loops with a single latch.
11953 // We're constructively (and conservatively) enumerating edges within the
11954 // loop body that dominate the latch. The dominator tree better agree
11955 // with us on this:
11956 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11957 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11958 BB != ContBr->getSuccessor(0)))
11959 return true;
11960 }
11961
11962 return false;
11963}
11964
11966 CmpPredicate Pred,
11967 const SCEV *LHS,
11968 const SCEV *RHS) {
11969 // Do not bother proving facts for unreachable code.
11970 if (!DT.isReachableFromEntry(BB))
11971 return true;
11972 if (VerifyIR)
11973 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11974 "This cannot be done on broken IR!");
11975
11976 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11977 // the facts (a >= b && a != b) separately. A typical situation is when the
11978 // non-strict comparison is known from ranges and non-equality is known from
11979 // dominating predicates. If we are proving strict comparison, we always try
11980 // to prove non-equality and non-strict comparison separately.
11981 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11982 const bool ProvingStrictComparison =
11983 Pred != NonStrictPredicate.dropSameSign();
11984 bool ProvedNonStrictComparison = false;
11985 bool ProvedNonEquality = false;
11986
11987 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11988 if (!ProvedNonStrictComparison)
11989 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11990 if (!ProvedNonEquality)
11991 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11992 if (ProvedNonStrictComparison && ProvedNonEquality)
11993 return true;
11994 return false;
11995 };
11996
11997 if (ProvingStrictComparison) {
11998 auto ProofFn = [&](CmpPredicate P) {
11999 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12000 };
12001 if (SplitAndProve(ProofFn))
12002 return true;
12003 }
12004
12005 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12006 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12007 const Instruction *CtxI = &BB->front();
12008 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12009 return true;
12010 if (ProvingStrictComparison) {
12011 auto ProofFn = [&](CmpPredicate P) {
12012 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12013 };
12014 if (SplitAndProve(ProofFn))
12015 return true;
12016 }
12017 return false;
12018 };
12019
12020 // Starting at the block's predecessor, climb up the predecessor chain, as long
12021 // as there are predecessors that can be found that have unique successors
12022 // leading to the original block.
12023 const Loop *ContainingLoop = LI.getLoopFor(BB);
12024 const BasicBlock *PredBB;
12025 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12026 PredBB = ContainingLoop->getLoopPredecessor();
12027 else
12028 PredBB = BB->getSinglePredecessor();
12029 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12030 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12031 const CondBrInst *BlockEntryPredicate =
12032 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12033 if (!BlockEntryPredicate)
12034 continue;
12035
12036 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12037 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12038 return true;
12039 }
12040
12041 // Check conditions due to any @llvm.assume intrinsics.
12042 for (auto &AssumeVH : AC.assumptions()) {
12043 if (!AssumeVH)
12044 continue;
12045 auto *CI = cast<CallInst>(AssumeVH);
12046 if (!DT.dominates(CI, BB))
12047 continue;
12048
12049 if (ProveViaCond(CI->getArgOperand(0), false))
12050 return true;
12051 }
12052
12053 // Check conditions due to any @llvm.experimental.guard intrinsics.
12054 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12055 F.getParent(), Intrinsic::experimental_guard);
12056 if (GuardDecl)
12057 for (const auto *GU : GuardDecl->users())
12058 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12059 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12060 if (ProveViaCond(Guard->getArgOperand(0), false))
12061 return true;
12062 return false;
12063}
12064
12066 const SCEV *LHS,
12067 const SCEV *RHS) {
12068 // Interpret a null as meaning no loop, where there is obviously no guard
12069 // (interprocedural conditions notwithstanding).
12070 if (!L)
12071 return false;
12072
12073 // Both LHS and RHS must be available at loop entry.
12075 "LHS is not available at Loop Entry");
12077 "RHS is not available at Loop Entry");
12078
12079 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12080 return true;
12081
12082 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12083}
12084
12085bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12086 const SCEV *RHS,
12087 const Value *FoundCondValue, bool Inverse,
12088 const Instruction *CtxI) {
12089 // False conditions implies anything. Do not bother analyzing it further.
12090 if (FoundCondValue ==
12091 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12092 return true;
12093
12094 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12095 return false;
12096
12097 llvm::scope_exit ClearOnExit(
12098 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12099
12100 // Recursively handle And and Or conditions.
12101 const Value *Op0, *Op1;
12102 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12103 if (!Inverse)
12104 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12105 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12106 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12107 if (Inverse)
12108 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12109 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12110 }
12111
12112 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12113 if (!ICI) return false;
12114
12115 // Now that we found a conditional branch that dominates the loop or controls
12116 // the loop latch. Check to see if it is the comparison we are looking for.
12117 CmpPredicate FoundPred;
12118 if (Inverse)
12119 FoundPred = ICI->getInverseCmpPredicate();
12120 else
12121 FoundPred = ICI->getCmpPredicate();
12122
12123 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12124 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12125
12126 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12127}
12128
12129bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12130 const SCEV *RHS, CmpPredicate FoundPred,
12131 const SCEV *FoundLHS, const SCEV *FoundRHS,
12132 const Instruction *CtxI) {
12133 // Balance the types.
12134 if (getTypeSizeInBits(LHS->getType()) <
12135 getTypeSizeInBits(FoundLHS->getType())) {
12136 // For unsigned and equality predicates, try to prove that both found
12137 // operands fit into narrow unsigned range. If so, try to prove facts in
12138 // narrow types.
12139 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12140 !FoundRHS->getType()->isPointerTy()) {
12141 auto *NarrowType = LHS->getType();
12142 auto *WideType = FoundLHS->getType();
12143 auto BitWidth = getTypeSizeInBits(NarrowType);
12144 const SCEV *MaxValue = getZeroExtendExpr(
12146 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12147 MaxValue) &&
12148 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12149 MaxValue)) {
12150 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12151 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12152 // We cannot preserve samesign after truncation.
12153 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12154 TruncFoundLHS, TruncFoundRHS, CtxI))
12155 return true;
12156 }
12157 }
12158
12159 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12160 return false;
12161 if (CmpInst::isSigned(Pred)) {
12162 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12163 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12164 } else {
12165 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12166 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12167 }
12168 } else if (getTypeSizeInBits(LHS->getType()) >
12169 getTypeSizeInBits(FoundLHS->getType())) {
12170 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12171 return false;
12172 if (CmpInst::isSigned(FoundPred)) {
12173 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12174 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12175 } else {
12176 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12177 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12178 }
12179 }
12180 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12181 FoundRHS, CtxI);
12182}
12183
12184bool ScalarEvolution::isImpliedCondBalancedTypes(
12185 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12186 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12188 getTypeSizeInBits(FoundLHS->getType()) &&
12189 "Types should be balanced!");
12190 // Canonicalize the query to match the way instcombine will have
12191 // canonicalized the comparison.
12192 if (SimplifyICmpOperands(Pred, LHS, RHS))
12193 if (LHS == RHS)
12194 return CmpInst::isTrueWhenEqual(Pred);
12195 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12196 if (FoundLHS == FoundRHS)
12197 return CmpInst::isFalseWhenEqual(FoundPred);
12198
12199 // Check to see if we can make the LHS or RHS match.
12200 if (LHS == FoundRHS || RHS == FoundLHS) {
12201 if (isa<SCEVConstant>(RHS)) {
12202 std::swap(FoundLHS, FoundRHS);
12203 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12204 } else {
12205 std::swap(LHS, RHS);
12207 }
12208 }
12209
12210 // Check whether the found predicate is the same as the desired predicate.
12211 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12212 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12213
12214 // Check whether swapping the found predicate makes it the same as the
12215 // desired predicate.
12216 if (auto P = CmpPredicate::getMatching(
12217 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12218 // We can write the implication
12219 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12220 // using one of the following ways:
12221 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12222 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12223 // Both require swapping the operands of one condition. Don't do this if it
12224 // would break canonical constant/addrec ordering.
12226 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12227 LHS, FoundLHS, FoundRHS, CtxI);
12228 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12229 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12230
12231 return false;
12232 }
12233
12234 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12236 assert(P1 != P2 && "Handled earlier!");
12237 return CmpInst::isRelational(P2) &&
12239 };
12240 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12241 // Unsigned comparison is the same as signed comparison when both the
12242 // operands are non-negative or negative.
12243 if (haveSameSign(FoundLHS, FoundRHS))
12244 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12245 // Create local copies that we can freely swap and canonicalize our
12246 // conditions to "le/lt".
12247 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12248 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12249 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12250 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12251 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12252 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12253 std::swap(CanonicalLHS, CanonicalRHS);
12254 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12255 }
12256 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12257 "Must be!");
12258 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12259 ICmpInst::isLE(CanonicalFoundPred)) &&
12260 "Must be!");
12261 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12262 // Use implication:
12263 // x <u y && y >=s 0 --> x <s y.
12264 // If we can prove the left part, the right part is also proven.
12265 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12266 CanonicalRHS, CanonicalFoundLHS,
12267 CanonicalFoundRHS);
12268 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12269 // Use implication:
12270 // x <s y && y <s 0 --> x <u y.
12271 // If we can prove the left part, the right part is also proven.
12272 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12273 CanonicalRHS, CanonicalFoundLHS,
12274 CanonicalFoundRHS);
12275 }
12276
12277 // Check if we can make progress by sharpening ranges.
12278 if (FoundPred == ICmpInst::ICMP_NE &&
12279 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12280
12281 const SCEVConstant *C = nullptr;
12282 const SCEV *V = nullptr;
12283
12284 if (isa<SCEVConstant>(FoundLHS)) {
12285 C = cast<SCEVConstant>(FoundLHS);
12286 V = FoundRHS;
12287 } else {
12288 C = cast<SCEVConstant>(FoundRHS);
12289 V = FoundLHS;
12290 }
12291
12292 // The guarding predicate tells us that C != V. If the known range
12293 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12294 // range we consider has to correspond to same signedness as the
12295 // predicate we're interested in folding.
12296
12297 APInt Min = ICmpInst::isSigned(Pred) ?
12299
12300 if (Min == C->getAPInt()) {
12301 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12302 // This is true even if (Min + 1) wraps around -- in case of
12303 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12304
12305 APInt SharperMin = Min + 1;
12306
12307 switch (Pred) {
12308 case ICmpInst::ICMP_SGE:
12309 case ICmpInst::ICMP_UGE:
12310 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12311 // RHS, we're done.
12312 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12313 CtxI))
12314 return true;
12315 [[fallthrough]];
12316
12317 case ICmpInst::ICMP_SGT:
12318 case ICmpInst::ICMP_UGT:
12319 // We know from the range information that (V `Pred` Min ||
12320 // V == Min). We know from the guarding condition that !(V
12321 // == Min). This gives us
12322 //
12323 // V `Pred` Min || V == Min && !(V == Min)
12324 // => V `Pred` Min
12325 //
12326 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12327
12328 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12329 return true;
12330 break;
12331
12332 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12333 case ICmpInst::ICMP_SLE:
12334 case ICmpInst::ICMP_ULE:
12335 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12336 LHS, V, getConstant(SharperMin), CtxI))
12337 return true;
12338 [[fallthrough]];
12339
12340 case ICmpInst::ICMP_SLT:
12341 case ICmpInst::ICMP_ULT:
12342 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12343 LHS, V, getConstant(Min), CtxI))
12344 return true;
12345 break;
12346
12347 default:
12348 // No change
12349 break;
12350 }
12351 }
12352 }
12353
12354 // Check whether the actual condition is beyond sufficient.
12355 if (FoundPred == ICmpInst::ICMP_EQ)
12356 if (ICmpInst::isTrueWhenEqual(Pred))
12357 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12358 return true;
12359 if (Pred == ICmpInst::ICMP_NE)
12360 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12361 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12362 return true;
12363
12364 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12365 return true;
12366
12367 // Otherwise assume the worst.
12368 return false;
12369}
12370
12371bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12372 SCEVFlags &Flags) {
12373 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12374 return false;
12375
12376 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12377 return true;
12378}
12379
12380std::optional<APInt>
12382 // We avoid subtracting expressions here because this function is usually
12383 // fairly deep in the call stack (i.e. is called many times).
12384
12385 unsigned BW = getTypeSizeInBits(More->getType());
12386 APInt Diff(BW, 0);
12387 APInt DiffMul(BW, 1);
12388 // Try various simplifications to reduce the difference to a constant. Limit
12389 // the number of allowed simplifications to keep compile-time low.
12390 for (unsigned I = 0; I < 8; ++I) {
12391 if (More == Less)
12392 return Diff;
12393
12394 // Reduce addrecs with identical steps to their start value.
12396 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12397 const auto *MAR = cast<SCEVAddRecExpr>(More);
12398
12399 if (LAR->getLoop() != MAR->getLoop())
12400 return std::nullopt;
12401
12402 // We look at affine expressions only; not for correctness but to keep
12403 // getStepRecurrence cheap.
12404 if (!LAR->isAffine() || !MAR->isAffine())
12405 return std::nullopt;
12406
12407 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12408 return std::nullopt;
12409
12410 Less = LAR->getStart();
12411 More = MAR->getStart();
12412 continue;
12413 }
12414
12415 // Try to match a common constant multiply.
12416 auto MatchConstMul =
12417 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12418 const APInt *C;
12419 const SCEV *Op;
12420 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12421 return {{Op, *C}};
12422 return std::nullopt;
12423 };
12424 if (auto MatchedMore = MatchConstMul(More)) {
12425 if (auto MatchedLess = MatchConstMul(Less)) {
12426 if (MatchedMore->second == MatchedLess->second) {
12427 More = MatchedMore->first;
12428 Less = MatchedLess->first;
12429 DiffMul *= MatchedMore->second;
12430 continue;
12431 }
12432 }
12433 }
12434
12435 // Try to cancel out common factors in two add expressions.
12437 auto Add = [&](const SCEV *S, int Mul) {
12438 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12439 if (Mul == 1) {
12440 Diff += C->getAPInt() * DiffMul;
12441 } else {
12442 assert(Mul == -1);
12443 Diff -= C->getAPInt() * DiffMul;
12444 }
12445 } else
12446 Multiplicity[S] += Mul;
12447 };
12448 auto Decompose = [&](const SCEV *S, int Mul) {
12449 if (isa<SCEVAddExpr>(S)) {
12450 for (const SCEV *Op : S->operands())
12451 Add(Op, Mul);
12452 } else
12453 Add(S, Mul);
12454 };
12455 Decompose(More, 1);
12456 Decompose(Less, -1);
12457
12458 // Check whether all the non-constants cancel out, or reduce to new
12459 // More/Less values.
12460 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12461 for (const auto &[S, Mul] : Multiplicity) {
12462 if (Mul == 0)
12463 continue;
12464 if (Mul == 1) {
12465 if (NewMore)
12466 return std::nullopt;
12467 NewMore = S;
12468 } else if (Mul == -1) {
12469 if (NewLess)
12470 return std::nullopt;
12471 NewLess = S;
12472 } else
12473 return std::nullopt;
12474 }
12475
12476 // Values stayed the same, no point in trying further.
12477 if (NewMore == More || NewLess == Less)
12478 return std::nullopt;
12479
12480 More = NewMore;
12481 Less = NewLess;
12482
12483 // Reduced to constant.
12484 if (!More && !Less)
12485 return Diff;
12486
12487 // Left with variable on only one side, bail out.
12488 if (!More || !Less)
12489 return std::nullopt;
12490 }
12491
12492 // Did not reduce to constant.
12493 return std::nullopt;
12494}
12495
12496bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12497 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12498 const SCEV *FoundRHS, const Instruction *CtxI) {
12499 // Try to recognize the following pattern:
12500 //
12501 // FoundRHS = ...
12502 // ...
12503 // loop:
12504 // FoundLHS = {Start,+,W}
12505 // context_bb: // Basic block from the same loop
12506 // known(Pred, FoundLHS, FoundRHS)
12507 //
12508 // If some predicate is known in the context of a loop, it is also known on
12509 // each iteration of this loop, including the first iteration. Therefore, in
12510 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12511 // prove the original pred using this fact.
12512 if (!CtxI)
12513 return false;
12514 const BasicBlock *ContextBB = CtxI->getParent();
12515 // Make sure AR varies in the context block.
12516 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12517 const Loop *L = AR->getLoop();
12518 const auto *Latch = L->getLoopLatch();
12519 // Make sure that context belongs to the loop and executes on 1st iteration
12520 // (if it ever executes at all).
12521 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12522 return false;
12523 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12524 return false;
12525 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12526 }
12527
12528 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12529 const Loop *L = AR->getLoop();
12530 const auto *Latch = L->getLoopLatch();
12531 // Make sure that context belongs to the loop and executes on 1st iteration
12532 // (if it ever executes at all).
12533 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12534 return false;
12535 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12536 return false;
12537 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12538 }
12539
12540 return false;
12541}
12542
12543bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12544 const SCEV *LHS,
12545 const SCEV *RHS,
12546 const SCEV *FoundLHS,
12547 const SCEV *FoundRHS) {
12548 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12549 return false;
12550
12551 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12552 if (!AddRecLHS)
12553 return false;
12554
12555 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12556 if (!AddRecFoundLHS)
12557 return false;
12558
12559 // We'd like to let SCEV reason about control dependencies, so we constrain
12560 // both the inequalities to be about add recurrences on the same loop. This
12561 // way we can use isLoopEntryGuardedByCond later.
12562
12563 const Loop *L = AddRecFoundLHS->getLoop();
12564 if (L != AddRecLHS->getLoop())
12565 return false;
12566
12567 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12568 //
12569 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12570 // ... (2)
12571 //
12572 // Informal proof for (2), assuming (1) [*]:
12573 //
12574 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12575 //
12576 // Then
12577 //
12578 // FoundLHS s< FoundRHS s< INT_MIN - C
12579 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12580 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12581 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12582 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12583 // <=> FoundLHS + C s< FoundRHS + C
12584 //
12585 // [*]: (1) can be proved by ruling out overflow.
12586 //
12587 // [**]: This can be proved by analyzing all the four possibilities:
12588 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12589 // (A s>= 0, B s>= 0).
12590 //
12591 // Note:
12592 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12593 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12594 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12595 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12596 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12597 // C)".
12598
12599 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12600 if (!LDiff)
12601 return false;
12602 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12603 if (!RDiff || *LDiff != *RDiff)
12604 return false;
12605
12606 if (LDiff->isMinValue())
12607 return true;
12608
12609 APInt FoundRHSLimit;
12610
12611 if (Pred == CmpInst::ICMP_ULT) {
12612 FoundRHSLimit = -(*RDiff);
12613 } else {
12614 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12615 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12616 }
12617
12618 // Try to prove (1) or (2), as needed.
12619 return isAvailableAtLoopEntry(FoundRHS, L) &&
12620 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12621 getConstant(FoundRHSLimit));
12622}
12623
12624bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12625 const SCEV *RHS, const SCEV *FoundLHS,
12626 const SCEV *FoundRHS, unsigned Depth) {
12627 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12628
12629 llvm::scope_exit ClearOnExit([&]() {
12630 if (LPhi) {
12631 bool Erased = PendingMerges.erase(LPhi);
12632 assert(Erased && "Failed to erase LPhi!");
12633 (void)Erased;
12634 }
12635 if (RPhi) {
12636 bool Erased = PendingMerges.erase(RPhi);
12637 assert(Erased && "Failed to erase RPhi!");
12638 (void)Erased;
12639 }
12640 });
12641
12642 // Find respective Phis and check that they are not being pending.
12643 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12644 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12645 if (!PendingMerges.insert(Phi).second)
12646 return false;
12647 LPhi = Phi;
12648 }
12649 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12650 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12651 // If we detect a loop of Phi nodes being processed by this method, for
12652 // example:
12653 //
12654 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12655 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12656 //
12657 // we don't want to deal with a case that complex, so return conservative
12658 // answer false.
12659 if (!PendingMerges.insert(Phi).second)
12660 return false;
12661 RPhi = Phi;
12662 }
12663
12664 // If none of LHS, RHS is a Phi, nothing to do here.
12665 if (!LPhi && !RPhi)
12666 return false;
12667
12668 // If there is a SCEVUnknown Phi we are interested in, make it left.
12669 if (!LPhi) {
12670 std::swap(LHS, RHS);
12671 std::swap(FoundLHS, FoundRHS);
12672 std::swap(LPhi, RPhi);
12674 }
12675
12676 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12677 const BasicBlock *LBB = LPhi->getParent();
12678 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12679
12680 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12681 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12682 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12683 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12684 };
12685
12686 if (RPhi && RPhi->getParent() == LBB) {
12687 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12688 // If we compare two Phis from the same block, and for each entry block
12689 // the predicate is true for incoming values from this block, then the
12690 // predicate is also true for the Phis.
12691 for (const BasicBlock *IncBB : predecessors(LBB)) {
12692 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12693 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12694 if (!ProvedEasily(L, R))
12695 return false;
12696 }
12697 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12698 // Case two: RHS is also a Phi from the same basic block, and it is an
12699 // AddRec. It means that there is a loop which has both AddRec and Unknown
12700 // PHIs, for it we can compare incoming values of AddRec from above the loop
12701 // and latch with their respective incoming values of LPhi.
12702 // TODO: Generalize to handle loops with many inputs in a header.
12703 if (LPhi->getNumIncomingValues() != 2) return false;
12704
12705 auto *RLoop = RAR->getLoop();
12706 auto *Predecessor = RLoop->getLoopPredecessor();
12707 assert(Predecessor && "Loop with AddRec with no predecessor?");
12708 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12709 if (!ProvedEasily(L1, RAR->getStart()))
12710 return false;
12711 auto *Latch = RLoop->getLoopLatch();
12712 assert(Latch && "Loop with AddRec with no latch?");
12713 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12714 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12715 return false;
12716 } else {
12717 // In all other cases go over inputs of LHS and compare each of them to RHS,
12718 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12719 // At this point RHS is either a non-Phi, or it is a Phi from some block
12720 // different from LBB.
12721 for (const BasicBlock *IncBB : predecessors(LBB)) {
12722 // Check that RHS is available in this block.
12723 if (!dominates(RHS, IncBB))
12724 return false;
12725 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12726 // Make sure L does not refer to a value from a potentially previous
12727 // iteration of a loop.
12728 if (!properlyDominates(L, LBB))
12729 return false;
12730 // Addrecs are considered to properly dominate their loop, so are missed
12731 // by the previous check. Discard any values that have computable
12732 // evolution in this loop.
12733 if (auto *Loop = LI.getLoopFor(LBB))
12735 return false;
12736 if (!ProvedEasily(L, RHS))
12737 return false;
12738 }
12739 }
12740 return true;
12741}
12742
12743bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12744 const SCEV *LHS,
12745 const SCEV *RHS,
12746 const SCEV *FoundLHS,
12747 const SCEV *FoundRHS) {
12748 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12749 // sure that we are dealing with same LHS.
12750 if (RHS == FoundRHS) {
12751 std::swap(LHS, RHS);
12752 std::swap(FoundLHS, FoundRHS);
12754 }
12755 if (LHS != FoundLHS)
12756 return false;
12757
12758 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12759 if (!SUFoundRHS)
12760 return false;
12761
12762 Value *Shiftee, *ShiftValue;
12763
12764 using namespace PatternMatch;
12765 if (match(SUFoundRHS->getValue(),
12766 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12767 auto *ShifteeS = getSCEV(Shiftee);
12768 // Prove one of the following:
12769 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12770 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12771 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12772 // ---> LHS <s RHS
12773 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12774 // ---> LHS <=s RHS
12775 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12776 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12777 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12778 if (isKnownNonNegative(ShifteeS))
12779 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12780 }
12781
12782 return false;
12783}
12784
12785bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12786 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12787 const SCEV *FoundRHS) {
12788 // Only valid for equality predicates: (A == B) implies (C == D) when
12789 // the SCEV difference A - B equals C - D (they check the same
12790 // underlying relationship at every iteration).
12791 if (!ICmpInst::isEquality(Pred))
12792 return false;
12793
12794 // Restrict to cases involving loop recurrences - that's where this
12795 // pattern arises (correlated IV comparisons). This avoids calling
12796 // getMinusSCEV on arbitrary non-loop expressions.
12798 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12799 return false;
12800
12801 // AddRecs from different loops can never produce matching differences.
12802 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12803 if (!QueryAddRec)
12804 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12805 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12806 if (!FoundAddRec)
12807 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12808 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12809 return false;
12810
12811 // If the strides differ, the differences can never match.
12812 if (QueryAddRec->getStepRecurrence(*this) !=
12813 FoundAddRec->getStepRecurrence(*this))
12814 return false;
12815
12816 // Compute differences. For pointer-typed operands sharing the same base,
12817 // getMinusSCEV strips the common base and returns an integer SCEV.
12818 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12819 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12820 if (isa<SCEVCouldNotCompute>(FoundDiff))
12821 return false;
12822
12823 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12824 if (isa<SCEVCouldNotCompute>(Diff))
12825 return false;
12826
12827 return Diff == FoundDiff;
12828}
12829
12830bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12831 const SCEV *RHS,
12832 const SCEV *FoundLHS,
12833 const SCEV *FoundRHS,
12834 const Instruction *CtxI) {
12835 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12836 FoundRHS) ||
12837 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12838 FoundRHS) ||
12839 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12840 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12841 CtxI) ||
12842 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12843 FoundRHS) ||
12844 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12845}
12846
12847/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12848template <typename MinMaxExprType>
12849static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12850 const SCEV *Candidate) {
12851 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12852 if (!MinMaxExpr)
12853 return false;
12854
12855 return is_contained(MinMaxExpr->operands(), Candidate);
12856}
12857
12859 CmpPredicate Pred, const SCEV *LHS,
12860 const SCEV *RHS) {
12861 // If both sides are affine addrecs for the same loop, with equal
12862 // steps, and we know the recurrences don't wrap, then we only
12863 // need to check the predicate on the starting values.
12864
12865 if (!ICmpInst::isRelational(Pred))
12866 return false;
12867
12868 const SCEV *LStart, *RStart, *Step;
12869 const Loop *L;
12870 if (!match(LHS,
12871 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12873 m_SpecificLoop(L))))
12874 return false;
12878 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12879 return false;
12880
12881 return SE.isKnownPredicate(Pred, LStart, RStart);
12882}
12883
12884/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12885/// go below its own start value?
12887 CmpPredicate Pred,
12888 const SCEV *LHS,
12889 const SCEV *RHS) {
12890 // Normalize to (AddRec Pred Start).
12893 std::swap(LHS, RHS);
12894 }
12895
12896 // The recurrence is equal to Start in the first iteration, so only the
12897 // non-strict predicate holds.
12898 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12899 return false;
12900
12901 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12902 if (!AR || AR->getStart() != RHS)
12903 return false;
12904
12905 return SE.getMonotonicPredicateType(AR, Pred) ==
12907}
12908
12909/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12910/// expression?
12912 const SCEV *LHS, const SCEV *RHS) {
12913 switch (Pred) {
12914 default:
12915 return false;
12916
12917 case ICmpInst::ICMP_SGE:
12918 std::swap(LHS, RHS);
12919 [[fallthrough]];
12920 case ICmpInst::ICMP_SLE:
12921 return
12922 // min(A, ...) <= A
12924 // A <= max(A, ...)
12926
12927 case ICmpInst::ICMP_UGE:
12928 std::swap(LHS, RHS);
12929 [[fallthrough]];
12930 case ICmpInst::ICMP_ULE:
12931 return
12932 // min(A, ...) <= A
12933 // FIXME: what about umin_seq?
12935 // A <= max(A, ...)
12937
12938 case ICmpInst::ICMP_UGT:
12939 std::swap(LHS, RHS);
12940 [[fallthrough]];
12941 case ICmpInst::ICMP_ULT:
12942 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12943 // umin(Ops) u< RHS.
12944 //
12945 // Use computeConstantDifference instead of the more powerful
12946 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12947 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12948 // the full predicate prover would be expensive.
12949 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12950 for (SCEVUse Op : Min->operands()) {
12951 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12952 // When Op and RHS share a common base differing by a
12953 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12954 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12955 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12956 return true;
12957 }
12958 }
12959 return false;
12960 }
12961
12962 llvm_unreachable("covered switch fell through?!");
12963}
12964
12965bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12966 const SCEV *RHS,
12967 const SCEV *FoundLHS,
12968 const SCEV *FoundRHS,
12969 unsigned Depth) {
12972 "LHS and RHS have different sizes?");
12973 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12974 getTypeSizeInBits(FoundRHS->getType()) &&
12975 "FoundLHS and FoundRHS have different sizes?");
12976 // We want to avoid hurting the compile time with analysis of too big trees.
12978 return false;
12979
12980 // We only want to work with GT comparison so far.
12981 if (ICmpInst::isLT(Pred)) {
12983 std::swap(LHS, RHS);
12984 std::swap(FoundLHS, FoundRHS);
12985 }
12986
12988
12989 // For unsigned, try to reduce it to corresponding signed comparison.
12990 if (P == ICmpInst::ICMP_UGT)
12991 // We can replace unsigned predicate with its signed counterpart if all
12992 // involved values are non-negative.
12993 // TODO: We could have better support for unsigned.
12994 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12995 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12996 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12997 // use this fact to prove that LHS and RHS are non-negative.
12998 const SCEV *MinusOne = getMinusOne(LHS->getType());
12999 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13000 FoundRHS) &&
13001 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13002 FoundRHS))
13004 }
13005
13006 if (P != ICmpInst::ICMP_SGT)
13007 return false;
13008
13009 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13010 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13011 return Ext->getOperand();
13012 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13013 // the constant in some cases.
13014 return S;
13015 };
13016
13017 // Acquire values from extensions.
13018 auto *OrigLHS = LHS;
13019 auto *OrigFoundLHS = FoundLHS;
13020 LHS = GetOpFromSExt(LHS);
13021 FoundLHS = GetOpFromSExt(FoundLHS);
13022
13023 // Is the SGT predicate can be proved trivially or using the found context.
13024 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13025 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13026 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13027 FoundRHS, Depth + 1);
13028 };
13029
13030 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13031 // We want to avoid creation of any new non-constant SCEV. Since we are
13032 // going to compare the operands to RHS, we should be certain that we don't
13033 // need any size extensions for this. So let's decline all cases when the
13034 // sizes of types of LHS and RHS do not match.
13035 // TODO: Maybe try to get RHS from sext to catch more cases?
13037 return false;
13038
13039 // Should not overflow.
13040 if (!LHSAddExpr->hasNoSignedWrap())
13041 return false;
13042
13043 SCEVUse LL = LHSAddExpr->getOperand(0);
13044 SCEVUse LR = LHSAddExpr->getOperand(1);
13045 auto *MinusOne = getMinusOne(RHS->getType());
13046
13047 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13048 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13049 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13050 };
13051 // Try to prove the following rule:
13052 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13053 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13054 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13055 return true;
13056 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13057 Value *LL, *LR;
13058 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13059
13060 using namespace llvm::PatternMatch;
13061
13062 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13063 // Rules for division.
13064 // We are going to perform some comparisons with Denominator and its
13065 // derivative expressions. In general case, creating a SCEV for it may
13066 // lead to a complex analysis of the entire graph, and in particular it
13067 // can request trip count recalculation for the same loop. This would
13068 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13069 // this, we only want to create SCEVs that are constants in this section.
13070 // So we bail if Denominator is not a constant.
13071 if (!isa<ConstantInt>(LR))
13072 return false;
13073
13074 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13075
13076 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13077 // then a SCEV for the numerator already exists and matches with FoundLHS.
13078 auto *Numerator = getExistingSCEV(LL);
13079 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13080 return false;
13081
13082 // Make sure that the numerator matches with FoundLHS and the denominator
13083 // is positive.
13084 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13085 return false;
13086
13087 auto *DTy = Denominator->getType();
13088 auto *FRHSTy = FoundRHS->getType();
13089 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13090 // One of types is a pointer and another one is not. We cannot extend
13091 // them properly to a wider type, so let us just reject this case.
13092 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13093 // to avoid this check.
13094 return false;
13095
13096 // Given that:
13097 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13098 auto *WTy = getWiderType(DTy, FRHSTy);
13099 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13100 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13101
13102 // Try to prove the following rule:
13103 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13104 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13105 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13106 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13107 if (isKnownNonPositive(RHS) &&
13108 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13109 return true;
13110
13111 // Try to prove the following rule:
13112 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13113 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13114 // If we divide it by Denominator > 2, then:
13115 // 1. If FoundLHS is negative, then the result is 0.
13116 // 2. If FoundLHS is non-negative, then the result is non-negative.
13117 // Anyways, the result is non-negative.
13118 auto *MinusOne = getMinusOne(WTy);
13119 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13120 if (isKnownNegative(RHS) &&
13121 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13122 return true;
13123 }
13124 }
13125
13126 // If our expression contained SCEVUnknown Phis, and we split it down and now
13127 // need to prove something for them, try to prove the predicate for every
13128 // possible incoming values of those Phis.
13129 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13130 return true;
13131
13132 return false;
13133}
13134
13136 const SCEV *RHS) {
13137 // zext x u<= sext x, sext x s<= zext x
13138 const SCEV *Op;
13139 switch (Pred) {
13140 case ICmpInst::ICMP_SGE:
13141 std::swap(LHS, RHS);
13142 [[fallthrough]];
13143 case ICmpInst::ICMP_SLE: {
13144 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13145 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13147 }
13148 case ICmpInst::ICMP_UGE:
13149 std::swap(LHS, RHS);
13150 [[fallthrough]];
13151 case ICmpInst::ICMP_ULE: {
13152 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13153 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13155 }
13156 default:
13157 return false;
13158 };
13159 llvm_unreachable("unhandled case");
13160}
13161
13162bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13163 SCEVUse LHS,
13164 SCEVUse RHS) {
13165 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13166 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13167 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13168 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13170 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13171}
13172
13173bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13174 const SCEV *LHS,
13175 const SCEV *RHS,
13176 const SCEV *FoundLHS,
13177 const SCEV *FoundRHS) {
13178 switch (Pred) {
13179 default:
13180 llvm_unreachable("Unexpected CmpPredicate value!");
13181 case ICmpInst::ICMP_EQ:
13182 case ICmpInst::ICMP_NE:
13183 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13184 return true;
13185 break;
13186 case ICmpInst::ICMP_SLT:
13187 case ICmpInst::ICMP_SLE:
13188 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13189 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13190 return true;
13191 break;
13192 case ICmpInst::ICMP_SGT:
13193 case ICmpInst::ICMP_SGE:
13194 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13195 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13196 return true;
13197 break;
13198 case ICmpInst::ICMP_ULT:
13199 case ICmpInst::ICMP_ULE:
13200 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13201 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13202 return true;
13203 break;
13204 case ICmpInst::ICMP_UGT:
13205 case ICmpInst::ICMP_UGE:
13206 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13207 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13208 return true;
13209 break;
13210 }
13211
13212 // Maybe it can be proved via operations?
13213 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13214 return true;
13215
13216 return false;
13217}
13218
13219bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13220 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13221 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13222 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13223 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13224 // reduce the compile time impact of this optimization.
13225 return false;
13226
13227 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13228 if (!Addend)
13229 return false;
13230
13231 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13232
13233 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13234 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13235 ConstantRange FoundLHSRange =
13236 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13237
13238 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13239 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13240
13241 // We can also compute the range of values for `LHS` that satisfy the
13242 // consequent, "`LHS` `Pred` `RHS`":
13243 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13244 // The antecedent implies the consequent if every value of `LHS` that
13245 // satisfies the antecedent also satisfies the consequent.
13246 return LHSRange.icmp(Pred, ConstRHS);
13247}
13248
13249bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13250 bool IsSigned, bool Invert) {
13251 assert(isKnownPositive(Stride) && "Positive stride expected!");
13252
13253 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13254 const SCEV *One = getOne(Stride->getType());
13255
13256 if (IsSigned) {
13257 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13258 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13259 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13260
13261 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13262 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13263 }
13264
13265 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13266 APInt MaxValue = APInt::getMaxValue(BitWidth);
13267 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13268
13269 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13270 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13271}
13272
13274 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13275 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13276 // expression fixes the case of N=0.
13277 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13278 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13279 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13280}
13281
13282const SCEV *
13283ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13284 const SCEV *End, unsigned BitWidth,
13285 bool IsSigned, bool Invert) {
13286 // The logic in this function assumes we can represent a positive stride.
13287 // If we can't, the backedge-taken count must be zero.
13288 if (IsSigned && BitWidth == 1)
13289 return getZero(Stride->getType());
13290
13291 // This code below only been closely audited for negative strides in the
13292 // unsigned comparison case, it may be correct for signed comparison, but
13293 // that needs to be established.
13294 if (IsSigned && isKnownNegative(Stride))
13295 return getCouldNotCompute();
13296
13297 // Calculate the maximum backedge count based on the range of values
13298 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13299 // need inverting. Stride was already negated by the caller.
13300 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13301
13302 APInt MinStride =
13303 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13304
13305 // We assume either the stride is positive, or the backedge-taken count
13306 // is zero. So force StrideForMaxBECount to be at least one.
13307 APInt One(BitWidth, 1);
13308 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13309 : APIntOps::umax(One, MinStride);
13310
13311 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13312 : APInt::getMaxValue(BitWidth);
13313 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13314
13315 // Although End can be a MAX expression we estimate MaxEnd considering only
13316 // the case End = RHS of the loop termination condition. This is safe because
13317 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13318 // taken count.
13319 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13320 MaxEnd =
13321 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13322
13323 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13324 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13325 : APIntOps::umax(MaxEnd, MinStart);
13326
13327 APInt Delta = MaxEnd - MinStart;
13328
13329 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13330 // tighter bound after folding.
13331 const SCEV *DeltaExpr =
13332 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13333 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13334
13335 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13336}
13337
13339ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13340 const Loop *L, bool IsSigned, bool Invert,
13341 bool ControlsOnlyExit, bool AllowPredicates) {
13343
13344 // Loop guards for L, collected on demand.
13345 std::optional<LoopGuards> CachedGuards;
13346 auto getGuards = [&]() -> const LoopGuards & {
13347 if (!CachedGuards)
13348 CachedGuards.emplace(LoopGuards::collect(L, *this));
13349 return *CachedGuards;
13350 };
13351
13352 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13353 if (Invert && !isLoopInvariant(RHS, L))
13354 return getCouldNotCompute();
13355
13356 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13357 bool PredicatedIV = false;
13358 // FIXME: Generalize the NUW inference below to decreasing IVs.
13359 if (!IV && !Invert) {
13360 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13361 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13362 if (AR && AR->getLoop() == L && AR->isAffine()) {
13363 auto canProveNUW = [&]() {
13364 // We can use the comparison to infer no-wrap flags only if it fully
13365 // controls the loop exit.
13366 if (!ControlsOnlyExit)
13367 return false;
13368
13369 if (!isLoopInvariant(RHS, L))
13370 return false;
13371
13372 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13373 // We need the sequence defined by AR to strictly increase in the
13374 // unsigned integer domain for the logic below to hold.
13375 return false;
13376
13377 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13378 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13379 // If RHS <=u Limit, then there must exist a value V in the sequence
13380 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13381 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13382 // overflow occurs. This limit also implies that a signed comparison
13383 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13384 // the high bits on both sides must be zero.
13385 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13386 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13387 Limit = Limit.zext(OuterBitWidth);
13388 return getUnsignedRangeMax(applyLoopGuards(RHS, getGuards()))
13389 .ule(Limit);
13390 };
13391 auto Flags = AR->getNoWrapFlags();
13392 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13393 Flags = setFlags(Flags, SCEV::FlagNUW);
13394
13395 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13396 if (AR->hasNoUnsignedWrap()) {
13397 // Emulate what getZeroExtendExpr would have done during construction
13398 // if we'd been able to infer the fact just above at that time.
13399 const SCEV *Step = AR->getStepRecurrence(*this);
13400 Type *Ty = ZExt->getType();
13401 const SCEV *S = getAddRecExpr(
13403 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13405 }
13406 }
13407 }
13408 }
13409
13410 if (!IV && AllowPredicates) {
13411 // Try to make this an AddRec using runtime tests, in the first X
13412 // iterations of this loop, where X is the SCEV expression found by the
13413 // algorithm below.
13414 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13415 PredicatedIV = true;
13416 }
13417
13418 // Avoid weird loops
13419 if (!IV || IV->getLoop() != L || !IV->isAffine())
13420 return getCouldNotCompute();
13421
13422 // A precondition of this method is that the condition being analyzed
13423 // reaches an exiting branch which dominates the latch. Given that, we can
13424 // assume that an increment which violates the nowrap specification and
13425 // produces poison must cause undefined behavior when the resulting poison
13426 // value is branched upon and thus we can conclude that the backedge is
13427 // taken no more often than would be required to produce that poison value.
13428 // Note that a well defined loop can exit on the iteration which violates
13429 // the nowrap specification if there is another exit (either explicit or
13430 // implicit/exceptional) which causes the loop to execute before the
13431 // exiting instruction we're analyzing would trigger UB.
13432 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13433 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13434 // Reverse the ordering for greater-than comparisons.
13436 if (Invert)
13438
13439 // The step of ~IV is the negated step of IV.
13440 const SCEV *Stride = IV->getStepRecurrence(*this);
13441 if (Invert)
13442 Stride = getNegativeSCEV(Stride);
13443 const SCEV *GuardedStride = Stride;
13444
13445 // Whether the IV may reach the maximum (or minimum if inverted) value
13446 // before the exit is taken.
13447 bool IVMayOverflow = true;
13448
13449 bool PositiveStride = isKnownPositive(Stride);
13450 // A dominating guard may prove the stride positive.
13451 if (!PositiveStride) {
13452 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, getGuards());
13453 if (isKnownPositive(LoopGuardedStride)) {
13454 GuardedStride = LoopGuardedStride;
13455 PositiveStride = true;
13456 // Encode the context-sensitive stride > 0 fact into the expression
13457 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13458 }
13459 }
13460
13461 // Avoid negative or zero stride values.
13462 if (!PositiveStride) {
13463 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13464 if (Invert)
13465 return getCouldNotCompute();
13466
13467 // We can compute the correct backedge taken count for loops with unknown
13468 // strides if we can prove that the loop is not an infinite loop with side
13469 // effects. Here's the loop structure we are trying to handle -
13470 //
13471 // i = start
13472 // do {
13473 // A[i] = i;
13474 // i += s;
13475 // } while (i < end);
13476 //
13477 // The backedge taken count for such loops is evaluated as -
13478 // (max(end, start + stride) - start - 1) /u stride
13479 //
13480 // The additional preconditions that we need to check to prove correctness
13481 // of the above formula is as follows -
13482 //
13483 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13484 // NoWrap flag).
13485 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13486 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13487 // no side effects within the loop) or a predicate is added to ensure
13488 // stride is positive.
13489 // c) loop has a single static exit (with no abnormal exits)
13490 //
13491 // Precondition a) implies that if the stride is negative, this is a single
13492 // trip loop. The backedge taken count formula reduces to zero in this case.
13493 //
13494 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13495 // then a zero stride means the backedge can't be taken without executing
13496 // undefined behavior.
13497 //
13498 // The positive stride case is the same as isKnownPositive(Stride) returning
13499 // true (original behavior of the function).
13500 //
13501 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13502 return getCouldNotCompute();
13503
13504 if (!loopIsFiniteByAssumption(L)) {
13505 // If the loop may be infinite, add a predicate ensuring Stride is
13506 // positive, to guarantee forward progress.
13507 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13508 return getCouldNotCompute();
13509
13510 const SCEV *Zero = getZero(Stride->getType());
13511 const SCEVPredicate *P =
13513 Predicates.push_back(P);
13514 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13515 // so the result is unchanged. To prevent div by zero.
13516 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13517 } else if (!isKnownNonZero(Stride)) {
13518 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13519 // if it might eventually be greater than start and if so, on which
13520 // iteration. We can't even produce a useful upper bound.
13521 if (!isLoopInvariant(RHS, L))
13522 return getCouldNotCompute();
13523
13524 // We allow a potentially zero stride, but we need to divide by stride
13525 // below. Since the loop can't be infinite and this check must control
13526 // the sole exit, we can infer the exit must be taken on the first
13527 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13528 // we know the numerator in the divides below must be zero, so we can
13529 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13530 // and produce the right result.
13531 // FIXME: Handle the case where Stride is poison?
13532 auto wouldZeroStrideBeUB = [&]() {
13533 // Proof by contradiction. Suppose the stride were zero. If we can
13534 // prove that the backedge *is* taken on the first iteration, then since
13535 // we know this condition controls the sole exit, we must have an
13536 // infinite loop. We can't have a (well defined) infinite loop per
13537 // check just above.
13538 // Note: The (Start - Stride) term is used to get the start' term from
13539 // (start' + stride,+,stride). Remember that we only care about the
13540 // result of this expression when stride == 0 at runtime.
13541 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13542 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13543 };
13544 if (!wouldZeroStrideBeUB()) {
13545 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13546 }
13547 }
13548 } else {
13549 // Avoid proven overflow cases: this will ensure that the backedge taken
13550 // count will not generate any unsigned overflow.
13551 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert);
13552 if (IVMayOverflow && !NoWrap)
13553 return getCouldNotCompute();
13554 }
13555
13556 // On all paths just preceeding, we established the following invariant:
13557 // IV can be assumed not to overflow up to and including the exiting
13558 // iteration. We proved this in one of two ways:
13559 // 1) We can show overflow doesn't occur before the exiting iteration
13560 // 1a) canIVOverflowOnLT, and b) step of one
13561 // 2) We can show that if overflow occurs, the loop must execute UB
13562 // before any possible exit.
13563 // Note that we have not yet proved RHS invariant (in general).
13564
13565 const SCEV *Start = IV->getStart();
13566
13567 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13568 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13569 // Use integer-typed versions for actual computation; we can't subtract
13570 // pointers in general.
13571 const SCEV *OrigStart = Start;
13572 const SCEV *OrigRHS = RHS;
13573 if (Start->getType()->isPointerTy()) {
13574 Start = getPtrToAddrExpr(Start);
13575 if (isa<SCEVCouldNotCompute>(Start))
13576 return Start;
13577 }
13578 if (RHS->getType()->isPointerTy()) {
13581 return RHS;
13582 }
13583
13584 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13585 *BECountIfBackedgeTaken = getCouldNotCompute();
13586 if (!isLoopInvariant(RHS, L)) {
13587 assert(!Invert && "RHS must be loop-invariant for Invert");
13588 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13589 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13590 any(RHSAddRec->getNoWrapFlags())) {
13591 // The structure of loop we are trying to calculate backedge count of:
13592 //
13593 // left = left_start
13594 // right = right_start
13595 //
13596 // while(left < right){
13597 // ... do something here ...
13598 // left += s1; // stride of left is s1 (s1 > 0)
13599 // right += s2; // stride of right is s2 (s2 < 0)
13600 // }
13601 //
13602
13603 const SCEV *RHSStart = RHSAddRec->getStart();
13604 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13605
13606 // If Stride - RHSStride is positive and does not overflow, we can write
13607 // backedge count as ->
13608 // ceil((End - Start) /u (Stride - RHSStride))
13609 // Where, End = max(RHSStart, Start)
13610
13611 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13612 if (isKnownNegative(RHSStride) &&
13613 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13614 RHSStride)) {
13615
13616 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13617 if (isKnownPositive(Denominator)) {
13618 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13619 : getUMaxExpr(RHSStart, Start);
13620
13621 // We can do this because End >= Start, as End = max(RHSStart, Start)
13622 const SCEV *Delta = getMinusSCEV(End, Start);
13623
13624 BECount = getUDivCeilSCEV(Delta, Denominator);
13625 BECountIfBackedgeTaken =
13626 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13627 }
13628 }
13629 }
13630 } else {
13631 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13632 // describe the backedge count: if the backedge is taken at least once then
13633 // End is RHS, and if not End is Start so we get a backedge count of zero.
13634 // Inverted, End is min(RHS, Start).
13635 //
13636 // AddingStrideMinusOneMayOverflow has the following preconditions:
13637 //
13638 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13639 // 2. The index variable doesn't overflow.
13640 //
13641 // Therefore, we know N exists such that
13642 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13643 // doesn't overflow.
13644 //
13645 // Using this information, try to prove whether the addition in
13646 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13647 //
13648 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13649 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13650 // the (Stride - 1) addition below cannot overflow.
13651 const SCEV *One = getOne(Stride->getType());
13652 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13653 if (isKnownToBeAPowerOfTwo(Stride)) {
13654 // Suppose Stride is a power of two, and Start/End are unsigned
13655 // integers. Let UMAX be the largest representable unsigned
13656 // integer.
13657 //
13658 // By the preconditions of this function, we know
13659 // "(Start + Stride * N) >= End", and this doesn't overflow.
13660 // As a formula:
13661 //
13662 // End <= (Start + Stride * N) <= UMAX
13663 //
13664 // Subtracting Start from all the terms:
13665 //
13666 // End - Start <= Stride * N <= UMAX - Start
13667 //
13668 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13669 //
13670 // End - Start <= Stride * N <= UMAX
13671 //
13672 // Stride * N is a multiple of Stride. Therefore,
13673 //
13674 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13675 //
13676 // Since Stride is a power of two, UMAX + 1 is divisible by
13677 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13678 // write:
13679 //
13680 // End - Start <= Stride * N <= UMAX - Stride - 1
13681 //
13682 // Dropping the middle term:
13683 //
13684 // End - Start <= UMAX - Stride - 1
13685 //
13686 // Adding Stride - 1 to both sides:
13687 //
13688 // (End - Start) + (Stride - 1) <= UMAX
13689 //
13690 // In other words, the addition doesn't have unsigned overflow.
13691 //
13692 // A similar proof works if we treat Start/End as signed values.
13693 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13694 // to use signed max instead of unsigned max. Note that we're
13695 // trying to prove a lack of unsigned overflow in either case.
13696 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13697 return false;
13698 }
13699 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13700 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13701 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13702 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13703 // 1 <s End.
13704 //
13705 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13706 // End.
13707 //
13708 // Both need Start to be the smaller value, so neither applies inverted.
13709 return false;
13710 }
13711 return true;
13712 }();
13713
13714 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13715 // Offset)" and "~To - ~From" is "From - To".
13716 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13717 if (Invert)
13718 return getAddExpr(V, Offset);
13719 return getMinusSCEV(V, Offset);
13720 };
13721 auto Distance = [&](const SCEV *From, const SCEV *To) {
13722 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13723 };
13724
13725 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13726 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13727 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13728 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13729 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13730 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13731 // does not overflow?
13732 if ((!AddingStrideMinusOneMayOverflow ||
13733 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13734 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13735 // In this case, we can use a refined formula for computing backedge
13736 // taken count. The general formula remains:
13737 // "End-Start /uceiling Stride"
13738 // We want to use the alternate formula:
13739 // "((RHS - 1) - (Start - Stride)) /u Stride"
13740 // Let's do a quick case analysis to show these are equivalent under
13741 // our preconditions. When inverted, the proof uses complemented Start,
13742 // RHS and End; Stride remains positive.
13743 // * For RHS <= Start (End is Start), the backedge-taken count must be
13744 // zero. Together with the precondition "Start - Stride < RHS", we have
13745 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13746 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13747 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13748 // So dividing that by Stride gives zero.
13749 //
13750 // * For RHS > Start (End is RHS), the backedge count must be
13751 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13752 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13753 //
13754 // If "Start - Stride < Start" holds, we have
13755 // "RHS > Start > Start - Stride". As such
13756 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13757 // reassociated numerator.
13758 //
13759 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13760 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13761 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13762 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13763 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13764 const SCEV *Numerator =
13765 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13766 BECount = getUDivExpr(Numerator, Stride);
13767 }
13768
13769 if (isa<SCEVCouldNotCompute>(BECount)) {
13770 auto canProveRHSIsAtOrBeyondStart = [&]() {
13771 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13772 // by swapping their operands rather than their predicates:
13773 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13774 // proof if the IV bound moves to the other side.
13775 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13776 return Invert ? std::pair(B, A) : std::pair(A, B);
13777 };
13778
13779 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13780 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, getGuards());
13781 const SCEV *GuardedStart = applyLoopGuards(OrigStart, getGuards());
13782 if (Invert)
13783 std::swap(GuardedRHS, GuardedStart);
13784
13785 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13786 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13787 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13788 return true;
13789
13790 // (RHS > Start - 1) implies RHS >= Start.
13791 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13792 // "Start - 1" doesn't overflow.
13793 // * For signed comparison, if Start - 1 does overflow, it's equal
13794 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13795 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13796 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13797 //
13798 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13799 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13800 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13801 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13802 };
13803
13804 // If we know that RHS >= Start in the context of loop, then we know
13805 // that max(RHS, Start) = RHS at this point.
13806 if (canProveRHSIsAtOrBeyondStart()) {
13807 End = RHS;
13808 } else {
13809 // If RHS < Start, the backedge will be taken zero times. So in
13810 // general, we can write the backedge-taken count as:
13811 //
13812 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13813 //
13814 // We convert it to the following to make it more convenient for SCEV:
13815 //
13816 // ceil(max(RHS, Start) - Start) / Stride
13817 //
13818 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13819 if (Invert)
13820 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13821 else
13822 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13823
13824 // See what would happen if we assume the backedge is taken. This is
13825 // used to compute MaxBECount.
13826 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13827 }
13828
13829 const SCEV *Delta = Distance(Start, End);
13830 if (!AddingStrideMinusOneMayOverflow) {
13831 // floor((D + (S - 1)) / S)
13832 // We prefer this formulation if it's legal because it's fewer
13833 // operations.
13834 BECount =
13835 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13836 } else {
13837 BECount = getUDivCeilSCEV(Delta, Stride);
13838 }
13839 }
13840 }
13841
13842 const SCEV *ConstantMaxBECount;
13843 bool MaxOrZero = false;
13844 if (isa<SCEVConstant>(BECount)) {
13845 ConstantMaxBECount = BECount;
13846 } else {
13847 ConstantMaxBECount = computeMaxBECountForLT(
13848 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13849 Invert);
13850 // If we know exactly how many times the backedge will be taken if it's
13851 // taken at least once, then the backedge count will either be that or
13852 // zero. If that count exceeds the range-based bound, the backedge can
13853 // never be taken.
13854 const APInt *IfTaken, *RangeMax;
13855 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13856 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13857 IfTaken->ugt(*RangeMax)) {
13858 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13859 } else {
13860 ConstantMaxBECount = BECountIfBackedgeTaken;
13861 MaxOrZero = true;
13862 }
13863 }
13864 }
13865
13866 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13867 !isa<SCEVCouldNotCompute>(BECount))
13868 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13869
13870 const SCEV *SymbolicMaxBECount =
13871 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13872 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13873 Predicates);
13874}
13875
13877 ScalarEvolution &SE) const {
13878 if (Range.isFullSet()) // Infinite loop.
13879 return SE.getCouldNotCompute();
13880
13881 // If the start is a non-zero constant, shift the range to simplify things.
13882 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13883 if (!SC->getValue()->isZero()) {
13885 Operands[0] = SE.getZero(SC->getType());
13886 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13888 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13889 return ShiftedAddRec->getNumIterationsInRange(
13890 Range.subtract(SC->getAPInt()), SE);
13891 // This is strange and shouldn't happen.
13892 return SE.getCouldNotCompute();
13893 }
13894
13895 // The only time we can solve this is when we have all constant indices.
13896 // Otherwise, we cannot determine the overflow conditions.
13898 return SE.getCouldNotCompute();
13899
13900 // Okay at this point we know that all elements of the chrec are constants and
13901 // that the start element is zero.
13902
13903 // First check to see if the range contains zero. If not, the first
13904 // iteration exits.
13905 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13906 if (!Range.contains(APInt(BitWidth, 0)))
13907 return SE.getZero(getType());
13908
13909 if (isAffine()) {
13910 // If this is an affine expression then we have this situation:
13911 // Solve {0,+,A} in Range === Ax in Range
13912
13913 // We know that zero is in the range. If A is positive then we know that
13914 // the upper value of the range must be the first possible exit value.
13915 // If A is negative then the lower of the range is the last possible loop
13916 // value. Also note that we already checked for a full range.
13917 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13918 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13919
13920 // The exit value should be (End+A)/A.
13921 APInt ExitVal = (End + A).udiv(A);
13922 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13923
13924 // Evaluate at the exit value. If we really did fall out of the valid
13925 // range, then we computed our trip count, otherwise wrap around or other
13926 // things must have happened.
13927 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13928 if (Range.contains(Val->getValue()))
13929 return SE.getCouldNotCompute(); // Something strange happened
13930
13931 // Ensure that the previous value is in the range.
13932 assert(Range.contains(
13934 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13935 "Linear scev computation is off in a bad way!");
13936 return SE.getConstant(ExitValue);
13937 }
13938
13939 if (isQuadratic()) {
13940 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13941 return SE.getConstant(*S);
13942 }
13943
13944 return SE.getCouldNotCompute();
13945}
13946
13947const SCEVAddRecExpr *
13949 assert(getNumOperands() > 1 && "AddRec with zero step?");
13950 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13951 // but in this case we cannot guarantee that the value returned will be an
13952 // AddRec because SCEV does not have a fixed point where it stops
13953 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13954 // may happen if we reach arithmetic depth limit while simplifying. So we
13955 // construct the returned value explicitly.
13957 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13958 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13959 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13960 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13961 // We know that the last operand is not a constant zero (otherwise it would
13962 // have been popped out earlier). This guarantees us that if the result has
13963 // the same last operand, then it will also not be popped out, meaning that
13964 // the returned value will be an AddRec.
13965 const SCEV *Last = getOperand(getNumOperands() - 1);
13966 assert(!Last->isZero() && "Recurrency with zero step?");
13967 Ops.push_back(Last);
13969}
13970
13971// Return true when S contains at least an undef value.
13973 return SCEVExprContains(
13974 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13975}
13976
13977// Return true when S contains a value that is a nullptr.
13979 return SCEVExprContains(S, [](const SCEV *S) {
13980 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13981 return SU->getValue() == nullptr;
13982 return false;
13983 });
13984}
13985
13986/// Return the size of an element read or written by Inst.
13988 if (!isa<LoadInst, StoreInst>(Inst))
13989 return nullptr;
13991 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
13992}
13993
13994//===----------------------------------------------------------------------===//
13995// SCEVCallbackVH Class Implementation
13996//===----------------------------------------------------------------------===//
13997
13999 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14000 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14001 SE->ConstantEvolutionLoopExitValue.erase(PN);
14002 SE->eraseValueFromMap(getValPtr());
14003 // this now dangles!
14004}
14005
14006void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14007 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14008
14009 // Forget all the expressions associated with users of the old value,
14010 // so that future queries will recompute the expressions using the new
14011 // value.
14012 SE->forgetValue(getValPtr());
14013 // this now dangles!
14014}
14015
14016ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14017 : CallbackVH(V), SE(se) {}
14018
14019//===----------------------------------------------------------------------===//
14020// ScalarEvolution Class Implementation
14021//===----------------------------------------------------------------------===//
14022
14025 LoopInfo &LI)
14026 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14027 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14028 LoopDispositions(64), BlockDispositions(64) {
14029 // To use guards for proving predicates, we need to scan every instruction in
14030 // relevant basic blocks, and not just terminators. Doing this is a waste of
14031 // time if the IR does not actually contain any calls to
14032 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14033 //
14034 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14035 // to _add_ guards to the module when there weren't any before, and wants
14036 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14037 // efficient in lieu of being smart in that rather obscure case.
14038
14039 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14040 F.getParent(), Intrinsic::experimental_guard);
14041 HasGuards = GuardDecl && !GuardDecl->use_empty();
14042}
14043
14045 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14046 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14047 ValueExprMap(std::move(Arg.ValueExprMap)),
14048 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14049 PendingMerges(std::move(Arg.PendingMerges)),
14050 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14051 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14052 PredicatedBackedgeTakenCounts(
14053 std::move(Arg.PredicatedBackedgeTakenCounts)),
14054 BECountUsers(std::move(Arg.BECountUsers)),
14055 ConstantEvolutionLoopExitValue(
14056 std::move(Arg.ConstantEvolutionLoopExitValue)),
14057 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14058 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14059 LoopDispositions(std::move(Arg.LoopDispositions)),
14060 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14061 BlockDispositions(std::move(Arg.BlockDispositions)),
14062 SCEVUsers(std::move(Arg.SCEVUsers)),
14063 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14064 SignedRanges(std::move(Arg.SignedRanges)),
14065 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14066 UniquePreds(std::move(Arg.UniquePreds)),
14067 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14068 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14069 LoopUsers(std::move(Arg.LoopUsers)),
14070 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14071 FirstUnknown(Arg.FirstUnknown),
14072 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14073 Arg.FirstUnknown = nullptr;
14074}
14075
14077 // Iterate through all the SCEVUnknown instances and call their
14078 // destructors, so that they release their references to their values.
14079 for (SCEVUnknown *U = FirstUnknown; U;) {
14080 SCEVUnknown *Tmp = U;
14081 U = U->Next;
14082 Tmp->~SCEVUnknown();
14083 }
14084 FirstUnknown = nullptr;
14085
14086 ExprValueMap.clear();
14087 ValueExprMap.clear();
14088 HasRecMap.clear();
14089 BackedgeTakenCounts.clear();
14090 PredicatedBackedgeTakenCounts.clear();
14091
14092 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14093 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14094 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14095 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14096}
14097
14101
14102/// When printing a top-level SCEV for trip counts, it's helpful to include
14103/// a type for constants which are otherwise hard to disambiguate.
14104static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14105 if (isa<SCEVConstant>(S))
14106 OS << *S->getType() << " ";
14107 OS << *S;
14108}
14109
14111 const Loop *L) {
14112 // Print all inner loops first
14113 for (Loop *I : *L)
14114 PrintLoopInfo(OS, SE, I);
14115
14116 OS << "Loop ";
14117 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14118 OS << ": ";
14119
14120 SmallVector<BasicBlock *, 8> ExitingBlocks;
14121 L->getExitingBlocks(ExitingBlocks);
14122 if (ExitingBlocks.size() != 1)
14123 OS << "<multiple exits> ";
14124
14125 auto *BTC = SE->getBackedgeTakenCount(L);
14126 if (!isa<SCEVCouldNotCompute>(BTC)) {
14127 OS << "backedge-taken count is ";
14128 PrintSCEVWithTypeHint(OS, BTC);
14129 } else
14130 OS << "Unpredictable backedge-taken count.";
14131 OS << "\n";
14132
14133 if (ExitingBlocks.size() > 1)
14134 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14135 OS << " exit count for " << ExitingBlock->getName() << ": ";
14136 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14137 PrintSCEVWithTypeHint(OS, EC);
14138 if (isa<SCEVCouldNotCompute>(EC)) {
14139 // Retry with predicates.
14141 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14142 if (!isa<SCEVCouldNotCompute>(EC)) {
14143 OS << "\n predicated exit count for " << ExitingBlock->getName()
14144 << ": ";
14145 PrintSCEVWithTypeHint(OS, EC);
14146 OS << "\n Predicates:\n";
14147 for (const auto *P : Predicates)
14148 P->print(OS, 4);
14149 }
14150 }
14151 OS << "\n";
14152 }
14153
14154 OS << "Loop ";
14155 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14156 OS << ": ";
14157
14158 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14159 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14160 OS << "constant max backedge-taken count is ";
14161 PrintSCEVWithTypeHint(OS, ConstantBTC);
14163 OS << ", actual taken count either this or zero.";
14164 } else {
14165 OS << "Unpredictable constant max backedge-taken count. ";
14166 }
14167
14168 OS << "\n"
14169 "Loop ";
14170 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14171 OS << ": ";
14172
14173 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14174 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14175 OS << "symbolic max backedge-taken count is ";
14176 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14178 OS << ", actual taken count either this or zero.";
14179 } else {
14180 OS << "Unpredictable symbolic max backedge-taken count. ";
14181 }
14182 OS << "\n";
14183
14184 if (ExitingBlocks.size() > 1)
14185 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14186 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14187 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14189 PrintSCEVWithTypeHint(OS, ExitBTC);
14190 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14191 // Retry with predicates.
14193 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14195 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14196 OS << "\n predicated symbolic max exit count for "
14197 << ExitingBlock->getName() << ": ";
14198 PrintSCEVWithTypeHint(OS, ExitBTC);
14199 OS << "\n Predicates:\n";
14200 for (const auto *P : Predicates)
14201 P->print(OS, 4);
14202 }
14203 }
14204 OS << "\n";
14205 }
14206
14208 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14209 if (PBT != BTC) {
14210 OS << "Loop ";
14211 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14212 OS << ": ";
14213 if (!isa<SCEVCouldNotCompute>(PBT)) {
14214 OS << "Predicated backedge-taken count is ";
14215 PrintSCEVWithTypeHint(OS, PBT);
14216 } else
14217 OS << "Unpredictable predicated backedge-taken count.";
14218 OS << "\n";
14219 OS << " Predicates:\n";
14220 for (const auto *P : Preds)
14221 P->print(OS, 4);
14222 }
14223 Preds.clear();
14224
14225 auto *PredConstantMax =
14227 if (PredConstantMax != ConstantBTC) {
14228 OS << "Loop ";
14229 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14230 OS << ": ";
14231 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14232 OS << "Predicated constant max backedge-taken count is ";
14233 PrintSCEVWithTypeHint(OS, PredConstantMax);
14234 } else
14235 OS << "Unpredictable predicated constant max backedge-taken count.";
14236 OS << "\n";
14237 OS << " Predicates:\n";
14238 for (const auto *P : Preds)
14239 P->print(OS, 4);
14240 }
14241 Preds.clear();
14242
14243 auto *PredSymbolicMax =
14245 if (SymbolicBTC != PredSymbolicMax) {
14246 OS << "Loop ";
14247 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14248 OS << ": ";
14249 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14250 OS << "Predicated symbolic max backedge-taken count is ";
14251 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14252 } else
14253 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14254 OS << "\n";
14255 OS << " Predicates:\n";
14256 for (const auto *P : Preds)
14257 P->print(OS, 4);
14258 }
14259
14261 OS << "Loop ";
14262 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14263 OS << ": ";
14264 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14265 }
14266}
14267
14268namespace llvm {
14269// Note: these overloaded operators need to be in the llvm namespace for them
14270// to be resolved correctly. If we put them outside the llvm namespace, the
14271//
14272// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14273//
14274// code below "breaks" and start printing raw enum values as opposed to the
14275// string values.
14278 switch (LD) {
14280 OS << "Variant";
14281 break;
14283 OS << "Invariant";
14284 break;
14286 OS << "Uniform";
14287 break;
14289 OS << "Computable";
14290 break;
14291 }
14292 return OS;
14293}
14294
14297 switch (BD) {
14299 OS << "DoesNotDominate";
14300 break;
14302 OS << "Dominates";
14303 break;
14305 OS << "ProperlyDominates";
14306 break;
14307 }
14308 return OS;
14309}
14310} // namespace llvm
14311
14313 // ScalarEvolution's implementation of the print method is to print
14314 // out SCEV values of all instructions that are interesting. Doing
14315 // this potentially causes it to create new SCEV objects though,
14316 // which technically conflicts with the const qualifier. This isn't
14317 // observable from outside the class though, so casting away the
14318 // const isn't dangerous.
14319 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14320
14321 if (ClassifyExpressions) {
14322 OS << "Classifying expressions for: ";
14323 F.printAsOperand(OS, /*PrintType=*/false);
14324 OS << "\n";
14325 for (Instruction &I : instructions(F))
14326 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14327 OS << I << '\n';
14328 OS << " --> ";
14329 const SCEV *SV = SE.getSCEV(&I);
14330 SV->print(OS);
14331 if (!isa<SCEVCouldNotCompute>(SV)) {
14332 OS << " U: ";
14333 SE.getUnsignedRange(SV).print(OS);
14334 OS << " S: ";
14335 SE.getSignedRange(SV).print(OS);
14336 }
14337
14338 const Loop *L = LI.getLoopFor(I.getParent());
14339
14340 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14341 if (AtUse != SV) {
14342 OS << " --> ";
14343 OS << AtUse;
14344 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14345 OS << " U: ";
14346 SE.getUnsignedRange(AtUse).print(OS);
14347 OS << " S: ";
14348 SE.getSignedRange(AtUse).print(OS);
14349 }
14350 }
14351
14352 if (L) {
14353 OS << "\t\t" "Exits: ";
14354 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14355 if (!SE.isLoopInvariant(ExitValue, L)) {
14356 OS << "<<Unknown>>";
14357 } else {
14358 OS << ExitValue;
14359 }
14360
14361 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14362 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14363 OS << LS;
14364 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14365 OS << ": " << SE.getLoopDisposition(SV, Iter);
14366 }
14367
14368 for (const auto *InnerL : depth_first(L)) {
14369 if (InnerL == L)
14370 continue;
14371 OS << LS;
14372 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14373 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14374 }
14375
14376 OS << " }";
14377 }
14378
14379 OS << "\n";
14380 }
14381 }
14382
14383 OS << "Determining loop execution counts for: ";
14384 F.printAsOperand(OS, /*PrintType=*/false);
14385 OS << "\n";
14386 for (Loop *I : LI)
14387 PrintLoopInfo(OS, &SE, I);
14388}
14389
14392 auto &Values = LoopDispositions[S];
14393 for (auto &V : Values) {
14394 if (V.getPointer() == L)
14395 return V.getInt();
14396 }
14397 Values.emplace_back(L, LoopVariant);
14398 LoopDisposition D = computeLoopDisposition(S, L);
14399 auto &Values2 = LoopDispositions[S];
14400 for (auto &V : llvm::reverse(Values2)) {
14401 if (V.getPointer() == L) {
14402 V.setInt(D);
14403 break;
14404 }
14405 }
14406 return D;
14407}
14408
14410ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14411 switch (S->getSCEVType()) {
14412 case scConstant:
14413 case scVScale:
14414 return LoopInvariant;
14415 case scAddRecExpr: {
14416 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14417
14418 // If L is the addrec's loop, it's computable.
14419 if (AR->getLoop() == L)
14420 return LoopComputable;
14421
14422 // Add recurrences are never invariant in the function-body (null loop).
14423 if (!L)
14424 return LoopVariant;
14425
14426 // Everything that is not defined at loop entry is variant.
14427 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14428 if (L->contains(AR->getLoop()) &&
14429 llvm::all_of(AR->operands(),
14430 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14431 return LoopUniform;
14432
14433 return LoopVariant;
14434 }
14435 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14436 " dominate the contained loop's header?");
14437
14438 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14439 if (AR->getLoop()->contains(L))
14440 return LoopInvariant;
14441
14442 // This recurrence is variant w.r.t. L if any of its operands
14443 // are variant.
14444 for (SCEVUse Op : AR->operands())
14445 if (!isLoopInvariant(Op, L))
14446 return LoopVariant;
14447
14448 // Otherwise it's loop-invariant.
14449 return LoopInvariant;
14450 }
14451 case scTruncate:
14452 case scZeroExtend:
14453 case scSignExtend:
14454 case scPtrToAddr:
14455 case scAddExpr:
14456 case scMulExpr:
14457 case scUDivExpr:
14458 case scUMaxExpr:
14459 case scSMaxExpr:
14460 case scUMinExpr:
14461 case scSMinExpr:
14462 case scSequentialUMinExpr: {
14463 bool HasVarying = false;
14464 bool HasUniform = false;
14465 for (SCEVUse Op : S->operands()) {
14467 if (D == LoopVariant)
14468 return LoopVariant;
14469 if (D == LoopComputable)
14470 HasVarying = true;
14471 if (D == LoopUniform)
14472 HasUniform = true;
14473 }
14474 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14475 : (HasUniform ? LoopUniform : LoopInvariant);
14476 }
14477 case scUnknown:
14478 // All non-instruction values are loop invariant. All instructions are loop
14479 // invariant if they are not contained in the specified loop.
14480 // Instructions are never considered invariant in the function body
14481 // (null loop) because they are defined within the "loop".
14483 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14484 return LoopInvariant;
14485 case scCouldNotCompute:
14486 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14487 }
14488 llvm_unreachable("Unknown SCEV kind!");
14489}
14490
14491bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14493 return D == LoopUniform || D == LoopInvariant;
14494}
14495
14497 return getLoopDisposition(S, L) == LoopInvariant;
14498}
14499
14501 return getLoopDisposition(S, L) == LoopComputable;
14502}
14503
14506 auto &Values = BlockDispositions[S];
14507 for (auto &V : Values) {
14508 if (V.getPointer() == BB)
14509 return V.getInt();
14510 }
14511 Values.emplace_back(BB, DoesNotDominateBlock);
14512 BlockDisposition D = computeBlockDisposition(S, BB);
14513 auto &Values2 = BlockDispositions[S];
14514 for (auto &V : llvm::reverse(Values2)) {
14515 if (V.getPointer() == BB) {
14516 V.setInt(D);
14517 break;
14518 }
14519 }
14520 return D;
14521}
14522
14524ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14525 switch (S->getSCEVType()) {
14526 case scConstant:
14527 case scVScale:
14529 case scAddRecExpr: {
14530 // This uses a "dominates" query instead of "properly dominates" query
14531 // to test for proper dominance too, because the instruction which
14532 // produces the addrec's value is a PHI, and a PHI effectively properly
14533 // dominates its entire containing block.
14534 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14535 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14536 return DoesNotDominateBlock;
14537
14538 // Fall through into SCEVNAryExpr handling.
14539 [[fallthrough]];
14540 }
14541 case scTruncate:
14542 case scZeroExtend:
14543 case scSignExtend:
14544 case scPtrToAddr:
14545 case scAddExpr:
14546 case scMulExpr:
14547 case scUDivExpr:
14548 case scUMaxExpr:
14549 case scSMaxExpr:
14550 case scUMinExpr:
14551 case scSMinExpr:
14552 case scSequentialUMinExpr: {
14553 bool Proper = true;
14554 for (const SCEV *NAryOp : S->operands()) {
14556 if (D == DoesNotDominateBlock)
14557 return DoesNotDominateBlock;
14558 if (D == DominatesBlock)
14559 Proper = false;
14560 }
14561 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14562 }
14563 case scUnknown:
14564 if (Instruction *I =
14566 if (I->getParent() == BB)
14567 return DominatesBlock;
14568 if (DT.properlyDominates(I->getParent(), BB))
14570 return DoesNotDominateBlock;
14571 }
14573 case scCouldNotCompute:
14574 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14575 }
14576 llvm_unreachable("Unknown SCEV kind!");
14577}
14578
14579bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14580 return getBlockDisposition(S, BB) >= DominatesBlock;
14581}
14582
14585}
14586
14587void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14588 bool Predicated) {
14589 auto &BECounts =
14590 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14591 auto It = BECounts.find(L);
14592 if (It != BECounts.end()) {
14593 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14594 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14595 if (!isa<SCEVConstant>(S)) {
14596 auto UserIt = BECountUsers.find(S);
14597 assert(UserIt != BECountUsers.end());
14598 UserIt->second.erase({L, Predicated});
14599 }
14600 }
14601 }
14602 BECounts.erase(It);
14603 }
14604}
14605
14606void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14607 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14608 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14609
14610 while (!Worklist.empty()) {
14611 const SCEV *Curr = Worklist.pop_back_val();
14612 auto Users = SCEVUsers.find(Curr);
14613 if (Users != SCEVUsers.end())
14614 for (const auto *User : Users->second)
14615 if (ToForget.insert(User).second)
14616 Worklist.push_back(User);
14617 }
14618
14619 for (const auto *S : ToForget)
14620 forgetMemoizedResultsImpl(S);
14621
14622 PredicatedSCEVRewrites.remove_if(
14623 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14624}
14625
14626void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14627 LoopDispositions.erase(S);
14628 BlockDispositions.erase(S);
14629 UnsignedRanges.erase(S);
14630 SignedRanges.erase(S);
14631 HasRecMap.erase(S);
14632 ConstantMultipleCache.erase(S);
14633
14634 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14635 UnsignedWrapViaInductionTried.erase(AR);
14636 SignedWrapViaInductionTried.erase(AR);
14637 }
14638
14639 auto ExprIt = ExprValueMap.find(S);
14640 if (ExprIt != ExprValueMap.end()) {
14641 for (Value *V : ExprIt->second) {
14642 auto ValueIt = ValueExprMap.find_as(V);
14643 if (ValueIt != ValueExprMap.end())
14644 ValueExprMap.erase(ValueIt);
14645 }
14646 ExprValueMap.erase(ExprIt);
14647 }
14648
14649 auto ScopeIt = ValuesAtScopes.find(S);
14650 if (ScopeIt != ValuesAtScopes.end()) {
14651 for (const auto &Pair : ScopeIt->second)
14652 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14653 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14654 std::make_pair(Pair.first, S));
14655 ValuesAtScopes.erase(ScopeIt);
14656 }
14657
14658 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14659 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14660 for (const auto &Pair : ScopeUserIt->second)
14661 // The recorded value at scope is a use of S, which may carry no-wrap
14662 // flags that are not part of this key.
14663 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14664 return LS.first == Pair.first && LS.second.getPointer() == S;
14665 });
14666 ValuesAtScopesUsers.erase(ScopeUserIt);
14667 }
14668
14669 auto BEUsersIt = BECountUsers.find(S);
14670 if (BEUsersIt != BECountUsers.end()) {
14671 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14672 auto Copy = BEUsersIt->second;
14673 for (const auto &Pair : Copy)
14674 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14675 BECountUsers.erase(BEUsersIt);
14676 }
14677
14678 auto FoldUser = FoldCacheUser.find(S);
14679 if (FoldUser != FoldCacheUser.end())
14680 for (auto &KV : FoldUser->second)
14681 FoldCache.erase(KV);
14682 FoldCacheUser.erase(S);
14683}
14684
14685void
14686ScalarEvolution::getUsedLoops(const SCEV *S,
14687 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14688 struct FindUsedLoops {
14689 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14690 : LoopsUsed(LoopsUsed) {}
14691 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14692 bool follow(const SCEV *S) {
14693 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14694 LoopsUsed.insert(AR->getLoop());
14695 return true;
14696 }
14697
14698 bool isDone() const { return false; }
14699 };
14700
14701 FindUsedLoops F(LoopsUsed);
14702 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14703}
14704
14705void ScalarEvolution::getReachableBlocks(
14708 Worklist.push_back(&F.getEntryBlock());
14709 while (!Worklist.empty()) {
14710 BasicBlock *BB = Worklist.pop_back_val();
14711 if (!Reachable.insert(BB).second)
14712 continue;
14713
14714 Value *Cond;
14715 BasicBlock *TrueBB, *FalseBB;
14716 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14717 m_BasicBlock(FalseBB)))) {
14718 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14719 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14720 continue;
14721 }
14722
14723 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14724 const SCEV *L = getSCEV(Cmp->getOperand(0));
14725 const SCEV *R = getSCEV(Cmp->getOperand(1));
14726 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14727 Worklist.push_back(TrueBB);
14728 continue;
14729 }
14730 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14731 R)) {
14732 Worklist.push_back(FalseBB);
14733 continue;
14734 }
14735 }
14736 }
14737
14738 append_range(Worklist, successors(BB));
14739 }
14740}
14741
14743 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14744 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14745
14746 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14747
14748 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14749 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14750 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14751
14752 const SCEV *visitConstant(const SCEVConstant *Constant) {
14753 return SE.getConstant(Constant->getAPInt());
14754 }
14755
14756 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14757 return SE.getUnknown(Expr->getValue());
14758 }
14759
14760 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14761 return SE.getCouldNotCompute();
14762 }
14763 };
14764
14765 SCEVMapper SCM(SE2);
14766 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14767 SE2.getReachableBlocks(ReachableBlocks, F);
14768
14769 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14770 if (containsUndefs(Old) || containsUndefs(New)) {
14771 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14772 // not propagate undef aggressively). This means we can (and do) fail
14773 // verification in cases where a transform makes a value go from "undef"
14774 // to "undef+1" (say). The transform is fine, since in both cases the
14775 // result is "undef", but SCEV thinks the value increased by 1.
14776 return nullptr;
14777 }
14778
14779 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14780 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14781 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14782 return nullptr;
14783
14784 return Delta;
14785 };
14786
14787 while (!LoopStack.empty()) {
14788 auto *L = LoopStack.pop_back_val();
14789 llvm::append_range(LoopStack, *L);
14790
14791 // Only verify BECounts in reachable loops. For an unreachable loop,
14792 // any BECount is legal.
14793 if (!ReachableBlocks.contains(L->getHeader()))
14794 continue;
14795
14796 // Only verify cached BECounts. Computing new BECounts may change the
14797 // results of subsequent SCEV uses.
14798 auto It = BackedgeTakenCounts.find(L);
14799 if (It == BackedgeTakenCounts.end())
14800 continue;
14801
14802 auto *CurBECount =
14803 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14804 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14805
14806 if (CurBECount == SE2.getCouldNotCompute() ||
14807 NewBECount == SE2.getCouldNotCompute()) {
14808 // NB! This situation is legal, but is very suspicious -- whatever pass
14809 // change the loop to make a trip count go from could not compute to
14810 // computable or vice-versa *should have* invalidated SCEV. However, we
14811 // choose not to assert here (for now) since we don't want false
14812 // positives.
14813 continue;
14814 }
14815
14816 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14817 SE.getTypeSizeInBits(NewBECount->getType()))
14818 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14819 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14820 SE.getTypeSizeInBits(NewBECount->getType()))
14821 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14822
14823 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14824 if (Delta && !Delta->isZero()) {
14825 dbgs() << "Trip Count for " << *L << " Changed!\n";
14826 dbgs() << "Old: " << *CurBECount << "\n";
14827 dbgs() << "New: " << *NewBECount << "\n";
14828 dbgs() << "Delta: " << *Delta << "\n";
14829 std::abort();
14830 }
14831 }
14832
14833 // Collect all valid loops currently in LoopInfo.
14834 SmallPtrSet<Loop *, 32> ValidLoops;
14835 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14836 while (!Worklist.empty()) {
14837 Loop *L = Worklist.pop_back_val();
14838 if (ValidLoops.insert(L).second)
14839 Worklist.append(L->begin(), L->end());
14840 }
14841 for (const auto &KV : ValueExprMap) {
14842#ifndef NDEBUG
14843 // Check for SCEV expressions referencing invalid/deleted loops.
14844 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14845 assert(ValidLoops.contains(AR->getLoop()) &&
14846 "AddRec references invalid loop");
14847 }
14848#endif
14849
14850 // Check that the value is also part of the reverse map.
14851 auto It = ExprValueMap.find(KV.second);
14852 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14853 dbgs() << "Value " << *KV.first
14854 << " is in ValueExprMap but not in ExprValueMap\n";
14855 std::abort();
14856 }
14857
14858 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14859 if (!ReachableBlocks.contains(I->getParent()))
14860 continue;
14861 const SCEV *OldSCEV = SCM.visit(KV.second);
14862 const SCEV *NewSCEV = SE2.getSCEV(I);
14863 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14864 if (Delta && !Delta->isZero()) {
14865 dbgs() << "SCEV for value " << *I << " changed!\n"
14866 << "Old: " << *OldSCEV << "\n"
14867 << "New: " << *NewSCEV << "\n"
14868 << "Delta: " << *Delta << "\n";
14869 std::abort();
14870 }
14871 }
14872 }
14873
14874 for (const auto &KV : ExprValueMap) {
14875 for (Value *V : KV.second) {
14876 const SCEV *S = ValueExprMap.lookup(V);
14877 if (!S) {
14878 dbgs() << "Value " << *V
14879 << " is in ExprValueMap but not in ValueExprMap\n";
14880 std::abort();
14881 }
14882 if (S != KV.first) {
14883 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14884 << *KV.first << "\n";
14885 std::abort();
14886 }
14887 }
14888 }
14889
14890 // Verify integrity of SCEV users.
14891 for (const auto &S : UniqueSCEVs) {
14892 for (SCEVUse Op : S.operands()) {
14893 // We do not store dependencies of constants.
14894 if (isa<SCEVConstant>(Op))
14895 continue;
14896 auto It = SCEVUsers.find(Op);
14897 if (It != SCEVUsers.end() && It->second.count(&S))
14898 continue;
14899 dbgs() << "Use of operand " << *Op << " by user " << S
14900 << " is not being tracked!\n";
14901 std::abort();
14902 }
14903 }
14904
14905 // Verify integrity of ValuesAtScopes users.
14906 for (const auto &ValueAndVec : ValuesAtScopes) {
14907 const SCEV *Value = ValueAndVec.first;
14908 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14909 const Loop *L = LoopAndValueAtScope.first;
14910 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14911 if (!isa<SCEVConstant>(ValueAtScope)) {
14912 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14913 if (It != ValuesAtScopesUsers.end() &&
14914 is_contained(It->second, std::make_pair(L, Value)))
14915 continue;
14916 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14917 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14918 std::abort();
14919 }
14920 }
14921 }
14922
14923 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14924 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14925 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14926 const Loop *L = LoopAndValue.first;
14927 const SCEV *Value = LoopAndValue.second;
14929 auto It = ValuesAtScopes.find(Value);
14930 // The recorded value at scope may carry no-wrap flags that are not part
14931 // of the key it is recorded under.
14932 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14933 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14934 }))
14935 continue;
14936 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14937 << *ValueAtScope << " missing in ValuesAtScopes\n";
14938 std::abort();
14939 }
14940 }
14941
14942 // Verify integrity of BECountUsers.
14943 auto VerifyBECountUsers = [&](bool Predicated) {
14944 auto &BECounts =
14945 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14946 for (const auto &LoopAndBEInfo : BECounts) {
14947 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14948 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14949 if (!isa<SCEVConstant>(S)) {
14950 auto UserIt = BECountUsers.find(S);
14951 if (UserIt != BECountUsers.end() &&
14952 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14953 continue;
14954 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14955 << " missing from BECountUsers\n";
14956 std::abort();
14957 }
14958 }
14959 }
14960 }
14961 };
14962 VerifyBECountUsers(/* Predicated */ false);
14963 VerifyBECountUsers(/* Predicated */ true);
14964
14965 // Verify intergity of loop disposition cache.
14966 for (auto &[S, Values] : LoopDispositions) {
14967 for (auto [Loop, CachedDisposition] : Values) {
14968 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14969 if (CachedDisposition != RecomputedDisposition) {
14970 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14971 << " is incorrect: cached " << CachedDisposition << ", actual "
14972 << RecomputedDisposition << "\n";
14973 std::abort();
14974 }
14975 }
14976 }
14977
14978 // Verify integrity of the block disposition cache.
14979 for (auto &[S, Values] : BlockDispositions) {
14980 for (auto [BB, CachedDisposition] : Values) {
14981 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14982 if (CachedDisposition != RecomputedDisposition) {
14983 dbgs() << "Cached disposition of " << *S << " for block %"
14984 << BB->getName() << " is incorrect: cached " << CachedDisposition
14985 << ", actual " << RecomputedDisposition << "\n";
14986 std::abort();
14987 }
14988 }
14989 }
14990
14991 // Verify FoldCache/FoldCacheUser caches.
14992 for (auto [FoldID, Expr] : FoldCache) {
14993 auto I = FoldCacheUser.find(Expr);
14994 if (I == FoldCacheUser.end()) {
14995 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14996 << "!\n";
14997 std::abort();
14998 }
14999 if (!is_contained(I->second, FoldID)) {
15000 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15001 std::abort();
15002 }
15003 }
15004 for (auto [Expr, IDs] : FoldCacheUser) {
15005 for (auto &FoldID : IDs) {
15006 const SCEV *S = FoldCache.lookup(FoldID);
15007 if (!S) {
15008 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15009 << "!\n";
15010 std::abort();
15011 }
15012 if (S != Expr) {
15013 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15014 << " != " << *Expr << "!\n";
15015 std::abort();
15016 }
15017 }
15018 }
15019
15020 // Verify that ConstantMultipleCache computations are correct. We check that
15021 // cached multiples and recomputed multiples are multiples of each other to
15022 // verify correctness. It is possible that a recomputed multiple is different
15023 // from the cached multiple due to strengthened no wrap flags or changes in
15024 // KnownBits computations.
15025 for (auto [S, Multiple] : ConstantMultipleCache) {
15026 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15027 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15028 Multiple.urem(RecomputedMultiple) != 0 &&
15029 RecomputedMultiple.urem(Multiple) != 0)) {
15030 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15031 << *S << " : Computed " << RecomputedMultiple
15032 << " but cache contains " << Multiple << "!\n";
15033 std::abort();
15034 }
15035 }
15036}
15037
15039 Function &F, const PreservedAnalyses &PA,
15040 FunctionAnalysisManager::Invalidator &Inv) {
15041 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15042 // of its dependencies is invalidated.
15043 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15044 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15045 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15046 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15047 Inv.invalidate<LoopAnalysis>(F, PA);
15048}
15049
15050AnalysisKey ScalarEvolutionAnalysis::Key;
15051
15054 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15055 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15056 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15057 auto &LI = AM.getResult<LoopAnalysis>(F);
15058 return ScalarEvolution(F, TLI, AC, DT, LI);
15059}
15060
15066
15069 // For compatibility with opt's -analyze feature under legacy pass manager
15070 // which was not ported to NPM. This keeps tests using
15071 // update_analyze_test_checks.py working.
15072 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15073 << F.getName() << "':\n";
15075 return PreservedAnalyses::all();
15076}
15077
15079 "Scalar Evolution Analysis", false, true)
15085 "Scalar Evolution Analysis", false, true)
15086
15087char ScalarEvolutionWrapperPass::ID = 0;
15088
15090
15092 SE.reset(new ScalarEvolution(
15094 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15096 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15097 return false;
15098}
15099
15101
15103 SE->print(OS);
15104}
15105
15107 if (!VerifySCEV)
15108 return;
15109
15110 SE->verify();
15111}
15112
15120
15122 const SCEV *RHS) {
15123 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15124}
15125
15126const SCEVPredicate *
15128 const SCEV *LHS, const SCEV *RHS) {
15130 assert(LHS->getType() == RHS->getType() &&
15131 "Type mismatch between LHS and RHS");
15132 // Unique this node based on the arguments
15133 ID.AddInteger(SCEVPredicate::P_Compare);
15134 ID.AddInteger(Pred);
15135 ID.AddPointer(LHS);
15136 ID.AddPointer(RHS);
15138 if (const auto *S = UniquePreds.lookup(ID, Token))
15139 return S;
15140 SCEVComparePredicate *Eq = new (SCEVAllocator)
15141 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15142 UniquePreds.insert(Eq, Token);
15143 return Eq;
15144}
15145
15147 const SCEVAddRecExpr *AR,
15150 // Unique this node based on the arguments
15152 ID.AddPointer(AR);
15153 ID.AddInteger(AddedFlags);
15155 if (const auto *S = UniquePreds.lookup(ID, Token))
15156 return S;
15157 auto *OF = new (SCEVAllocator)
15158 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15159 UniquePreds.insert(OF, Token);
15160 return OF;
15161}
15162
15163namespace {
15164
15165class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15166public:
15167
15168 /// Rewrites \p S in the context of a loop L and the SCEV predication
15169 /// infrastructure.
15170 ///
15171 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15172 /// equivalences present in \p Pred.
15173 ///
15174 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15175 /// \p NewPreds such that the result will be an AddRecExpr.
15176 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15178 const SCEVPredicate *Pred) {
15179 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15180 return Rewriter.visit(S);
15181 }
15182
15183 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15184 if (Pred) {
15185 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15186 for (const auto *Pred : U->getPredicates())
15187 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15188 if (IPred->getLHS() == Expr &&
15189 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15190 return IPred->getRHS();
15191 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15192 if (IPred->getLHS() == Expr &&
15193 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15194 return IPred->getRHS();
15195 }
15196 }
15197 return convertToAddRecWithPreds(Expr);
15198 }
15199
15200 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15201 const SCEV *Operand = visit(Expr->getOperand());
15202 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15203 if (AR && AR->getLoop() == L && AR->isAffine()) {
15204 // This couldn't be folded because the operand didn't have the nuw
15205 // flag. Add the nusw flag as an assumption that we could make.
15206 const SCEV *Step = AR->getStepRecurrence(SE);
15207 Type *Ty = Expr->getType();
15208 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15209 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15210 SE.getSignExtendExpr(Step, Ty), L,
15211 AR->getNoWrapFlags());
15212 }
15213 return SE.getZeroExtendExpr(Operand, Expr->getType());
15214 }
15215
15216 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15217 const SCEV *Operand = visit(Expr->getOperand());
15218 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15219 if (AR && AR->getLoop() == L && AR->isAffine()) {
15220 // This couldn't be folded because the operand didn't have the nsw
15221 // flag. Add the nssw flag as an assumption that we could make.
15222 const SCEV *Step = AR->getStepRecurrence(SE);
15223 Type *Ty = Expr->getType();
15224 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15225 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15226 SE.getSignExtendExpr(Step, Ty), L,
15227 AR->getNoWrapFlags());
15228 }
15229 return SE.getSignExtendExpr(Operand, Expr->getType());
15230 }
15231
15232private:
15233 explicit SCEVPredicateRewriter(
15234 const Loop *L, ScalarEvolution &SE,
15235 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15236 const SCEVPredicate *Pred)
15237 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15238
15239 bool addOverflowAssumption(const SCEVPredicate *P) {
15240 if (!NewPreds) {
15241 // Check if we've already made this assumption.
15242 return Pred && Pred->implies(P, SE);
15243 }
15244 NewPreds->push_back(P);
15245 return true;
15246 }
15247
15248 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15250 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15251 return addOverflowAssumption(A);
15252 }
15253
15254 // If \p Expr represents a PHINode, we try to see if it can be represented
15255 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15256 // to add this predicate as a runtime overflow check, we return the AddRec.
15257 // If \p Expr does not meet these conditions (is not a PHI node, or we
15258 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15259 // return \p Expr.
15260 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15261 if (!isa<PHINode>(Expr->getValue()))
15262 return Expr;
15263 std::optional<
15264 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15265 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15266 if (!PredicatedRewrite)
15267 return Expr;
15268 for (const auto *P : PredicatedRewrite->second){
15269 // Wrap predicates from outer loops are not supported.
15270 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15271 if (L != WP->getExpr()->getLoop())
15272 return Expr;
15273 }
15274 if (!addOverflowAssumption(P))
15275 return Expr;
15276 }
15277 return PredicatedRewrite->first;
15278 }
15279
15280 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15281 const SCEVPredicate *Pred;
15282 const Loop *L;
15283};
15284
15285} // end anonymous namespace
15286
15287const SCEV *
15289 const SCEVPredicate &Preds) {
15290 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15291}
15292
15294 const SCEV *S, const Loop *L,
15297 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15298 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15299
15300 if (!AddRec)
15301 return nullptr;
15302
15303 // Check if any of the transformed predicates is known to be false. In that
15304 // case, it doesn't make sense to convert to a predicated AddRec, as the
15305 // versioned loop will never execute.
15306 for (const SCEVPredicate *Pred : TransformPreds) {
15307 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15308 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15309 continue;
15310
15311 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15312 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15313 if (isa<SCEVCouldNotCompute>(ExitCount))
15314 continue;
15315
15316 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15317 if (!Step->isOne())
15318 continue;
15319
15320 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15321 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15322 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15323 return nullptr;
15324 }
15325
15326 // Since the transformation was successful, we can now transfer the SCEV
15327 // predicates.
15328 Preds.append(TransformPreds.begin(), TransformPreds.end());
15329
15330 return AddRec;
15331}
15332
15333/// SCEV predicates
15337
15339 const ICmpInst::Predicate Pred,
15340 const SCEV *LHS, const SCEV *RHS)
15341 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15342 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15343 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15344}
15345
15347 ScalarEvolution &SE) const {
15348 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15349
15350 if (!Op)
15351 return false;
15352
15353 if (Pred != ICmpInst::ICMP_EQ)
15354 return false;
15355
15356 return Op->LHS == LHS && Op->RHS == RHS;
15357}
15358
15359bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15360
15362 if (Pred == ICmpInst::ICMP_EQ)
15363 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15364 else
15365 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15366 << *RHS << "\n";
15367
15368}
15369
15371 const SCEVAddRecExpr *AR,
15372 IncrementWrapFlags Flags)
15373 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15374
15375const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15376
15378 ScalarEvolution &SE) const {
15379 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15380 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15381 return false;
15382
15383 if (Op->AR == AR)
15384 return true;
15385
15386 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15388 return false;
15389
15390 const SCEV *Start = AR->getStart();
15391 const SCEV *OpStart = Op->AR->getStart();
15392 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15393 return false;
15394
15395 // Reject pointers to different address spaces.
15396 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15397 return false;
15398
15399 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15400 // narrower-type AddRec.
15401 if (SE.getTypeSizeInBits(AR->getType()) >
15402 SE.getTypeSizeInBits(Op->AR->getType()))
15403 return false;
15404
15405 const SCEV *Step = AR->getStepRecurrence(SE);
15406 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15407 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15408 return false;
15409
15410 // If both steps are positive, this implies N, if N's start and step are
15411 // ULE/SLE (for NSUW/NSSW) than this'.
15412 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15413 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15414 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15415
15416 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15417 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15418 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15419 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15420 : SE.getNoopOrSignExtend(Start, WiderTy);
15422 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15423 SE.isKnownPredicate(Pred, OpStart, Start);
15424}
15425
15427 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15428 IncrementWrapFlags IFlags = Flags;
15429
15430 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15431 IFlags = clearFlags(IFlags, IncrementNSSW);
15432
15433 return IFlags == IncrementAnyWrap;
15434}
15435
15436void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15437 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15439 OS << "<nusw>";
15441 OS << "<nssw>";
15442 OS << "\n";
15443}
15444
15445/// Union predicates don't get cached so create a dummy set ID for it.
15447 ScalarEvolution &SE)
15449 for (const auto *P : Preds)
15450 add(P, SE);
15451}
15452
15454 return all_of(Preds,
15455 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15456}
15457
15459 ScalarEvolution &SE) const {
15460 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15461 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15462 return this->implies(I, SE);
15463 });
15464
15465 if (any_of(Preds,
15466 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15467 return true;
15468
15469 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15470 // equal predicates.
15471 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15472 if (!NWrap)
15473 return false;
15474 const Loop *L = NWrap->getExpr()->getLoop();
15475 return any_of(Preds, [&](const SCEVPredicate *I) {
15476 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15477 if (!IWrap)
15478 return false;
15479 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15480 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15481 return RewrittenAR &&
15482 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15483 });
15484}
15485
15487 for (const auto *Pred : Preds)
15488 Pred->print(OS, Depth);
15489}
15490
15491void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15492 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15493 for (const auto *Pred : Set->Preds)
15494 add(Pred, SE);
15495 return;
15496 }
15497
15498 // Implication checks are quadratic in the number of predicates. Stop doing
15499 // them if there are many predicates, as they should be too expensive to use
15500 // anyway at that point.
15501 bool CheckImplies = Preds.size() < 16;
15502
15503 // Only add predicate if it is not already implied by this union predicate.
15504 if (CheckImplies && implies(N, SE))
15505 return;
15506
15507 // Build a new vector containing the current predicates, except the ones that
15508 // are implied by the new predicate N.
15510 for (auto *P : Preds) {
15511 if (CheckImplies && N->implies(P, SE))
15512 continue;
15513 PrunedPreds.push_back(P);
15514 }
15515 Preds = std::move(PrunedPreds);
15516 Preds.push_back(N);
15517}
15518
15520 Loop &L)
15521 : SE(SE), L(L) {
15523 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15524}
15525
15527 for (const SCEV *Op : Ops)
15528 // We do not expect that forgetting cached data for SCEVConstants will ever
15529 // open any prospects for sharpening or introduce any correctness issues,
15530 // so we don't bother storing their dependencies.
15531 if (!isa<SCEVConstant>(Op))
15532 SCEVUsers[Op].insert(User);
15533}
15534
15536 const SCEV *Expr = SE.getSCEV(V);
15537 return getPredicatedSCEV(Expr);
15538}
15539
15541 RewriteEntry &Entry = RewriteMap[Expr];
15542
15543 // If we already have an entry and the version matches, return it.
15544 if (Entry.second && Generation == Entry.first)
15545 return Entry.second;
15546
15547 // We found an entry but it's stale. Rewrite the stale entry
15548 // according to the current predicate.
15549 if (Entry.second)
15550 Expr = Entry.second;
15551
15552 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15553 Entry = {Generation, NewSCEV};
15554
15555 return NewSCEV;
15556}
15557
15559 if (!BackedgeCount) {
15561 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15562 for (const auto *P : Preds)
15563 addPredicate(*P);
15564 }
15565 return BackedgeCount;
15566}
15567
15569 if (!SymbolicMaxBackedgeCount) {
15571 SymbolicMaxBackedgeCount =
15572 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15573 for (const auto *P : Preds)
15574 addPredicate(*P);
15575 }
15576 return SymbolicMaxBackedgeCount;
15577}
15578
15580 if (!SmallConstantMaxTripCount) {
15582 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15583 for (const auto *P : Preds)
15584 addPredicate(*P);
15585 }
15586 return *SmallConstantMaxTripCount;
15587}
15588
15590 if (Preds->implies(&Pred, SE))
15591 return;
15592
15593 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15594 NewPreds.push_back(&Pred);
15595 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15596 updateGeneration();
15597}
15598
15601 for (const SCEVPredicate *P : Preds)
15602 addPredicate(*P);
15603}
15604
15606 return *Preds;
15607}
15608
15609void PredicatedScalarEvolution::updateGeneration() {
15610 // If the generation number wrapped recompute everything.
15611 if (++Generation == 0) {
15612 for (auto &II : RewriteMap) {
15613 const SCEV *Rewritten = II.second.second;
15614 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15615 }
15616 }
15617}
15618
15621 const SCEV *Expr = this->getSCEV(V);
15623 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15624
15625 if (!New)
15626 return nullptr;
15627
15628 if (ExtraPreds) {
15629 ExtraPreds->append(NewPreds);
15630 return New;
15631 }
15632
15633 addPredicates(NewPreds);
15634
15635 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15636 return New;
15637}
15638
15641 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15642 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15643 SE)),
15644 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15645
15647 // For each block.
15648 for (auto *BB : L.getBlocks())
15649 for (auto &I : *BB) {
15650 if (!SE.isSCEVable(I.getType()))
15651 continue;
15652
15653 auto *Expr = SE.getSCEV(&I);
15654 auto II = RewriteMap.find(Expr);
15655
15656 if (II == RewriteMap.end())
15657 continue;
15658
15659 // Don't print things that are not interesting.
15660 if (II->second.second == Expr)
15661 continue;
15662
15663 OS.indent(Depth) << "[PSE]" << I << ":\n";
15664 OS.indent(Depth + 2) << *Expr << "\n";
15665 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15666 }
15667}
15668
15671 BasicBlock *Header = L->getHeader();
15672 BasicBlock *Pred = L->getLoopPredecessor();
15673 LoopGuards Guards(SE);
15674 if (!Pred)
15675 return Guards;
15677 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15678 return Guards;
15679}
15680
15681void ScalarEvolution::LoopGuards::collectFromPHI(
15685 unsigned Depth) {
15686 if (!SE.isSCEVable(Phi.getType()))
15687 return;
15688
15689 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15690 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15691 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15692 if (!VisitedBlocks.insert(InBlock).second)
15693 return {nullptr, scCouldNotCompute};
15694
15695 // Avoid analyzing unreachable blocks so that we don't get trapped
15696 // traversing cycles with ill-formed dominance or infinite cycles
15697 if (!SE.DT.isReachableFromEntry(InBlock))
15698 return {nullptr, scCouldNotCompute};
15699
15700 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15701 if (Inserted)
15702 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15703 Depth + 1);
15704 auto &RewriteMap = G->second.RewriteMap;
15705 if (RewriteMap.empty())
15706 return {nullptr, scCouldNotCompute};
15707 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15708 if (S == RewriteMap.end())
15709 return {nullptr, scCouldNotCompute};
15710 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15711 if (!SM)
15712 return {nullptr, scCouldNotCompute};
15713 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15714 return {C0, SM->getSCEVType()};
15715 return {nullptr, scCouldNotCompute};
15716 };
15717 auto MergeMinMaxConst = [](MinMaxPattern P1,
15718 MinMaxPattern P2) -> MinMaxPattern {
15719 auto [C1, T1] = P1;
15720 auto [C2, T2] = P2;
15721 if (!C1 || !C2 || T1 != T2)
15722 return {nullptr, scCouldNotCompute};
15723 switch (T1) {
15724 case scUMaxExpr:
15725 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15726 case scSMaxExpr:
15727 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15728 case scUMinExpr:
15729 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15730 case scSMinExpr:
15731 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15732 default:
15733 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15734 }
15735 };
15736 auto P = GetMinMaxConst(0);
15737 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15738 if (!P.first)
15739 break;
15740 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15741 }
15742 if (P.first) {
15743 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15744 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15745 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15746 Guards.RewriteMap.insert({LHS, RHS});
15747 }
15748}
15749
15750// Return a new SCEV that modifies \p Expr to the closest number divides by
15751// \p Divisor and less or equal than Expr. For now, only handle constant
15752// Expr.
15754 const APInt &DivisorVal,
15755 ScalarEvolution &SE) {
15756 const APInt *ExprVal;
15757 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15758 DivisorVal.isNonPositive())
15759 return Expr;
15760 APInt Rem = ExprVal->urem(DivisorVal);
15761 // return the SCEV: Expr - Expr % Divisor
15762 return SE.getConstant(*ExprVal - Rem);
15763}
15764
15765// Return a new SCEV that modifies \p Expr to the closest number divides by
15766// \p Divisor and greater or equal than Expr. For now, only handle constant
15767// Expr.
15768static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15769 const APInt &DivisorVal,
15770 ScalarEvolution &SE) {
15771 const APInt *ExprVal;
15772 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15773 DivisorVal.isNonPositive())
15774 return Expr;
15775 APInt Rem = ExprVal->urem(DivisorVal);
15776 if (Rem.isZero())
15777 return Expr;
15778 // return the SCEV: Expr + Divisor - Expr % Divisor
15779 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15780}
15781
15783 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15786 // If we have LHS == 0, check if LHS is computing a property of some unknown
15787 // SCEV %v which we can rewrite %v to express explicitly.
15789 return false;
15790 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15791 // explicitly express that.
15792 const SCEVUnknown *URemLHS = nullptr;
15793 const SCEV *URemRHS = nullptr;
15794 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15795 return false;
15796
15797 const SCEV *Multiple =
15798 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15799 DivInfo[URemLHS] = Multiple;
15800 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15801 Multiples[URemLHS] = C->getAPInt();
15802 return true;
15803}
15804
15805// Check if the condition is a divisibility guard (A % B == 0).
15806static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15807 ScalarEvolution &SE) {
15808 const SCEV *X, *Y;
15809 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15810}
15811
15812// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15813// recursively. This is done by aligning up/down the constant value to the
15814// Divisor.
15815static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15816 APInt Divisor,
15817 ScalarEvolution &SE) {
15818 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15819 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15820 // the non-constant operand and in \p LHS the constant operand.
15821 auto IsMinMaxSCEVWithNonNegativeConstant =
15822 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15823 const SCEV *&RHS) {
15824 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15825 if (MinMax->getNumOperands() != 2)
15826 return false;
15827 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15828 if (C->getAPInt().isNegative())
15829 return false;
15830 SCTy = MinMax->getSCEVType();
15831 LHS = MinMax->getOperand(0);
15832 RHS = MinMax->getOperand(1);
15833 return true;
15834 }
15835 }
15836 return false;
15837 };
15838
15839 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15840 SCEVTypes SCTy;
15841 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15842 MinMaxRHS))
15843 return MinMaxExpr;
15844 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15845 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15846 auto *DivisibleExpr =
15847 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15848 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15850 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15851 return SE.getMinMaxExpr(SCTy, Ops);
15852}
15853
15854void ScalarEvolution::LoopGuards::collectFromBlock(
15855 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15856 const BasicBlock *Block, const BasicBlock *Pred,
15857 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15858
15860
15861 SmallVector<SCEVUse> ExprsToRewrite;
15862 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15863 const SCEV *RHS,
15864 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15865 const LoopGuards &DivGuards) {
15866 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15867 // replacement SCEV which isn't directly implied by the structure of that
15868 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15869 // legal. See the scoping rules for flags in the header to understand why.
15870
15871 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15872 // and \p FromRewritten are the same (i.e. there has been no rewrite
15873 // registered for \p From), then puts this value in the list of rewritten
15874 // expressions.
15875 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15876 const SCEV *To) {
15877 if (From == FromRewritten)
15878 ExprsToRewrite.push_back(From);
15879 RewriteMap[From] = To;
15880 };
15881
15882 // Checks whether \p S has already been rewritten. In that case returns the
15883 // existing rewrite because we want to chain further rewrites onto the
15884 // already rewritten value. Otherwise returns \p S.
15885 auto GetMaybeRewritten = [&](const SCEV *S) {
15886 return RewriteMap.lookup_or(S, S);
15887 };
15888
15889 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15890 // create this form when combining two checks of the form (X u< C2 + C1) and
15891 // (X >=u C1).
15892 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15893 const SCEV *MatchLHS,
15894 const SCEV *MatchRHS) {
15895 const SCEVConstant *C1;
15896 const SCEVUnknown *LHSUnknown;
15897 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15898 if (!match(MatchLHS,
15899 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15900 !C2)
15901 return false;
15902
15903 auto ExactRegion =
15904 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15905 .sub(C1->getAPInt());
15906
15907 // Tighten the raw range with what we already know about LHSUnknown
15908 // from prior guards recorded in RewriteMap, or from SCEV's own range
15909 // analysis.
15910 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15911 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15913
15914 // Bail if the guard is inconsistent with prior facts, or if the range
15915 // is still not a monotonic non-wrapping interval after tightening.
15916 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15917 ExactRegion.isFullSet())
15918 return false;
15919
15920 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15921 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15922 const SCEV *ClampedLHS =
15923 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15924 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15925 return true;
15926 };
15927 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15928 return;
15929
15930 // Do not apply information for constants or if RHS contains an AddRec.
15932 return;
15933
15934 // If RHS is SCEVUnknown, make sure the information is applied to it.
15936 std::swap(LHS, RHS);
15938 }
15939
15940 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15941 // Apply divisibility information when computing the constant multiple.
15942 const APInt &DividesBy =
15943 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15944
15945 // Collect rewrites for LHS and its transitive operands based on the
15946 // condition.
15947 // For min/max expressions, also apply the guard to its operands:
15948 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15949 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15950 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15951 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15952
15953 // We cannot express strict predicates in SCEV, so instead we replace them
15954 // with non-strict ones against plus or minus one of RHS depending on the
15955 // predicate.
15956 const SCEV *One = SE.getOne(RHS->getType());
15957 switch (Predicate) {
15958 case CmpInst::ICMP_ULT:
15959 if (RHS->getType()->isPointerTy())
15960 return;
15961 RHS = SE.getUMaxExpr(RHS, One);
15962 [[fallthrough]];
15963 case CmpInst::ICMP_SLT: {
15964 RHS = SE.getMinusSCEV(RHS, One);
15965 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15966 break;
15967 }
15968 case CmpInst::ICMP_UGT:
15969 case CmpInst::ICMP_SGT:
15970 RHS = SE.getAddExpr(RHS, One);
15971 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15972 break;
15973 case CmpInst::ICMP_ULE:
15974 case CmpInst::ICMP_SLE:
15975 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15976 break;
15977 case CmpInst::ICMP_UGE:
15978 case CmpInst::ICMP_SGE:
15979 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15980 break;
15981 default:
15982 break;
15983 }
15984
15985 SmallVector<SCEVUse, 16> Worklist(1, LHS);
15986 SmallPtrSet<const SCEV *, 16> Visited;
15987
15988 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
15989 append_range(Worklist, S->operands());
15990 };
15991
15992 while (!Worklist.empty()) {
15993 const SCEV *From = Worklist.pop_back_val();
15994 if (isa<SCEVConstant>(From))
15995 continue;
15996 if (!Visited.insert(From).second)
15997 continue;
15998 const SCEV *FromRewritten = GetMaybeRewritten(From);
15999 const SCEV *To = nullptr;
16000
16001 switch (Predicate) {
16002 case CmpInst::ICMP_ULT:
16003 case CmpInst::ICMP_ULE:
16004 To = SE.getUMinExpr(FromRewritten, RHS);
16005 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16006 EnqueueOperands(UMax);
16007 break;
16008 case CmpInst::ICMP_SLT:
16009 case CmpInst::ICMP_SLE:
16010 To = SE.getSMinExpr(FromRewritten, RHS);
16011 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16012 EnqueueOperands(SMax);
16013 break;
16014 case CmpInst::ICMP_UGT:
16015 case CmpInst::ICMP_UGE:
16016 To = SE.getUMaxExpr(FromRewritten, RHS);
16017 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16018 EnqueueOperands(UMin);
16019 break;
16020 case CmpInst::ICMP_SGT:
16021 case CmpInst::ICMP_SGE:
16022 To = SE.getSMaxExpr(FromRewritten, RHS);
16023 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16024 EnqueueOperands(SMin);
16025 break;
16026 case CmpInst::ICMP_EQ:
16028 To = RHS;
16029 break;
16030 case CmpInst::ICMP_NE:
16031 if (match(RHS, m_scev_Zero())) {
16032 const SCEV *OneAlignedUp =
16033 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16034 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16035 } else {
16036 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16037 // but creating the subtraction eagerly is expensive. Track the
16038 // inequalities in a separate map, and materialize the rewrite lazily
16039 // when encountering a suitable subtraction while re-writing.
16040 if (LHS->getType()->isPointerTy()) {
16041 LHS = SE.getPtrToAddrExpr(LHS);
16042 RHS = SE.getPtrToAddrExpr(RHS);
16044 break;
16045 }
16046 const SCEVConstant *C;
16047 const SCEV *A, *B;
16050 RHS = A;
16051 LHS = B;
16052 }
16053 if (LHS > RHS)
16054 std::swap(LHS, RHS);
16055 Guards.NotEqual.insert({LHS, RHS});
16056 continue;
16057 }
16058 break;
16059 default:
16060 break;
16061 }
16062
16063 if (To)
16064 AddRewrite(From, FromRewritten, To);
16065 }
16066 };
16067
16069 // First, collect information from assumptions dominating the loop.
16070 for (auto &AssumeVH : SE.AC.assumptions()) {
16071 if (!AssumeVH)
16072 continue;
16073 auto *AssumeI = cast<CallInst>(AssumeVH);
16074 if (!SE.DT.dominates(AssumeI, Block))
16075 continue;
16076 Terms.emplace_back(AssumeI->getOperand(0), true);
16077 }
16078
16079 // Second, collect information from llvm.experimental.guards dominating the loop.
16080 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16081 SE.F.getParent(), Intrinsic::experimental_guard);
16082 if (GuardDecl)
16083 for (const auto *GU : GuardDecl->users())
16084 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16085 if (Guard->getFunction() == Block->getParent() &&
16086 SE.DT.dominates(Guard, Block))
16087 Terms.emplace_back(Guard->getArgOperand(0), true);
16088
16089 // Third, collect conditions from dominating branches. Starting at the loop
16090 // predecessor, climb up the predecessor chain, as long as there are
16091 // predecessors that can be found that have unique successors leading to the
16092 // original header.
16093 // TODO: share this logic with isLoopEntryGuardedByCond.
16094 unsigned NumCollectedConditions = 0;
16096 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16097 for (; Pair.first;
16098 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16099 VisitedBlocks.insert(Pair.second);
16100 const CondBrInst *LoopEntryPredicate =
16101 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16102 if (!LoopEntryPredicate)
16103 continue;
16104
16105 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16106 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16107 NumCollectedConditions++;
16108
16109 // If we are recursively collecting guards stop after 2
16110 // conditions to limit compile-time impact for now.
16111 if (Depth > 0 && NumCollectedConditions == 2)
16112 break;
16113 }
16114 // Finally, if we stopped climbing the predecessor chain because
16115 // there wasn't a unique one to continue, try to collect conditions
16116 // for PHINodes by recursively following all of their incoming
16117 // blocks and try to merge the found conditions to build a new one
16118 // for the Phi.
16119 if (Pair.second->hasNPredecessorsOrMore(2) &&
16121 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16122 for (auto &Phi : Pair.second->phis())
16123 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16124 }
16125
16126 // Now apply the information from the collected conditions to
16127 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16128 // earliest conditions is processed first, except guards with divisibility
16129 // information, which are moved to the back. This ensures the SCEVs with the
16130 // shortest dependency chains are constructed first.
16132 GuardsToProcess;
16133 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16134 SmallVector<Value *, 8> Worklist;
16135 SmallPtrSet<Value *, 8> Visited;
16136 Worklist.push_back(Term);
16137 while (!Worklist.empty()) {
16138 Value *Cond = Worklist.pop_back_val();
16139 if (!Visited.insert(Cond).second)
16140 continue;
16141
16142 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16143 auto Predicate =
16144 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16145 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16146 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16147 // If LHS is a constant, apply information to the other expression.
16148 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16149 // can improve results.
16150 if (isa<SCEVConstant>(LHS)) {
16151 std::swap(LHS, RHS);
16153 }
16154 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16155 continue;
16156 }
16157
16158 Value *L, *R;
16159 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16160 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16161 Worklist.push_back(L);
16162 Worklist.push_back(R);
16163 }
16164 }
16165 }
16166
16167 // Process divisibility guards in reverse order to populate DivGuards early.
16168 DenseMap<const SCEV *, APInt> Multiples;
16169 LoopGuards DivGuards(SE);
16170 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16171 if (!isDivisibilityGuard(LHS, RHS, SE))
16172 continue;
16173 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16174 Multiples, SE);
16175 }
16176
16177 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16178 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16179
16180 // Apply divisibility information last. This ensures it is applied to the
16181 // outermost expression after other rewrites for the given value.
16182 for (const auto &[K, Divisor] : Multiples) {
16183 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16184 Guards.RewriteMap[K] =
16186 Guards.rewrite(K), Divisor, SE),
16187 DivisorSCEV),
16188 DivisorSCEV);
16189 ExprsToRewrite.push_back(K);
16190 }
16191
16192 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16193 // the replacement expressions are contained in the ranges of the replaced
16194 // expressions.
16195 Guards.PreserveNUW = true;
16196 Guards.PreserveNSW = true;
16197 for (const SCEV *Expr : ExprsToRewrite) {
16198 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16199 Guards.PreserveNUW &=
16200 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16201 Guards.PreserveNSW &=
16202 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16203 }
16204
16205 // Now that all rewrite information is collect, rewrite the collected
16206 // expressions with the information in the map. This applies information to
16207 // sub-expressions.
16208 if (ExprsToRewrite.size() > 1) {
16209 for (const SCEV *Expr : ExprsToRewrite) {
16210 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16211 Guards.RewriteMap.erase(Expr);
16212 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16213 }
16214 }
16215}
16216
16218 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16219 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16220 /// replacement is loop invariant in the loop of the AddRec.
16221 class SCEVLoopGuardRewriter
16222 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16225
16226 SCEVFlags FlagMask = SCEV::FlagNone;
16227
16228 public:
16229 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16230 const ScalarEvolution::LoopGuards &Guards)
16231 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16232 NotEqual(Guards.NotEqual) {
16233 if (Guards.PreserveNUW)
16234 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16235 if (Guards.PreserveNSW)
16236 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16237 }
16238
16239 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16240
16241 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16242 return Map.lookup_or(Expr, Expr);
16243 }
16244
16245 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16246 if (const SCEV *S = Map.lookup(Expr))
16247 return S;
16249 Expr);
16250 }
16251
16252 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16253 if (const SCEV *S = Map.lookup(Expr))
16254 return S;
16255
16256 // If we didn't find the extact ZExt expr in the map, check if there's
16257 // an entry for a smaller ZExt we can use instead.
16258 Type *Ty = Expr->getType();
16259 const SCEV *Op = Expr->getOperand(0);
16260 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16261 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16262 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16263 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16264 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16265 if (const SCEV *S = Map.lookup(NarrowExt))
16266 return SE.getZeroExtendExpr(S, Ty);
16267 Bitwidth = Bitwidth / 2;
16268 }
16269
16271 Expr);
16272 }
16273
16274 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16275 if (const SCEV *S = Map.lookup(Expr))
16276 return S;
16278 Expr);
16279 }
16280
16281 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16282 if (const SCEV *S = Map.lookup(Expr))
16283 return S;
16285 }
16286
16287 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16288 if (const SCEV *S = Map.lookup(Expr))
16289 return S;
16291 }
16292
16293 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16294 if (const SCEV *S = Map.lookup(Expr))
16295 return S;
16296
16297 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16298 // return UMax(S, 1).
16299 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16300 SCEVUse LHS, RHS;
16301 if (MatchBinarySub(S, LHS, RHS)) {
16302 if (LHS > RHS)
16303 std::swap(LHS, RHS);
16304 if (NotEqual.contains({LHS, RHS})) {
16305 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16306 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16307 return SE.getUMaxExpr(OneAlignedUp, S);
16308 }
16309 }
16310 return nullptr;
16311 };
16312
16313 // Check if Expr itself is a subtraction pattern with guard info.
16314 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16315 return Rewritten;
16316
16317 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16318 // (Const + A + B). There may be guard info for A + B, and if so, apply
16319 // it.
16320 // TODO: Could more generally apply guards to Add sub-expressions.
16321 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16322 if (Expr->getNumOperands() == 3) {
16323 const SCEV *Add =
16324 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16325 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16326 return SE.getAddExpr(
16327 Expr->getOperand(0), Rewritten,
16328 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16329 if (const SCEV *S = Map.lookup(Add))
16330 return SE.getAddExpr(Expr->getOperand(0), S);
16331 }
16332
16333 // For expressions of the form (Const + A), check if we have guard info
16334 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16335 // sure we don't lose information when rewriting expressions based on
16336 // back-edge taken counts in some cases.
16337 if (Expr->getNumOperands() == 2) {
16338 const SCEV *S = nullptr;
16339 // Handle (-1 + 1 + A) without constructing SCEVs.
16340 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16341 S = Map.lookup(Expr->getOperand(1));
16342 } else {
16343 const SCEV *NewC =
16344 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16345 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16346 }
16347 if (S)
16348 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16349 }
16350 }
16352 bool Changed = false;
16353 for (SCEVUse Op : Expr->operands()) {
16354 Operands.push_back(
16356 Changed |= Op != Operands.back();
16357 }
16358 // We are only replacing operands with equivalent values, so transfer the
16359 // flags from the original expression.
16360 return !Changed ? Expr
16361 : SE.getAddExpr(Operands,
16363 Expr->getNoWrapFlags(), FlagMask));
16364 }
16365
16366 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16368 bool Changed = false;
16369 for (SCEVUse Op : Expr->operands()) {
16370 Operands.push_back(
16372 Changed |= Op != Operands.back();
16373 }
16374 // We are only replacing operands with equivalent values, so transfer the
16375 // flags from the original expression.
16376 return !Changed ? Expr
16377 : SE.getMulExpr(Operands,
16379 Expr->getNoWrapFlags(), FlagMask));
16380 }
16381 };
16382
16383 if (RewriteMap.empty() && NotEqual.empty())
16384 return Expr;
16385
16386 SCEVLoopGuardRewriter Rewriter(SE, *this);
16387 return Rewriter.visit(Expr);
16388}
16389
16390const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16391 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16392}
16393
16395 const LoopGuards &Guards) {
16396 return Guards.rewrite(Expr);
16397}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
@ PostInc
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static bool IsKnownPredicateViaAddRecMonotonicity(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true because one of them is an AddRec that is known not to go below its own start val...
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L, const TargetLibraryInfo *TLI)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static bool canConstantFold(const Instruction *I, const TargetLibraryInfo *TLI)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, const TargetLibraryInfo *TLI, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static SCEVFlags getNoWrapFlagsForGEP(GEPOperator *GEP, const SCEV *Accum, ScalarEvolution &SE)
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, ScalarEvolution *SE, unsigned Depth)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static SCEVFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEVFlags Flags)
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS, SCEVUse RHS, DominatorTree &DT)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool canConstantEvolve(Instruction *I, const Loop *L, const TargetLibraryInfo *TLI)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CtxI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:469
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:758
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:763
bool empty() const
Definition DenseMap.h:717
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:679
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:794
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:780
void swap(DenseMapBase &RHS)
Definition DenseMap.h:978
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
void AddInteger(signed I)
Definition FoldingSet.h:190
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(SCEVFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
static constexpr auto FlagsNoWrapMask
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check that S is a multiple of M.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2850
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ BinaryOp
One of the operands is a binary op.
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:381
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
SCEVPtrT getPointer() const
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.