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-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
241static cl::opt<bool>
242 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
243 cl::desc("Handle <= and >= in finite loops"),
244 cl::init(true));
245
247 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
248 cl::desc("Infer nuw/nsw flags using context where suitable"),
249 cl::init(true));
250
251//===----------------------------------------------------------------------===//
252// SCEV class definitions
253//===----------------------------------------------------------------------===//
254
256 // Leaf nodes are always their own canonical.
257 switch (getSCEVType()) {
258 case scConstant:
259 case scVScale:
260 case scUnknown:
261 CanonicalSCEV = this;
262 return;
263 default:
264 break;
265 }
266
267 // For all other expressions, check whether any immediate operand has a
268 // different canonical. Since operands are always created before their parent,
269 // their canonical pointers are already set — no recursion needed.
270 bool Changed = false;
272 for (SCEVUse Op : operands()) {
273 CanonOps.push_back(Op->getCanonical());
274 Changed |= CanonOps.back() != Op;
275 }
276
277 if (!Changed) {
278 CanonicalSCEV = this;
279 return;
280 }
281
282 // Rebuild the expression from the canonical operands, stripping use flags.
283 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
284}
285
286//===----------------------------------------------------------------------===//
287// Implementation of the SCEV class.
288//
289
290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
292 print(dbgs());
293 dbgs() << '\n';
294}
295#endif
296
297void SCEV::print(raw_ostream &OS) const {
298 switch (getSCEVType()) {
299 case scConstant:
300 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
301 return;
302 case scVScale:
303 OS << "vscale";
304 return;
305 case scPtrToAddr: {
306 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
307 SCEVUse Op = PtrCast->getOperand();
308 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
309 << *PtrCast->getType() << ")";
310 return;
311 }
312 case scTruncate: {
313 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
314 SCEVUse Op = Trunc->getOperand();
315 OS << "(trunc " << *Op->getType() << " " << Op << " to "
316 << *Trunc->getType() << ")";
317 return;
318 }
319 case scZeroExtend: {
321 SCEVUse Op = ZExt->getOperand();
322 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
323 << ")";
324 return;
325 }
326 case scSignExtend: {
328 SCEVUse Op = SExt->getOperand();
329 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
330 << ")";
331 return;
332 }
333 case scAddRecExpr: {
334 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
335 OS << "{" << AR->getOperand(0);
336 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
337 OS << ",+," << AR->getOperand(i);
338 OS << "}<";
339 if (AR->hasNoUnsignedWrap())
340 OS << "nuw><";
341 if (AR->hasNoSignedWrap())
342 OS << "nsw><";
343 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
344 !AR->hasNoSignedWrap())
345 OS << "nw><";
346 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
347 OS << ">";
348 return;
349 }
350 case scAddExpr:
351 case scMulExpr:
352 case scUMaxExpr:
353 case scSMaxExpr:
354 case scUMinExpr:
355 case scSMinExpr:
357 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
358 const char *OpStr = nullptr;
359 switch (NAry->getSCEVType()) {
360 case scAddExpr: OpStr = " + "; break;
361 case scMulExpr: OpStr = " * "; break;
362 case scUMaxExpr: OpStr = " umax "; break;
363 case scSMaxExpr: OpStr = " smax "; break;
364 case scUMinExpr:
365 OpStr = " umin ";
366 break;
367 case scSMinExpr:
368 OpStr = " smin ";
369 break;
371 OpStr = " umin_seq ";
372 break;
373 default:
374 llvm_unreachable("There are no other nary expression types.");
375 }
376 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
377 switch (NAry->getSCEVType()) {
378 case scAddExpr:
379 case scMulExpr:
380 if (NAry->hasNoUnsignedWrap())
381 OS << "<nuw>";
382 if (NAry->hasNoSignedWrap())
383 OS << "<nsw>";
384 break;
385 default:
386 // Nothing to print for other nary expressions.
387 break;
388 }
389 return;
390 }
391 case scUDivExpr: {
392 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
393 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
394 return;
395 }
396 case scUnknown:
397 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
398 return;
400 OS << "***COULDNOTCOMPUTE***";
401 return;
402 }
403 llvm_unreachable("Unknown SCEV kind!");
404}
405
407 switch (getSCEVType()) {
408 case scConstant:
409 case scVScale:
410 case scUnknown:
411 return {};
412 case scPtrToAddr:
413 case scTruncate:
414 case scZeroExtend:
415 case scSignExtend:
416 return cast<SCEVCastExpr>(this)->operands();
417 case scAddRecExpr:
418 case scAddExpr:
419 case scMulExpr:
420 case scUMaxExpr:
421 case scSMaxExpr:
422 case scUMinExpr:
423 case scSMinExpr:
425 return cast<SCEVNAryExpr>(this)->operands();
426 case scUDivExpr:
427 return cast<SCEVUDivExpr>(this)->operands();
429 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
430 }
431 llvm_unreachable("Unknown SCEV kind!");
432}
433
434bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
435
436bool SCEV::isOne() const { return match(this, m_scev_One()); }
437
438bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
439
442 if (!Mul) return false;
443
444 // If there is a constant factor, it will be first.
445 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
446 if (!SC) return false;
447
448 // Return true if the value is negative, this matches things like (-42 * V).
449 return SC->getAPInt().isNegative();
450}
451
454
456 return S->getSCEVType() == scCouldNotCompute;
457}
458
460 auto &Entry = ConstantSCEVs[V];
461 if (Entry)
462 return Entry;
463
466 ID.AddPointer(V);
468 if (SCEVConstant *S =
469 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
470 return Entry = S;
471 SCEVConstant *S =
472 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
473 UniqueSCEVs.insert(S, Token);
474 S->computeAndSetCanonical(*this);
475 return Entry = S;
476}
477
479 return getConstant(ConstantInt::get(getContext(), Val));
480}
481
482const SCEV *
485 // TODO: Avoid implicit trunc?
486 // See https://github.com/llvm/llvm-project/issues/112510.
487 return getConstant(
488 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
489}
490
494 ID.AddPointer(Ty);
496 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
497 return S;
498 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
499 UniqueSCEVs.insert(S, Token);
500 S->computeAndSetCanonical(*this);
501 return S;
502}
503
505 SCEV::NoWrapFlags Flags) {
506 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
507 if (EC.isScalable())
508 Res = getMulExpr(Res, getVScale(Ty), Flags);
509 return Res;
510}
511
513 SCEVUse op, Type *ty)
514 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
515
516SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
517 const SCEV *Op, Type *ITy)
518 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
519 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
520 "Must be a non-bit-width-changing pointer-to-integer cast!");
521}
522
527
528SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
529 Type *ty)
531 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
532 "Cannot truncate non-integer value!");
533}
534
535SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
536 Type *ty)
538 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
539 "Cannot zero extend non-integer value!");
540}
541
542SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
543 Type *ty)
545 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
546 "Cannot sign extend non-integer value!");
547}
548
550 // Clear this SCEVUnknown from various maps.
551 SE->forgetMemoizedResults({this});
552
553 // Remove this SCEVUnknown from the uniquing map.
554 SE->UniqueSCEVs.erase(this);
555
556 // Release the value.
557 setValPtr(nullptr);
558}
559
560void SCEVUnknown::allUsesReplacedWith(Value *New) {
561 // Clear this SCEVUnknown from various maps.
562 SE->forgetMemoizedResults({this});
563
564 // Remove this SCEVUnknown from the uniquing map.
565 SE->UniqueSCEVs.erase(this);
566
567 // Replace the value pointer in case someone is still using this SCEVUnknown.
568 setValPtr(New);
569}
570
571//===----------------------------------------------------------------------===//
572// SCEV Utilities
573//===----------------------------------------------------------------------===//
574
575/// Compare the two values \p LV and \p RV in terms of their "complexity" where
576/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
577/// operands in SCEV expressions.
578static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
579 Value *RV, unsigned Depth) {
581 return 0;
582
583 // Order pointer values after integer values. This helps SCEVExpander form
584 // GEPs.
585 bool LIsPointer = LV->getType()->isPointerTy(),
586 RIsPointer = RV->getType()->isPointerTy();
587 if (LIsPointer != RIsPointer)
588 return (int)LIsPointer - (int)RIsPointer;
589
590 // Compare getValueID values.
591 unsigned LID = LV->getValueID(), RID = RV->getValueID();
592 if (LID != RID)
593 return (int)LID - (int)RID;
594
595 // Sort arguments by their position.
596 if (const auto *LA = dyn_cast<Argument>(LV)) {
597 const auto *RA = cast<Argument>(RV);
598 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
599 return (int)LArgNo - (int)RArgNo;
600 }
601
602 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
603 const auto *RGV = cast<GlobalValue>(RV);
604
605 if (auto L = LGV->getLinkage() - RGV->getLinkage())
606 return L;
607
608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
609 auto LT = GV->getLinkage();
610 return !(GlobalValue::isPrivateLinkage(LT) ||
612 };
613
614 // Use the names to distinguish the two values, but only if the
615 // names are semantically important.
616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
617 return LGV->getName().compare(RGV->getName());
618 }
619
620 // For instructions, compare their loop depth, and their operand count. This
621 // is pretty loose.
622 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
623 const auto *RInst = cast<Instruction>(RV);
624
625 // Compare loop depths.
626 const BasicBlock *LParent = LInst->getParent(),
627 *RParent = RInst->getParent();
628 if (LParent != RParent) {
629 unsigned LDepth = LI->getLoopDepth(LParent),
630 RDepth = LI->getLoopDepth(RParent);
631 if (LDepth != RDepth)
632 return (int)LDepth - (int)RDepth;
633 }
634
635 // Compare the number of operands.
636 unsigned LNumOps = LInst->getNumOperands(),
637 RNumOps = RInst->getNumOperands();
638 if (LNumOps != RNumOps)
639 return (int)LNumOps - (int)RNumOps;
640
641 for (unsigned Idx : seq(LNumOps)) {
642 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
643 RInst->getOperand(Idx), Depth + 1);
644 if (Result != 0)
645 return Result;
646 }
647 }
648
649 return 0;
650}
651
652// Return negative, zero, or positive, if LHS is less than, equal to, or greater
653// than RHS, respectively. A three-way result allows recursive comparisons to be
654// more efficient.
655// If the max analysis depth was reached, return std::nullopt, assuming we do
656// not know if they are equivalent for sure.
657static std::optional<int>
658CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
659 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
660 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
661 if (LHS == RHS)
662 return 0;
663
664 // Primarily, sort the SCEVs by their getSCEVType().
665 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
666 if (LType != RType)
667 return (int)LType - (int)RType;
668
670 return std::nullopt;
671
672 // Aside from the getSCEVType() ordering, the particular ordering
673 // isn't very important except that it's beneficial to be consistent,
674 // so that (a + b) and (b + a) don't end up as different expressions.
675 switch (LType) {
676 case scUnknown: {
677 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
678 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
679
680 int X =
681 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
682 return X;
683 }
684
685 case scConstant: {
688
689 // Compare constant values.
690 const APInt &LA = LC->getAPInt();
691 const APInt &RA = RC->getAPInt();
692 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
693 if (LBitWidth != RBitWidth)
694 return (int)LBitWidth - (int)RBitWidth;
695 return LA.ult(RA) ? -1 : 1;
696 }
697
698 case scVScale: {
699 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
700 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
701 return LTy->getBitWidth() - RTy->getBitWidth();
702 }
703
704 case scAddRecExpr: {
707
708 // There is always a dominance between two recs that are used by one SCEV,
709 // so we can safely sort recs by loop header dominance. We require such
710 // order in getAddExpr.
711 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
712 if (LLoop != RLoop) {
713 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
714 assert(LHead != RHead && "Two loops share the same header?");
715 if (DT.dominates(LHead, RHead))
716 return 1;
717 assert(DT.dominates(RHead, LHead) &&
718 "No dominance between recurrences used by one SCEV?");
719 return -1;
720 }
721
722 [[fallthrough]];
723 }
724
725 case scTruncate:
726 case scZeroExtend:
727 case scSignExtend:
728 case scPtrToAddr:
729 case scAddExpr:
730 case scMulExpr:
731 case scUDivExpr:
732 case scSMaxExpr:
733 case scUMaxExpr:
734 case scSMinExpr:
735 case scUMinExpr:
737 ArrayRef<SCEVUse> LOps = LHS->operands();
738 ArrayRef<SCEVUse> ROps = RHS->operands();
739
740 // Lexicographically compare n-ary-like expressions.
741 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
742 if (LNumOps != RNumOps)
743 return (int)LNumOps - (int)RNumOps;
744
745 for (unsigned i = 0; i != LNumOps; ++i) {
746 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
747 ROps[i].getPointer(), DT, Depth + 1);
748 if (X != 0)
749 return X;
750 }
751 return 0;
752 }
753
755 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
756 }
757 llvm_unreachable("Unknown SCEV kind!");
758}
759
760/// Given a list of SCEV objects, order them by their complexity, and group
761/// objects of the same complexity together by value. When this routine is
762/// finished, we know that any duplicates in the vector are consecutive and that
763/// complexity is monotonically increasing.
764///
765/// Note that we go take special precautions to ensure that we get deterministic
766/// results from this routine. In other words, we don't want the results of
767/// this to depend on where the addresses of various SCEV objects happened to
768/// land in memory.
770 DominatorTree &DT) {
771 if (Ops.size() < 2) return; // Noop
772
773 // Whether LHS has provably less complexity than RHS.
774 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
775 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
776 return Complexity && *Complexity < 0;
777 };
778 if (Ops.size() == 2) {
779 // This is the common case, which also happens to be trivially simple.
780 // Special case it.
781 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
782 if (IsLessComplex(RHS, LHS))
783 std::swap(LHS, RHS);
784 return;
785 }
786
787 // Do the rough sort by complexity.
789 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
790
791 // Now that we are sorted by complexity, group elements of the same
792 // complexity. Note that this is, at worst, N^2, but the vector is likely to
793 // be extremely short in practice. Note that we take this approach because we
794 // do not want to depend on the addresses of the objects we are grouping.
795 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
796 const SCEV *S = Ops[i];
797 unsigned Complexity = S->getSCEVType();
798
799 // If there are any objects of the same complexity and same value as this
800 // one, group them.
801 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
802 if (Ops[j] == S) { // Found a duplicate.
803 // Move it to immediately after i'th element.
804 std::swap(Ops[i+1], Ops[j]);
805 ++i; // no need to rescan it.
806 if (i == e-2) return; // Done!
807 }
808 }
809 }
810}
811
812/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
813/// least HugeExprThreshold nodes).
815 return any_of(Ops, [](const SCEV *S) {
817 });
818}
819
820/// Performs a number of common optimizations on the passed \p Ops. If the
821/// whole expression reduces down to a single operand, it will be returned.
822///
823/// The following optimizations are performed:
824/// * Fold constants using the \p Fold function.
825/// * Remove identity constants satisfying \p IsIdentity.
826/// * If a constant satisfies \p IsAbsorber, return it.
827/// * Sort operands by complexity.
828template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
829static const SCEV *
831 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
832 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
833 const SCEVConstant *Folded = nullptr;
834 for (unsigned Idx = 0; Idx < Ops.size();) {
835 const SCEV *Op = Ops[Idx];
836 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
837 if (!Folded)
838 Folded = C;
839 else
840 Folded = cast<SCEVConstant>(
841 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
842 Ops.erase(Ops.begin() + Idx);
843 continue;
844 }
845 ++Idx;
846 }
847
848 if (Ops.empty()) {
849 assert(Folded && "Must have folded value");
850 return Folded;
851 }
852
853 if (Folded && IsAbsorber(Folded->getAPInt()))
854 return Folded;
855
856 GroupByComplexity(Ops, &LI, DT);
857 if (Folded && !IsIdentity(Folded->getAPInt()))
858 Ops.insert(Ops.begin(), Folded);
859
860 return Ops.size() == 1 ? Ops[0] : nullptr;
861}
862
863//===----------------------------------------------------------------------===//
864// Simple SCEV method implementations
865//===----------------------------------------------------------------------===//
866
867/// Compute BC(It, K). The result has width W. Assume, K > 0.
868static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
869 ScalarEvolution &SE,
870 Type *ResultTy) {
871 // Handle the simplest case efficiently.
872 if (K == 1)
873 return SE.getTruncateOrZeroExtend(It, ResultTy);
874
875 // We are using the following formula for BC(It, K):
876 //
877 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
878 //
879 // Suppose, W is the bitwidth of the return value. We must be prepared for
880 // overflow. Hence, we must assure that the result of our computation is
881 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
882 // safe in modular arithmetic.
883 //
884 // However, this code doesn't use exactly that formula; the formula it uses
885 // is something like the following, where T is the number of factors of 2 in
886 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
887 // exponentiation:
888 //
889 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
890 //
891 // This formula is trivially equivalent to the previous formula. However,
892 // this formula can be implemented much more efficiently. The trick is that
893 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
894 // arithmetic. To do exact division in modular arithmetic, all we have
895 // to do is multiply by the inverse. Therefore, this step can be done at
896 // width W.
897 //
898 // The next issue is how to safely do the division by 2^T. The way this
899 // is done is by doing the multiplication step at a width of at least W + T
900 // bits. This way, the bottom W+T bits of the product are accurate. Then,
901 // when we perform the division by 2^T (which is equivalent to a right shift
902 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
903 // truncated out after the division by 2^T.
904 //
905 // In comparison to just directly using the first formula, this technique
906 // is much more efficient; using the first formula requires W * K bits,
907 // but this formula less than W + K bits. Also, the first formula requires
908 // a division step, whereas this formula only requires multiplies and shifts.
909 //
910 // It doesn't matter whether the subtraction step is done in the calculation
911 // width or the input iteration count's width; if the subtraction overflows,
912 // the result must be zero anyway. We prefer here to do it in the width of
913 // the induction variable because it helps a lot for certain cases; CodeGen
914 // isn't smart enough to ignore the overflow, which leads to much less
915 // efficient code if the width of the subtraction is wider than the native
916 // register width.
917 //
918 // (It's possible to not widen at all by pulling out factors of 2 before
919 // the multiplication; for example, K=2 can be calculated as
920 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
921 // extra arithmetic, so it's not an obvious win, and it gets
922 // much more complicated for K > 3.)
923
924 // Protection from insane SCEVs; this bound is conservative,
925 // but it probably doesn't matter.
926 if (K > 1000)
927 return SE.getCouldNotCompute();
928
929 unsigned W = SE.getTypeSizeInBits(ResultTy);
930
931 // Calculate K! / 2^T and T; we divide out the factors of two before
932 // multiplying for calculating K! / 2^T to avoid overflow.
933 // Other overflow doesn't matter because we only care about the bottom
934 // W bits of the result.
935 APInt OddFactorial(W, 1);
936 unsigned T = 1;
937 for (unsigned i = 3; i <= K; ++i) {
938 unsigned TwoFactors = countr_zero(i);
939 T += TwoFactors;
940 OddFactorial *= (i >> TwoFactors);
941 }
942
943 // We need at least W + T bits for the multiplication step
944 unsigned CalculationBits = W + T;
945
946 // Calculate 2^T, at width T+W.
947 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
948
949 // Calculate the multiplicative inverse of K! / 2^T;
950 // this multiplication factor will perform the exact division by
951 // K! / 2^T.
952 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
953
954 // Calculate the product, at width T+W
955 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
956 CalculationBits);
957 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
958 for (unsigned i = 1; i != K; ++i) {
959 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
960 Dividend = SE.getMulExpr(Dividend,
961 SE.getTruncateOrZeroExtend(S, CalculationTy));
962 }
963
964 // Divide by 2^T
965 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
966
967 // Truncate the result, and divide by K! / 2^T.
968
969 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
970 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
971}
972
973/// Attach \p UseFlags to \p Res as use-specific flags, but only if \p Res
974/// really is the two-operand \p ExprT over \p LHS and \p RHS - in either order,
975/// as operands get sorted by complexity.
976///
977/// Flags established for that operation say nothing about any other expression:
978/// a folded-away operand, a flattened nested expression or a distributed
979/// constant all give a different computation. They must not be attached to it,
980/// because an n-ary expression's no-wrap flags have to hold for all subsets and
981/// orders of its operands, and SCEVExpander relies on that when it stamps them
982/// on every partial sum or product it builds.
983template <typename ExprT>
985 SCEVUse RHS,
986 SCEV::NoWrapFlags UseFlags) {
987 auto *E = dyn_cast<ExprT>(Res);
988 if (E && (equal(E->operands(), ArrayRef<SCEVUse>({LHS, RHS})) ||
989 equal(E->operands(), ArrayRef<SCEVUse>({RHS, LHS}))))
990 return {Res, UseFlags};
991 return Res;
992}
993
994/// Return the value of this chain of recurrences at the specified iteration
995/// number. We can evaluate this recurrence by multiplying each element in the
996/// chain by the binomial coefficient corresponding to it. In other words, we
997/// can evaluate {A,+,B,+,C,+,D} as:
998///
999/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1000///
1001/// where BC(It, k) stands for binomial coefficient.
1003 ScalarEvolution &SE) const {
1004 return evaluateAtIteration(operands(), It, SE);
1005}
1006
1008 const SCEV *It, ScalarEvolution &SE,
1009 SCEV::NoWrapFlags UseFlags) {
1010 assert(Operands.size() > 0);
1011 assert((Operands.size() == 2 || UseFlags == SCEV::FlagAnyWrap) &&
1012 "use-specific flags only supported for affine AddRecs");
1013 SCEVUse Result = Operands[0].getPointer();
1014 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1015 // The computation is correct in the face of overflow provided that the
1016 // multiplication is performed _after_ the evaluation of the binomial
1017 // coefficient.
1018 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1019 if (isa<SCEVCouldNotCompute>(Coeff))
1020 return Coeff;
1021
1022 const SCEV *Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff);
1024 Result, Mul, UseFlags);
1025 }
1026 return Result;
1027}
1028
1030 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
1031 if (isa<SCEVCouldNotCompute>(BTC))
1032 return BTC;
1033 // The loop reaches iteration BTC, so the value this recurrence computes there
1034 // is the value it had, and that did not wrap.
1035 return evaluateAtIteration(operands(), BTC, SE,
1038}
1039
1040//===----------------------------------------------------------------------===//
1041// SCEV Expression folder implementations
1042//===----------------------------------------------------------------------===//
1043
1044/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1045/// which computes a pointer-typed value, and rewrites the whole expression
1046/// tree so that *all* the computations are done on integers, and the only
1047/// pointer-typed operands in the expression are SCEVUnknown.
1048/// The CreatePtrCast callback is invoked to create the actual conversion
1049/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1051 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1053 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1054 Type *TargetTy;
1055 ConversionFn CreatePtrCast;
1056
1057public:
1059 ConversionFn CreatePtrCast)
1060 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1061
1062 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1063 Type *TargetTy, ConversionFn CreatePtrCast) {
1064 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1065 return Rewriter.visit(Scev);
1066 }
1067
1068 const SCEV *visit(const SCEV *S) {
1069 Type *STy = S->getType();
1070 // If the expression is not pointer-typed, just keep it as-is.
1071 if (!STy->isPointerTy())
1072 return S;
1073 // Else, recursively sink the cast down into it.
1074 return Base::visit(S);
1075 }
1076
1077 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1078 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1079 // implementation drops.
1081 bool Changed = false;
1082 for (SCEVUse Op : Expr->operands()) {
1083 Operands.push_back(visit(Op.getPointer()));
1084 Changed |= Op.getPointer() != Operands.back();
1085 }
1086 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1087 }
1088
1089 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1090 assert(Expr->getType()->isPointerTy() &&
1091 "Should only reach pointer-typed SCEVUnknown's.");
1092 // Perform some basic constant folding. If the operand of the cast is a
1093 // null pointer, don't create a cast SCEV expression (that will be left
1094 // as-is), but produce a zero constant.
1096 return SE.getZero(TargetTy);
1097 return CreatePtrCast(Expr);
1098 }
1099};
1100
1102 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1103
1104 // Treat pointers with unstable representation conservatively, since the
1105 // address bits may change.
1106 if (DL.hasUnstableRepresentation(Op->getType()))
1107 return getCouldNotCompute();
1108
1109 Type *Ty = DL.getAddressType(Op->getType());
1110
1111 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1112 // The rewriter handles null pointer constant folding.
1114 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1117 ID.AddPointer(U);
1118 ID.AddPointer(Ty);
1120 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1121 return S;
1122 SCEV *S = new (SCEVAllocator)
1123 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1124 UniqueSCEVs.insert(S, Token);
1125 S->computeAndSetCanonical(*this);
1126 registerUser(S, U);
1127 return static_cast<const SCEV *>(S);
1128 });
1129 assert(IntOp->getType()->isIntegerTy() &&
1130 "We must have succeeded in sinking the cast, "
1131 "and ending up with an integer-typed expression!");
1132 return IntOp;
1133}
1134
1136 unsigned Depth) {
1137 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1138 "This is not a truncating conversion!");
1139 assert(isSCEVable(Ty) &&
1140 "This is not a conversion to a SCEVable type!");
1141 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1142 Ty = getEffectiveSCEVType(Ty);
1143
1146 ID.AddPointer(Op.getOpaqueValue());
1147 ID.AddPointer(Ty);
1149 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1150 return S;
1151
1152 // Fold if the operand is constant.
1153 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1154 return getConstant(
1155 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1156
1157 // trunc(trunc(x)) --> trunc(x)
1159 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1160
1161 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1163 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1164
1165 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1167 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1168
1169 if (Depth > MaxCastDepth) {
1170 SCEV *S =
1171 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1172 UniqueSCEVs.insert(S, Token);
1173 S->computeAndSetCanonical(*this);
1174 registerUser(S, Op);
1175 return S;
1176 }
1177
1178 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1179 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1180 // if after transforming we have at most one truncate, not counting truncates
1181 // that replace other casts.
1183 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1185 unsigned numTruncs = 0;
1186 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1187 ++i) {
1188 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1189 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1191 numTruncs++;
1192 Operands.push_back(S);
1193 }
1194 if (numTruncs < 2) {
1195 if (isa<SCEVAddExpr>(Op))
1196 return getAddExpr(Operands);
1197 if (isa<SCEVMulExpr>(Op))
1198 return getMulExpr(Operands);
1199 llvm_unreachable("Unexpected SCEV type for Op.");
1200 }
1201 // Although we checked in the beginning that ID is not in the cache, it is
1202 // possible that during recursion and different modification ID was inserted
1203 // into the cache. So if we find it, just return it.
1204 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1205 return S;
1206 }
1207
1208 // If the input value is a chrec scev, truncate the chrec's operands.
1209 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1211 for (const SCEV *Op : AddRec->operands())
1212 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1213 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1214 }
1215
1216 // Return zero if truncating to known zeros.
1217 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1218 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1219 return getZero(Ty);
1220
1221 // The cast wasn't folded; create an explicit cast node. We can reuse
1222 // the existing insert position since if we get here, we won't have
1223 // made any changes which would invalidate it.
1224 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1225 Op, Ty);
1226 UniqueSCEVs.insert(S, Token);
1227 S->computeAndSetCanonical(*this);
1228 registerUser(S, Op);
1229 return S;
1230}
1231
1232// Get the limit of a recurrence such that incrementing by Step cannot cause
1233// signed overflow as long as the value of the recurrence within the
1234// loop does not exceed this limit before incrementing.
1235static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1236 ICmpInst::Predicate *Pred,
1237 ScalarEvolution *SE) {
1238 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1239 if (SE->isKnownPositive(Step)) {
1240 *Pred = ICmpInst::ICMP_SLT;
1242 SE->getSignedRangeMax(Step));
1243 }
1244 if (SE->isKnownNegative(Step)) {
1245 *Pred = ICmpInst::ICMP_SGT;
1247 SE->getSignedRangeMin(Step));
1248 }
1249 return nullptr;
1250}
1251
1252// Get the limit of a recurrence such that incrementing by Step cannot cause
1253// unsigned overflow as long as the value of the recurrence within the loop does
1254// not exceed this limit before incrementing.
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1259 *Pred = ICmpInst::ICMP_ULT;
1260
1262 SE->getUnsignedRangeMax(Step));
1263}
1264
1265namespace {
1266
1267struct ExtendOpTraitsBase {
1268 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1269 unsigned);
1270};
1271
1272// Used to make code generic over signed and unsigned overflow.
1273template <typename ExtendOp> struct ExtendOpTraits {
1274 // Members present:
1275 //
1276 // static const SCEV::NoWrapFlags WrapType;
1277 //
1278 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1279 //
1280 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1281 // ICmpInst::Predicate *Pred,
1282 // ScalarEvolution *SE);
1283};
1284
1285template <>
1286struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1287 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1288
1289 static const GetExtendExprTy GetExtendExpr;
1290
1291 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1292 ICmpInst::Predicate *Pred,
1293 ScalarEvolution *SE) {
1294 return getSignedOverflowLimitForStep(Step, Pred, SE);
1295 }
1296};
1297
1298const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1300
1301template <>
1302struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1303 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1304
1305 static const GetExtendExprTy GetExtendExpr;
1306
1307 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1308 ICmpInst::Predicate *Pred,
1309 ScalarEvolution *SE) {
1310 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1311 }
1312};
1313
1314const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1316
1317} // end anonymous namespace
1318
1319// The recurrence AR has been shown to have no signed/unsigned wrap or something
1320// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1321// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1322// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1323// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1324// expression "Step + sext/zext(PreIncAR)" is congruent with
1325// "sext/zext(PostIncAR)"
1326template <typename ExtendOpTy>
1328 ScalarEvolution *SE, unsigned Depth) {
1329 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1330 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1331
1332 const Loop *L = AR->getLoop();
1333 const SCEV *Start = AR->getStart();
1334 const SCEV *Step = AR->getStepRecurrence(*SE);
1335
1336 // Check for a simple looking step prior to loop entry.
1337 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1338 if (!SA)
1339 return nullptr;
1340
1341 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1342 // subtraction is expensive. For this purpose, perform a quick and dirty
1343 // difference, by checking for Step in the operand list. Note, that
1344 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1345 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1346 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1347 if (*It == Step) {
1348 DiffOps.erase(It);
1349 break;
1350 }
1351
1352 if (DiffOps.size() == SA->getNumOperands())
1353 return nullptr;
1354
1355 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1356 // `Step`:
1357
1358 // 1. NSW/NUW flags on the step increment.
1359 auto PreStartFlags =
1361 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1363 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1364
1365 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1366 // "S+X does not sign/unsign-overflow".
1367 //
1368
1369 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1370 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1371 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1372 return PreStart;
1373
1374 // 2. Direct overflow check on the step operation's expression.
1375 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1376 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1377 const SCEV *OperandExtendedStart =
1378 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1379 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1380 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1381 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1382 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1383 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1384 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1385 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1386 }
1387 return PreStart;
1388 }
1389
1390 // 3. Loop precondition.
1392 const SCEV *OverflowLimit =
1393 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1394
1395 if (OverflowLimit &&
1396 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1397 return PreStart;
1398
1399 return nullptr;
1400}
1401
1402// Get the normalized zero or sign extended expression for this AddRec's Start.
1403template <typename ExtendOpTy>
1404static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1405 ScalarEvolution *SE,
1406 unsigned Depth) {
1407 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1408
1409 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1410 if (!PreStart)
1411 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1412
1413 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1414 Depth),
1415 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1416}
1417
1418// Try to prove away overflow by looking at "nearby" add recurrences. A
1419// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1420// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1421//
1422// Formally:
1423//
1424// {S,+,X} == {S-T,+,X} + T
1425// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1426//
1427// If ({S-T,+,X} + T) does not overflow ... (1)
1428//
1429// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1430//
1431// If {S-T,+,X} does not overflow ... (2)
1432//
1433// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1434// == {Ext(S-T)+Ext(T),+,Ext(X)}
1435//
1436// If (S-T)+T does not overflow ... (3)
1437//
1438// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1439// == {Ext(S),+,Ext(X)} == LHS
1440//
1441// Thus, if (1), (2) and (3) are true for some T, then
1442// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1443//
1444// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1445// does not overflow" restricted to the 0th iteration. Therefore we only need
1446// to check for (1) and (2).
1447//
1448// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1449// is `Delta` (defined below).
1450template <typename ExtendOpTy>
1451bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1452 const SCEV *Step,
1453 const Loop *L) {
1454 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1455
1456 // We restrict `Start` to a constant to prevent SCEV from spending too much
1457 // time here. It is correct (but more expensive) to continue with a
1458 // non-constant `Start` and do a general SCEV subtraction to compute
1459 // `PreStart` below.
1460 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1461 if (!StartC)
1462 return false;
1463
1464 APInt StartAI = StartC->getAPInt();
1465
1466 for (unsigned Delta : {-2, -1, 1, 2}) {
1467 const SCEV *PreStart = getConstant(StartAI - Delta);
1468
1469 FoldingSetNodeID ID;
1470 ID.AddInteger(scAddRecExpr);
1471 ID.AddPointer(PreStart);
1472 ID.AddPointer(Step);
1473 ID.AddPointer(L);
1474 FoldingSetInsertToken Token;
1475 const auto *PreAR =
1476 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
1477
1478 // Give up if we don't already have the add recurrence we need because
1479 // actually constructing an add recurrence is relatively expensive.
1480 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1481 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1483 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1484 DeltaS, &Pred, this);
1485 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1486 return true;
1487 }
1488 }
1489
1490 return false;
1491}
1492
1493// Finds an integer D for an expression (C + x + y + ...) such that the top
1494// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1495// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1496// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1497// the (C + x + y + ...) expression is \p WholeAddExpr.
1499 const SCEVConstant *ConstantTerm,
1500 const SCEVAddExpr *WholeAddExpr) {
1501 const APInt &C = ConstantTerm->getAPInt();
1502 const unsigned BitWidth = C.getBitWidth();
1503 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1504 uint32_t TZ = BitWidth;
1505 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1506 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1507 if (TZ) {
1508 // Set D to be as many least significant bits of C as possible while still
1509 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1510 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1511 }
1512 return APInt(BitWidth, 0);
1513}
1514
1515// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1516// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1517// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1518// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1520 const APInt &ConstantStart,
1521 const SCEV *Step) {
1522 const unsigned BitWidth = ConstantStart.getBitWidth();
1523 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1524 if (TZ)
1525 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1526 : ConstantStart;
1527 return APInt(BitWidth, 0);
1528}
1529
1531 const ScalarEvolution::FoldID &ID, const SCEV *S,
1534 &FoldCacheUser) {
1535 auto I = FoldCache.insert({ID, S});
1536 if (!I.second) {
1537 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1538 // entry.
1539 auto &UserIDs = FoldCacheUser[I.first->second];
1540 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1541 for (unsigned I = 0; I != UserIDs.size(); ++I)
1542 if (UserIDs[I] == ID) {
1543 std::swap(UserIDs[I], UserIDs.back());
1544 break;
1545 }
1546 UserIDs.pop_back();
1547 I.first->second = S;
1548 }
1549 FoldCacheUser[S].push_back(ID);
1550}
1551
1553 unsigned Depth) {
1554 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1555 "This is not an extending conversion!");
1556 assert(isSCEVable(Ty) &&
1557 "This is not a conversion to a SCEVable type!");
1558 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1559 Ty = getEffectiveSCEVType(Ty);
1560
1561 FoldID ID(scZeroExtend, Op, Ty);
1562 if (const SCEV *S = FoldCache.lookup(ID))
1563 return S;
1564
1565 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1567 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1568 return S;
1569}
1570
1572 unsigned Depth) {
1573 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1574 "This is not an extending conversion!");
1575 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1576 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1577
1578 // Fold if the operand is constant.
1579 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1580 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1581
1582 // zext(zext(x)) --> zext(x)
1584 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1585
1586 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1587 // zero-extension distributes over the recurrence.
1588 const SCEV *Start, *Step;
1589 const Loop *L;
1590 if (Depth <= MaxCastDepth &&
1591 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1592 const auto *AR = cast<SCEVAddRecExpr>(Op);
1593 if (AR->hasNoUnsignedWrap()) {
1594 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1595 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1596 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1597 }
1598 }
1599
1600 // Before doing any expensive analysis, check to see if we've already
1601 // computed a SCEV for this Op and Ty.
1604 ID.AddPointer(Op.getOpaqueValue());
1605 ID.AddPointer(Ty);
1607 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1608 return S;
1609 if (Depth > MaxCastDepth) {
1610 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1611 Op, Ty);
1612 UniqueSCEVs.insert(S, Token);
1613 S->computeAndSetCanonical(*this);
1614 registerUser(S, Op);
1615 return S;
1616 }
1617
1618 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1620 // It's possible the bits taken off by the truncate were all zero bits. If
1621 // so, we should be able to simplify this further.
1622 const SCEV *X = ST->getOperand();
1624 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1625 unsigned NewBits = getTypeSizeInBits(Ty);
1626 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1627 CR.zextOrTrunc(NewBits)))
1628 return getTruncateOrZeroExtend(X, Ty, Depth);
1629 }
1630
1631 // If the input value is a chrec scev, and we can prove that the value
1632 // did not overflow the old, smaller, value, we can zero extend all of the
1633 // operands (often constants). This allows analysis of something like
1634 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1635 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1636 const auto *AR = cast<SCEVAddRecExpr>(Op);
1637 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1638
1639 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1640
1641 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1642 // Note that this serves two purposes: It filters out loops that are
1643 // simply not analyzable, and it covers the case where this code is
1644 // being called from within backedge-taken count analysis, such that
1645 // attempting to ask for the backedge-taken count would likely result
1646 // in infinite recursion. In the later case, the analysis code will
1647 // cope with a conservative value, and it will take care to purge
1648 // that value once it has finished.
1649 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1650 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1651 // Manually compute the final value for AR, checking for overflow.
1652
1653 // Check whether the backedge-taken count can be losslessly casted to
1654 // the addrec's type. The count is always unsigned.
1655 const SCEV *CastedMaxBECount =
1656 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1657 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1658 CastedMaxBECount, MaxBECount->getType(), Depth);
1659 if (MaxBECount == RecastedMaxBECount) {
1660 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1661 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1662 const SCEV *ZMul =
1663 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1664 const SCEV *ZAdd = getZeroExtendExpr(
1665 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1666 Depth + 1);
1667 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1668 const SCEV *WideMaxBECount =
1669 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1670 const SCEV *OperandExtendedAdd =
1671 getAddExpr(WideStart,
1672 getMulExpr(WideMaxBECount,
1673 getZeroExtendExpr(Step, WideTy, Depth + 1),
1676 if (ZAdd == OperandExtendedAdd) {
1677 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1678 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1679 // Return the expression with the addrec on the outside.
1680 Start =
1682 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1683 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1684 }
1685 // Similar to above, only this time treat the step value as signed.
1686 // This covers loops that count down.
1687 OperandExtendedAdd =
1688 getAddExpr(WideStart,
1689 getMulExpr(WideMaxBECount,
1690 getSignExtendExpr(Step, WideTy, Depth + 1),
1693 if (ZAdd == OperandExtendedAdd) {
1694 // Cache knowledge of AR NW, which is propagated to this AddRec.
1695 // Negative step causes unsigned wrap, but it still can't self-wrap.
1696 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1697 // Return the expression with the addrec on the outside.
1698 Start =
1700 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1701 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1702 }
1703 }
1704 }
1705
1706 // Normally, in the cases we can prove no-overflow via a
1707 // backedge guarding condition, we can also compute a backedge
1708 // taken count for the loop. The exceptions are assumptions and
1709 // guards present in the loop -- SCEV is not great at exploiting
1710 // these to compute max backedge taken counts, but can still use
1711 // these to prove lack of overflow. Use this fact to avoid
1712 // doing extra work that may not pay off.
1713 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1714 !AC.assumptions().empty()) {
1715
1716 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1717 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1718 if (AR->hasNoUnsignedWrap()) {
1719 // Same as nuw case above - duplicated here to avoid a compile time
1720 // issue. It's not clear that the order of checks does matter, but
1721 // it's one of two issue possible causes for a change which was
1722 // reverted. Be conservative for the moment.
1723 Start =
1725 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1726 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1727 }
1728
1729 // For a negative step, we can extend the operands iff doing so only
1730 // traverses values in the range zext([0,UINT_MAX]).
1731 if (isKnownNegative(Step)) {
1732 const SCEV *N =
1736 // Cache knowledge of AR NW, which is propagated to this
1737 // AddRec. Negative step causes unsigned wrap, but it
1738 // still can't self-wrap.
1739 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1740 // Return the expression with the addrec on the outside.
1741 Start =
1743 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1744 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1745 }
1746 }
1747 }
1748
1749 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1750 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1751 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1752 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1753 const APInt &C = SC->getAPInt();
1754 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1755 if (D != 0) {
1756 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1757 const SCEV *SResidual =
1758 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1759 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1760 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1761 Depth + 1);
1762 }
1763 }
1764
1765 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1766 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1767 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1768 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1769 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1770 }
1771 }
1772
1773 // zext(A % B) --> zext(A) % zext(B)
1774 {
1775 const SCEV *LHS;
1776 const SCEV *RHS;
1777 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1778 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1779 getZeroExtendExpr(RHS, Ty, Depth + 1));
1780 }
1781
1782 // zext(A / B) --> zext(A) / zext(B).
1783 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1784 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1785 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1786
1787 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1788 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1789 if (SA->hasNoUnsignedWrap()) {
1790 // If the addition does not unsign overflow then we can, by definition,
1791 // commute the zero extension with the addition operation.
1793 for (SCEVUse Op : SA->operands())
1794 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1795 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1796 }
1797
1798 const APInt *C, *C2;
1799 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1800 // Currently the non-negative check is done manually, as isKnownNonNegative
1801 // is too expensive.
1802 if (SA->hasNoSignedWrap() &&
1804 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1805 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1806 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1807 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1808 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1809 SCEV::FlagNSW, Depth + 1);
1810 }
1811
1812 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1813 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1814 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1815 //
1816 // Often address arithmetics contain expressions like
1817 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1818 // This transformation is useful while proving that such expressions are
1819 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1820 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1821 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1822 if (D != 0) {
1823 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1824 const SCEV *SResidual =
1826 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1827 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1828 Depth + 1);
1829 }
1830 }
1831 }
1832
1833 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1834 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1835 if (SM->hasNoUnsignedWrap()) {
1836 // If the multiply does not unsign overflow then we can, by definition,
1837 // commute the zero extension with the multiply operation.
1839 for (SCEVUse Op : SM->operands())
1840 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1841 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1842 }
1843
1844 // zext(2^K * (trunc X to iN)) to iM ->
1845 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1846 //
1847 // Proof:
1848 //
1849 // zext(2^K * (trunc X to iN)) to iM
1850 // = zext((trunc X to iN) << K) to iM
1851 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1852 // (because shl removes the top K bits)
1853 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1854 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1855 //
1856 const APInt *C;
1857 const SCEV *TruncRHS;
1858 if (match(SM,
1859 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1860 C->isPowerOf2()) {
1861 int NewTruncBits =
1862 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1863 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1864 return getMulExpr(
1865 getZeroExtendExpr(SM->getOperand(0), Ty),
1866 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1867 SCEV::FlagNUW, Depth + 1);
1868 }
1869 }
1870
1871 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1872 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1876 for (SCEVUse Operand : MinMax->operands())
1877 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1879 return getUMinExpr(Operands);
1880 return getUMaxExpr(Operands);
1881 }
1882
1883 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1885 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1887 for (SCEVUse Operand : MinMax->operands())
1888 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1889 return getUMinExpr(Operands, /*Sequential*/ true);
1890 }
1891
1892 // The cast wasn't folded; create an explicit cast node.
1893 // Recompute the insert position, as it may have been invalidated.
1894 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1895 return S;
1896 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1897 Op, Ty);
1898 UniqueSCEVs.insert(S, Token);
1899 S->computeAndSetCanonical(*this);
1900 registerUser(S, Op);
1901 return S;
1902}
1903
1905 unsigned Depth) {
1906 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1907 "This is not an extending conversion!");
1908 assert(isSCEVable(Ty) &&
1909 "This is not a conversion to a SCEVable type!");
1910 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1911 Ty = getEffectiveSCEVType(Ty);
1912
1913 FoldID ID(scSignExtend, Op, Ty);
1914 if (const SCEV *S = FoldCache.lookup(ID))
1915 return S;
1916
1917 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1919 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1920 return S;
1921}
1922
1924 unsigned Depth) {
1925 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1926 "This is not an extending conversion!");
1927 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1928 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1929 Ty = getEffectiveSCEVType(Ty);
1930
1931 // Fold if the operand is constant.
1932 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1933 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1934
1935 // sext(sext(x)) --> sext(x)
1937 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1938
1939 // sext(zext(x)) --> zext(x)
1941 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1942
1943 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1944 // sign-extension distributes over the recurrence.
1945 const SCEV *Start, *Step;
1946 const Loop *L;
1947 if (Depth <= MaxCastDepth &&
1948 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1949 const auto *AR = cast<SCEVAddRecExpr>(Op);
1950 if (AR->hasNoSignedWrap()) {
1951 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1952 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1953 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1954 }
1955 }
1956
1957 // Before doing any expensive analysis, check to see if we've already
1958 // computed a SCEV for this Op and Ty.
1961 ID.AddPointer(Op.getOpaqueValue());
1962 ID.AddPointer(Ty);
1964 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1965 return S;
1966 // Limit recursion depth.
1967 if (Depth > MaxCastDepth) {
1968 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1969 Op, Ty);
1970 UniqueSCEVs.insert(S, Token);
1971 S->computeAndSetCanonical(*this);
1972 registerUser(S, Op);
1973 return S;
1974 }
1975
1976 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1978 // It's possible the bits taken off by the truncate were all sign bits. If
1979 // so, we should be able to simplify this further.
1980 const SCEV *X = ST->getOperand();
1982 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1983 unsigned NewBits = getTypeSizeInBits(Ty);
1984 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1985 CR.sextOrTrunc(NewBits)))
1986 return getTruncateOrSignExtend(X, Ty, Depth);
1987 }
1988
1989 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1990 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1991 if (SA->hasNoSignedWrap()) {
1992 // If the addition does not sign overflow then we can, by definition,
1993 // commute the sign extension with the addition operation.
1995 for (SCEVUse Op : SA->operands())
1996 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1997 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1998 }
1999
2000 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2001 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2002 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2003 //
2004 // For instance, this will bring two seemingly different expressions:
2005 // 1 + sext(5 + 20 * %x + 24 * %y) and
2006 // sext(6 + 20 * %x + 24 * %y)
2007 // to the same form:
2008 // 2 + sext(4 + 20 * %x + 24 * %y)
2009 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2010 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2011 if (D != 0) {
2012 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2013 const SCEV *SResidual =
2015 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2016 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2017 Depth + 1);
2018 }
2019 }
2020 }
2021 // If the input value is a chrec scev, and we can prove that the value
2022 // did not overflow the old, smaller, value, we can sign extend all of the
2023 // operands (often constants). This allows analysis of something like
2024 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2025 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2026 const auto *AR = cast<SCEVAddRecExpr>(Op);
2027 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2028
2029 // The no-signed-wrap case is handled before the uniquing lookup above.
2030
2031 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2032 // Note that this serves two purposes: It filters out loops that are
2033 // simply not analyzable, and it covers the case where this code is
2034 // being called from within backedge-taken count analysis, such that
2035 // attempting to ask for the backedge-taken count would likely result
2036 // in infinite recursion. In the later case, the analysis code will
2037 // cope with a conservative value, and it will take care to purge
2038 // that value once it has finished.
2039 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2040 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2041 // Manually compute the final value for AR, checking for
2042 // overflow.
2043
2044 // Check whether the backedge-taken count can be losslessly casted to
2045 // the addrec's type. The count is always unsigned.
2046 const SCEV *CastedMaxBECount =
2047 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2048 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2049 CastedMaxBECount, MaxBECount->getType(), Depth);
2050 if (MaxBECount == RecastedMaxBECount) {
2051 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2052 // Check whether Start+Step*MaxBECount has no signed overflow.
2053 const SCEV *SMul =
2054 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2055 const SCEV *SAdd = getSignExtendExpr(
2056 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2057 Depth + 1);
2058 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2059 const SCEV *WideMaxBECount =
2060 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2061 const SCEV *OperandExtendedAdd =
2062 getAddExpr(WideStart,
2063 getMulExpr(WideMaxBECount,
2064 getSignExtendExpr(Step, WideTy, Depth + 1),
2067 if (SAdd == OperandExtendedAdd) {
2068 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2069 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2070 // Return the expression with the addrec on the outside.
2071 Start =
2073 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2074 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2075 }
2076 // Similar to above, only this time treat the step value as unsigned.
2077 // This covers loops that count up with an unsigned step.
2078 OperandExtendedAdd =
2079 getAddExpr(WideStart,
2080 getMulExpr(WideMaxBECount,
2081 getZeroExtendExpr(Step, WideTy, Depth + 1),
2084 if (SAdd == OperandExtendedAdd) {
2085 // If AR wraps around then
2086 //
2087 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2088 // => SAdd != OperandExtendedAdd
2089 //
2090 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2091 // (SAdd == OperandExtendedAdd => AR is NW)
2092
2093 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2094
2095 // Return the expression with the addrec on the outside.
2096 Start =
2098 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2099 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2100 }
2101 }
2102 }
2103
2104 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2105 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2106 if (AR->hasNoSignedWrap()) {
2107 // Same as nsw case above - duplicated here to avoid a compile time
2108 // issue. It's not clear that the order of checks does matter, but
2109 // it's one of two issue possible causes for a change which was
2110 // reverted. Be conservative for the moment.
2111 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2112 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2113 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2114 }
2115
2116 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2117 // if D + (C - D + Step * n) could be proven to not signed wrap
2118 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2119 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2120 const APInt &C = SC->getAPInt();
2121 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2122 if (D != 0) {
2123 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2124 const SCEV *SResidual =
2125 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2126 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2127 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2128 Depth + 1);
2129 }
2130 }
2131
2132 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2133 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2134 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2135 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2136 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2137 }
2138 }
2139
2140 // If the input value is provably positive and we could not simplify
2141 // away the sext build a zext instead.
2143 return getZeroExtendExpr(Op, Ty, Depth + 1);
2144
2145 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2146 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2150 for (SCEVUse Operand : MinMax->operands())
2151 Operands.push_back(getSignExtendExpr(Operand, Ty));
2153 return getSMinExpr(Operands);
2154 return getSMaxExpr(Operands);
2155 }
2156
2157 // The cast wasn't folded; create an explicit cast node.
2158 // Recompute the insert position, as it may have been invalidated.
2159 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2160 return S;
2161 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2162 Op, Ty);
2163 UniqueSCEVs.insert(S, Token);
2164 S->computeAndSetCanonical(*this);
2165 registerUser(S, Op);
2166 return S;
2167}
2168
2170 switch (Kind) {
2171 case scTruncate:
2172 return getTruncateExpr(Op, Ty);
2173 case scZeroExtend:
2174 return getZeroExtendExpr(Op, Ty);
2175 case scSignExtend:
2176 return getSignExtendExpr(Op, Ty);
2177 case scPtrToAddr: {
2178 const SCEV *Expr = getPtrToAddrExpr(Op);
2179 assert(Expr->getType() == Ty && "requested type must match");
2180 return Expr;
2181 }
2182 default:
2183 llvm_unreachable("Not a SCEV cast expression!");
2184 }
2185}
2186
2187/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2188/// unspecified bits out to the given type.
2190 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2191 "This is not an extending conversion!");
2192 assert(isSCEVable(Ty) &&
2193 "This is not a conversion to a SCEVable type!");
2194 Ty = getEffectiveSCEVType(Ty);
2195
2196 // Sign-extend negative constants.
2197 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2198 if (SC->getAPInt().isNegative())
2199 return getSignExtendExpr(Op, Ty);
2200
2201 // Peel off a truncate cast.
2203 const SCEV *NewOp = T->getOperand();
2204 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2205 return getAnyExtendExpr(NewOp, Ty);
2206 return getTruncateOrNoop(NewOp, Ty);
2207 }
2208
2209 // Next try a zext cast. If the cast is folded, use it.
2210 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2211 if (!isa<SCEVZeroExtendExpr>(ZExt))
2212 return ZExt;
2213
2214 // Next try a sext cast. If the cast is folded, use it.
2215 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2216 if (!isa<SCEVSignExtendExpr>(SExt))
2217 return SExt;
2218
2219 // Force the cast to be folded into the operands of an addrec.
2220 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2222 for (const SCEV *Op : AR->operands())
2223 Ops.push_back(getAnyExtendExpr(Op, Ty));
2224 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2225 }
2226
2227 // If the expression is obviously signed, use the sext cast value.
2228 if (isa<SCEVSMaxExpr>(Op))
2229 return SExt;
2230
2231 // Absent any other information, use the zext cast value.
2232 return ZExt;
2233}
2234
2235/// Process the given Ops list, which is a list of operands to be added under
2236/// the given scale, update the given map. This is a helper function for
2237/// getAddRecExpr. As an example of what it does, given a sequence of operands
2238/// that would form an add expression like this:
2239///
2240/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2241///
2242/// where A and B are constants, update the map with these values:
2243///
2244/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2245///
2246/// and add 13 + A*B*29 to AccumulatedConstant.
2247/// This will allow getAddRecExpr to produce this:
2248///
2249/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2250///
2251/// This form often exposes folding opportunities that are hidden in
2252/// the original operand list.
2253///
2254/// Return true iff it appears that any interesting folding opportunities
2255/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2256/// the common case where no interesting opportunities are present, and
2257/// is also used as a check to avoid infinite recursion.
2260 APInt &AccumulatedConstant,
2262 const APInt &Scale,
2263 ScalarEvolution &SE) {
2264 bool Interesting = false;
2265
2266 // Iterate over the add operands. They are sorted, with constants first.
2267 unsigned i = 0;
2268 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2269 ++i;
2270 // Pull a buried constant out to the outside.
2271 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2272 Interesting = true;
2273 AccumulatedConstant += Scale * C->getAPInt();
2274 }
2275
2276 // Next comes everything else. We're especially interested in multiplies
2277 // here, but they're in the middle, so just visit the rest with one loop.
2278 for (; i != Ops.size(); ++i) {
2280 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2281 APInt NewScale =
2282 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2283 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2284 // A multiplication of a constant with another add; recurse.
2285 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2286 Interesting |= CollectAddOperandsWithScales(
2287 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2288 } else {
2289 // A multiplication of a constant with some other value. Update
2290 // the map.
2291 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2292 const SCEV *Key = SE.getMulExpr(MulOps);
2293 auto Pair = M.insert({Key, NewScale});
2294 if (Pair.second) {
2295 NewOps.push_back(Pair.first->first);
2296 } else {
2297 Pair.first->second += NewScale;
2298 // The map already had an entry for this value, which may indicate
2299 // a folding opportunity.
2300 Interesting = true;
2301 }
2302 }
2303 } else {
2304 // An ordinary operand. Update the map.
2305 auto Pair = M.insert({Ops[i], Scale});
2306 if (Pair.second) {
2307 NewOps.push_back(Pair.first->first);
2308 } else {
2309 Pair.first->second += Scale;
2310 // The map already had an entry for this value, which may indicate
2311 // a folding opportunity.
2312 Interesting = true;
2313 }
2314 }
2315 }
2316
2317 return Interesting;
2318}
2319
2321 const SCEV *LHS, const SCEV *RHS,
2322 const Instruction *CtxI) {
2324 unsigned);
2325 switch (BinOp) {
2326 default:
2327 llvm_unreachable("Unsupported binary op");
2328 case Instruction::Add:
2330 break;
2331 case Instruction::Sub:
2333 break;
2334 case Instruction::Mul:
2336 break;
2337 }
2338
2339 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2342
2343 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2344 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2345 auto *WideTy =
2346 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2347
2348 const SCEV *A = (this->*Extension)(
2349 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2350 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2351 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2352 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2353 if (A == B)
2354 return true;
2355 // Can we use context to prove the fact we need?
2356 if (!CtxI)
2357 return false;
2358 // TODO: Support mul.
2359 if (BinOp == Instruction::Mul)
2360 return false;
2361 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2362 // TODO: Lift this limitation.
2363 if (!RHSC)
2364 return false;
2365 APInt C = RHSC->getAPInt();
2366 unsigned NumBits = C.getBitWidth();
2367 bool IsSub = (BinOp == Instruction::Sub);
2368 bool IsNegativeConst = (Signed && C.isNegative());
2369 // Compute the direction and magnitude by which we need to check overflow.
2370 bool OverflowDown = IsSub ^ IsNegativeConst;
2371 APInt Magnitude = C;
2372 if (IsNegativeConst) {
2373 if (C == APInt::getSignedMinValue(NumBits))
2374 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2375 // want to deal with that.
2376 return false;
2377 Magnitude = -C;
2378 }
2379
2381 if (OverflowDown) {
2382 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2383 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2384 : APInt::getMinValue(NumBits);
2385 APInt Limit = Min + Magnitude;
2386 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2387 } else {
2388 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2389 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2390 : APInt::getMaxValue(NumBits);
2391 APInt Limit = Max - Magnitude;
2392 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2393 }
2394}
2395
2396std::optional<SCEV::NoWrapFlags>
2398 const OverflowingBinaryOperator *OBO) {
2399 // It cannot be done any better.
2400 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2401 return std::nullopt;
2402
2403 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2404
2405 if (OBO->hasNoUnsignedWrap())
2407 if (OBO->hasNoSignedWrap())
2409
2410 bool Deduced = false;
2411
2413 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2414 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2415
2416 bool CanUseNSW = true;
2417 const APInt *ShiftAmt;
2418 // Treat `shl %a, C` as `mul %a, 1 << C`.
2419 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2420 unsigned BitWidth = ShiftAmt->getBitWidth();
2421 if (ShiftAmt->uge(BitWidth))
2422 return std::nullopt;
2423 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2424 // overflows.
2425 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2426 Opcode = Instruction::Mul;
2428 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2429 Opcode != Instruction::Mul) {
2430 return std::nullopt;
2431 }
2432
2433 const Instruction *CtxI =
2435 if (!OBO->hasNoUnsignedWrap() &&
2436 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2438 Deduced = true;
2439 }
2440
2441 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2442 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2444 Deduced = true;
2445 }
2446
2447 if (Deduced)
2448 return Flags;
2449 return std::nullopt;
2450}
2451
2452// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2453// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2454// can't-overflow flags for the operation if possible.
2458 SCEV::NoWrapFlags Flags) {
2459 using namespace std::placeholders;
2460
2461 using OBO = OverflowingBinaryOperator;
2462
2463 bool CanAnalyze =
2465 (void)CanAnalyze;
2466 assert(CanAnalyze && "don't call from other places!");
2467
2468 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2469 SCEV::NoWrapFlags SignOrUnsignWrap =
2470 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2471
2472 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2473 auto IsKnownNonNegative = [&](SCEVUse U) {
2474 return SE->isKnownNonNegative(U);
2475 };
2476
2477 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2478 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2479
2480 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2481
2482 if (SignOrUnsignWrap != SignOrUnsignMask &&
2483 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2484 isa<SCEVConstant>(Ops[0])) {
2485
2486 auto Opcode = [&] {
2487 switch (Type) {
2488 case scAddExpr:
2489 return Instruction::Add;
2490 case scMulExpr:
2491 return Instruction::Mul;
2492 default:
2493 llvm_unreachable("Unexpected SCEV op.");
2494 }
2495 }();
2496
2497 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2498
2499 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2500 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2502 Opcode, C, OBO::NoSignedWrap);
2503 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2505 }
2506
2507 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2508 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2510 Opcode, C, OBO::NoUnsignedWrap);
2511 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2513 }
2514 }
2515
2516 // <0,+,nonnegative><nw> is also nuw
2517 // TODO: Add corresponding nsw case
2519 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2520 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2522
2523 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2525 Ops.size() == 2) {
2526 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2527 if (UDiv->getOperand(1) == Ops[1])
2529 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2530 if (UDiv->getOperand(1) == Ops[0])
2532 }
2533
2534 return Flags;
2535}
2536
2538 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2539}
2540
2541/// Get a canonical add expression, or something simpler if possible.
2543 SCEV::NoWrapFlags OrigFlags,
2544 unsigned Depth) {
2545 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2546 "only nuw or nsw allowed");
2547 assert(!Ops.empty() && "Cannot get empty add!");
2548 if (Ops.size() == 1) return Ops[0];
2549#ifndef NDEBUG
2550 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2551 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2552 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2553 "SCEVAddExpr operand types don't match!");
2554 unsigned NumPtrs = count_if(
2555 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2556 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2557#endif
2558
2559 const SCEV *Folded = constantFoldAndGroupOps(
2560 *this, LI, DT, Ops,
2561 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2562 [](const APInt &C) { return C.isZero(); }, // identity
2563 [](const APInt &C) { return false; }); // absorber
2564 if (Folded)
2565 return Folded;
2566
2567 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2568
2569 // Delay expensive flag strengthening until necessary.
2570 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2571 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2572 };
2573
2574 // Limit recursion calls depth.
2576 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2577
2578 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2579 // Don't strengthen flags if we have no new information.
2580 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2581 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2582 Add->setNoWrapFlags(ComputeFlags(Ops));
2583 return S;
2584 }
2585
2586 // Okay, check to see if the same value occurs in the operand list more than
2587 // once. If so, merge them together into an multiply expression. Since we
2588 // sorted the list, these values are required to be adjacent.
2589 Type *Ty = Ops[0]->getType();
2590 bool FoundMatch = false;
2591 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2592 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2593 // Scan ahead to count how many equal operands there are.
2594 unsigned Count = 2;
2595 while (i+Count != e && Ops[i+Count] == Ops[i])
2596 ++Count;
2597 // Merge the values into a multiply.
2598 SCEVUse Scale = getConstant(Ty, Count);
2599 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2600 if (Ops.size() == Count)
2601 return Mul;
2602 Ops[i] = Mul;
2603 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2604 --i; e -= Count - 1;
2605 FoundMatch = true;
2606 }
2607 if (FoundMatch)
2608 return getAddExpr(Ops, OrigFlags, Depth + 1);
2609
2610 // Check for truncates. If all the operands are truncated from the same
2611 // type, see if factoring out the truncate would permit the result to be
2612 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2613 // if the contents of the resulting outer trunc fold to something simple.
2614 auto FindTruncSrcType = [&]() -> Type * {
2615 // We're ultimately looking to fold an addrec of truncs and muls of only
2616 // constants and truncs, so if we find any other types of SCEV
2617 // as operands of the addrec then we bail and return nullptr here.
2618 // Otherwise, we return the type of the operand of a trunc that we find.
2619 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2620 return T->getOperand()->getType();
2621 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2622 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2623 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2624 return T->getOperand()->getType();
2625 }
2626 return nullptr;
2627 };
2628 if (auto *SrcType = FindTruncSrcType()) {
2629 SmallVector<SCEVUse, 8> LargeOps;
2630 bool Ok = true;
2631 // Check all the operands to see if they can be represented in the
2632 // source type of the truncate.
2633 for (const SCEV *Op : Ops) {
2635 if (T->getOperand()->getType() != SrcType) {
2636 Ok = false;
2637 break;
2638 }
2639 LargeOps.push_back(T->getOperand());
2640 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2641 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2642 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2643 SmallVector<SCEVUse, 8> LargeMulOps;
2644 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2645 if (const SCEVTruncateExpr *T =
2646 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2647 if (T->getOperand()->getType() != SrcType) {
2648 Ok = false;
2649 break;
2650 }
2651 LargeMulOps.push_back(T->getOperand());
2652 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2653 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2654 } else {
2655 Ok = false;
2656 break;
2657 }
2658 }
2659 if (Ok)
2660 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2661 } else {
2662 Ok = false;
2663 break;
2664 }
2665 }
2666 if (Ok) {
2667 // Evaluate the expression in the larger type.
2668 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2669 // If it folds to something simple, use it. Otherwise, don't.
2670 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2671 return getTruncateExpr(Fold, Ty);
2672 }
2673 }
2674
2675 if (Ops.size() == 2) {
2676 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2677 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2678 // C1).
2679 const SCEV *A = Ops[0];
2680 const SCEV *B = Ops[1];
2681 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2682 auto *C = dyn_cast<SCEVConstant>(A);
2683 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2684 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2685 auto C2 = C->getAPInt();
2686 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2687
2688 APInt ConstAdd = C1 + C2;
2689 auto AddFlags = AddExpr->getNoWrapFlags();
2690 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2692 ConstAdd.ule(C1)) {
2693 PreservedFlags =
2695 }
2696
2697 // Adding a constant with the same sign and small magnitude is NSW, if the
2698 // original AddExpr was NSW.
2700 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2701 ConstAdd.abs().ule(C1.abs())) {
2702 PreservedFlags =
2704 }
2705
2706 if (PreservedFlags != SCEV::FlagAnyWrap) {
2707 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2708 NewOps[0] = getConstant(ConstAdd);
2709 return getAddExpr(NewOps, PreservedFlags);
2710 }
2711 }
2712
2713 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2714 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2715 const SCEVAddExpr *InnerAdd;
2716 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2717 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2718 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2719 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2720 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2722 SCEV::FlagNUW)) {
2723 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2724 }
2725 }
2726 }
2727
2728 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2729 const SCEV *Y;
2730 if (Ops.size() == 2 &&
2731 match(Ops[0],
2733 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2734 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2735
2736 // Skip past any other cast SCEVs.
2737 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2738 ++Idx;
2739
2740 // If there are add operands they would be next.
2741 if (Idx < Ops.size()) {
2742 bool DeletedAdd = false;
2743 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2744 // common NUW flag for expression after inlining. Other flags cannot be
2745 // preserved, because they may depend on the original order of operations.
2746 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2747 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2748 if (Ops.size() > AddOpsInlineThreshold ||
2749 Add->getNumOperands() > AddOpsInlineThreshold)
2750 break;
2751 // If we have an add, expand the add operands onto the end of the operands
2752 // list.
2753 Ops.erase(Ops.begin()+Idx);
2754 append_range(Ops, Add->operands());
2755 DeletedAdd = true;
2756 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2757 }
2758
2759 // If we deleted at least one add, we added operands to the end of the list,
2760 // and they are not necessarily sorted. Recurse to resort and resimplify
2761 // any operands we just acquired.
2762 if (DeletedAdd)
2763 return getAddExpr(Ops, CommonFlags, Depth + 1);
2764 }
2765
2766 // Skip over the add expression until we get to a multiply.
2767 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2768 ++Idx;
2769
2770 // Check to see if there are any folding opportunities present with
2771 // operands multiplied by constant values.
2772 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2773 uint64_t BitWidth = getTypeSizeInBits(Ty);
2776 APInt AccumulatedConstant(BitWidth, 0);
2777 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2778 Ops, APInt(BitWidth, 1), *this)) {
2779 struct APIntCompare {
2780 bool operator()(const APInt &LHS, const APInt &RHS) const {
2781 return LHS.ult(RHS);
2782 }
2783 };
2784
2785 // Some interesting folding opportunity is present, so its worthwhile to
2786 // re-generate the operands list. Group the operands by constant scale,
2787 // to avoid multiplying by the same constant scale multiple times.
2788 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2789 for (const SCEV *NewOp : NewOps)
2790 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2791 // Re-generate the operands list.
2792 Ops.clear();
2793 if (AccumulatedConstant != 0)
2794 Ops.push_back(getConstant(AccumulatedConstant));
2795 for (auto &MulOp : MulOpLists) {
2796 if (MulOp.first == 1) {
2797 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2798 } else if (MulOp.first != 0) {
2799 Ops.push_back(getMulExpr(
2800 getConstant(MulOp.first),
2801 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2802 SCEV::FlagAnyWrap, Depth + 1));
2803 }
2804 }
2805 if (Ops.empty())
2806 return getZero(Ty);
2807 if (Ops.size() == 1)
2808 return Ops[0];
2809 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2810 }
2811 }
2812
2813 // Given a SCEVMulExpr and an operand index, return the product of all
2814 // operands except the one at OpIdx.
2815 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2816 if (M->getNumOperands() == 2)
2817 return M->getOperand(OpIdx == 0);
2818 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2819 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2820 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2821 };
2822
2823 // If we are adding something to a multiply expression, make sure the
2824 // something is not already an operand of the multiply. If so, merge it into
2825 // the multiply.
2826 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2827 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2828 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2829 // Scan all terms to find every occurrence of common factor MulOpSCEV
2830 // and fold them in one shot:
2831 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2832 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2833 if (isa<SCEVConstant>(MulOpSCEV))
2834 continue;
2835
2836 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2837 // remaining product for multiply terms containing MulOpSCEV.
2838 SmallVector<SCEVUse, 4> Cofactors;
2839 SmallVector<unsigned, 4> DeadIndices;
2840 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2841 if (MulOpSCEV == Ops[AddOp]) {
2842 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2843 Cofactors.push_back(getOne(Ty));
2844 DeadIndices.push_back(AddOp);
2845 continue;
2846 }
2847
2848 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2849 continue;
2850
2851 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2852 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2853 ++OMulOp) {
2854 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2855 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2856 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2857 DeadIndices.push_back(AddOp);
2858 break;
2859 }
2860 }
2861 }
2862
2863 // Fold all collected cofactors with the anchor multiply's cofactor:
2864 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2865 if (!Cofactors.empty()) {
2866 Cofactors.push_back(StripFactor(Mul, MulOp));
2867
2868 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2869 SCEVUse OuterMul =
2870 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2871
2872 // DeadIndices does not include Idx (the anchor), hence +1.
2873 if (Ops.size() == DeadIndices.size() + 1)
2874 return OuterMul;
2875
2876 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2877 // The -1 adjustment accounts for the shift from removing Idx;
2878 // reverse order means each erasure only shifts later positions,
2879 // which have already been processed.
2880 Ops.erase(Ops.begin() + Idx);
2881 for (unsigned Dead : reverse(DeadIndices))
2882 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2883
2884 Ops.push_back(OuterMul);
2885 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2886 }
2887 }
2888 }
2889
2890 // If there are any add recurrences in the operands list, see if any other
2891 // added values are loop invariant. If so, we can fold them into the
2892 // recurrence.
2893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2894 ++Idx;
2895
2896 // Scan over all recurrences, trying to fold loop invariants into them.
2897 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2898 // Scan all of the other operands to this add and add them to the vector if
2899 // they are loop invariant w.r.t. the recurrence.
2901 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2902 const Loop *AddRecLoop = AddRec->getLoop();
2903 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2904 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2905 LIOps.push_back(Ops[i]);
2906 Ops.erase(Ops.begin()+i);
2907 --i; --e;
2908 }
2909
2910 // If we found some loop invariants, fold them into the recurrence.
2911 if (!LIOps.empty()) {
2912 // Compute nowrap flags for the addition of the loop-invariant ops and
2913 // the addrec. Temporarily push it as an operand for that purpose. These
2914 // flags are valid in the scope of the addrec only.
2915 LIOps.push_back(AddRec);
2916 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2917 LIOps.pop_back();
2918
2919 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2920 LIOps.push_back(AddRec->getStart());
2921
2922 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2923
2924 // It is not in general safe to propagate flags valid on an add within
2925 // the addrec scope to one outside it. We must prove that the inner
2926 // scope is guaranteed to execute if the outer one does to be able to
2927 // safely propagate. We know the program is undefined if poison is
2928 // produced on the inner scoped addrec. We also know that *for this use*
2929 // the outer scoped add can't overflow (because of the flags we just
2930 // computed for the inner scoped add) without the program being undefined.
2931 // Proving that entry to the outer scope neccesitates entry to the inner
2932 // scope, thus proves the program undefined if the flags would be violated
2933 // in the outer scope.
2934 SCEV::NoWrapFlags AddFlags = Flags;
2935 if (AddFlags != SCEV::FlagAnyWrap) {
2936 auto *DefI = getDefiningScopeBound(LIOps);
2937 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2938 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2939 AddFlags = SCEV::FlagAnyWrap;
2940 }
2941 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2942
2943 // Build the new addrec. Propagate the NUW and NSW flags if both the
2944 // outer add and the inner addrec are guaranteed to have no overflow.
2945 // Always propagate NW.
2946 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2947 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2948
2949 // If all of the other operands were loop invariant, we are done.
2950 if (Ops.size() == 1) return NewRec;
2951
2952 // Otherwise, add the folded AddRec by the non-invariant parts.
2953 for (unsigned i = 0;; ++i)
2954 if (Ops[i] == AddRec) {
2955 Ops[i] = NewRec;
2956 break;
2957 }
2958 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2959 }
2960
2961 // Okay, if there weren't any loop invariants to be folded, check to see if
2962 // there are multiple AddRec's with the same loop induction variable being
2963 // added together. If so, we can fold them.
2964 for (unsigned OtherIdx = Idx+1;
2965 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2966 ++OtherIdx) {
2967 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2968 // so that the 1st found AddRecExpr is dominated by all others.
2969 assert(DT.dominates(
2970 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2971 AddRec->getLoop()->getHeader()) &&
2972 "AddRecExprs are not sorted in reverse dominance order?");
2973 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2974 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2975 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2976 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2977 ++OtherIdx) {
2978 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2979 if (OtherAddRec->getLoop() == AddRecLoop) {
2980 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2981 i != e; ++i) {
2982 if (i >= AddRecOps.size()) {
2983 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2984 break;
2985 }
2986 AddRecOps[i] =
2987 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2989 }
2990 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2991 }
2992 }
2993 // Step size has changed, so we cannot guarantee no self-wraparound.
2994 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2995 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2996 }
2997 }
2998
2999 // Otherwise couldn't fold anything into this recurrence. Move onto the
3000 // next one.
3001 }
3002
3003 // Okay, it looks like we really DO need an add expr. Check to see if we
3004 // already have one, otherwise create a new one.
3005 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3006}
3007
3008const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3009 SCEV::NoWrapFlags Flags) {
3012 for (SCEVUse Op : Ops)
3013 ID.AddPointer(Op.getOpaqueValue());
3015 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
3016 if (!S) {
3017 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3019 S = new (SCEVAllocator)
3020 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3021 UniqueSCEVs.insert(S, Token);
3022 S->computeAndSetCanonical(*this);
3023 registerUser(S, Ops);
3024 }
3025 S->setNoWrapFlags(Flags);
3026 return S;
3027}
3028
3029const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3030 const Loop *L,
3031 SCEV::NoWrapFlags Flags) {
3032 FoldingSetNodeID ID;
3033 ID.AddInteger(scAddRecExpr);
3034 for (SCEVUse Op : Ops)
3035 ID.AddPointer(Op.getOpaqueValue());
3036 ID.AddPointer(L);
3037 FoldingSetInsertToken Token;
3038 SCEVAddRecExpr *S =
3039 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
3040 if (!S) {
3041 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3043 S = new (SCEVAllocator)
3044 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3045 UniqueSCEVs.insert(S, Token);
3046 S->computeAndSetCanonical(*this);
3047 LoopUsers[L].push_back(S);
3048 registerUser(S, Ops);
3049 }
3050 setNoWrapFlags(S, Flags);
3051 return S;
3052}
3053
3054const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3055 SCEV::NoWrapFlags Flags) {
3056 FoldingSetNodeID ID;
3057 ID.AddInteger(scMulExpr);
3058 for (SCEVUse Op : Ops)
3059 ID.AddPointer(Op.getOpaqueValue());
3060 FoldingSetInsertToken Token;
3061 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3062 if (!S) {
3063 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3065 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3066 O, Ops.size());
3067 UniqueSCEVs.insert(S, Token);
3068 S->computeAndSetCanonical(*this);
3069 registerUser(S, Ops);
3070 }
3071 S->setNoWrapFlags(Flags);
3072 return S;
3073}
3074
3075const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3076 FoldingSetNodeID ID;
3077 ID.AddInteger(scUDivExpr);
3078 ID.AddPointer(LHS.getOpaqueValue());
3079 ID.AddPointer(RHS.getOpaqueValue());
3080 FoldingSetInsertToken Token;
3081 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3082 if (!S) {
3083 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3084 UniqueSCEVs.insert(S, Token);
3085 S->computeAndSetCanonical(*this);
3087 }
3088 return S;
3089}
3090
3091static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3092 uint64_t k = i*j;
3093 if (j > 1 && k / j != i) Overflow = true;
3094 return k;
3095}
3096
3097/// Compute the result of "n choose k", the binomial coefficient. If an
3098/// intermediate computation overflows, Overflow will be set and the return will
3099/// be garbage. Overflow is not cleared on absence of overflow.
3100static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3101 // We use the multiplicative formula:
3102 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3103 // At each iteration, we take the n-th term of the numeral and divide by the
3104 // (k-n)th term of the denominator. This division will always produce an
3105 // integral result, and helps reduce the chance of overflow in the
3106 // intermediate computations. However, we can still overflow even when the
3107 // final result would fit.
3108
3109 if (n == 0 || n == k) return 1;
3110 if (k > n) return 0;
3111
3112 if (k > n/2)
3113 k = n-k;
3114
3115 uint64_t r = 1;
3116 for (uint64_t i = 1; i <= k; ++i) {
3117 r = umul_ov(r, n-(i-1), Overflow);
3118 r /= i;
3119 }
3120 return r;
3121}
3122
3123/// Determine if any of the operands in this SCEV are a constant or if
3124/// any of the add or multiply expressions in this SCEV contain a constant.
3125static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3126 struct FindConstantInAddMulChain {
3127 bool FoundConstant = false;
3128
3129 bool follow(const SCEV *S) {
3130 FoundConstant |= isa<SCEVConstant>(S);
3131 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3132 }
3133
3134 bool isDone() const {
3135 return FoundConstant;
3136 }
3137 };
3138
3139 FindConstantInAddMulChain F;
3141 ST.visitAll(StartExpr);
3142 return F.FoundConstant;
3143}
3144
3145/// Get a canonical multiply expression, or something simpler if possible.
3147 SCEV::NoWrapFlags OrigFlags,
3148 unsigned Depth) {
3149 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3150 "only nuw or nsw allowed");
3151 assert(!Ops.empty() && "Cannot get empty mul!");
3152 if (Ops.size() == 1) return Ops[0];
3153#ifndef NDEBUG
3154 Type *ETy = Ops[0]->getType();
3155 assert(!ETy->isPointerTy());
3156 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3157 assert(Ops[i]->getType() == ETy &&
3158 "SCEVMulExpr operand types don't match!");
3159#endif
3160
3161 const SCEV *Folded = constantFoldAndGroupOps(
3162 *this, LI, DT, Ops,
3163 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3164 [](const APInt &C) { return C.isOne(); }, // identity
3165 [](const APInt &C) { return C.isZero(); }); // absorber
3166 if (Folded)
3167 return Folded;
3168
3169 // Delay expensive flag strengthening until necessary.
3170 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3171 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3172 };
3173
3174 // Limit recursion calls depth.
3176 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3177
3178 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3179 // Don't strengthen flags if we have no new information.
3180 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3181 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3182 Mul->setNoWrapFlags(ComputeFlags(Ops));
3183 return S;
3184 }
3185
3186 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3187 if (Ops.size() == 2) {
3188 // C1*(C2+V) -> C1*C2 + C1*V
3189 // If any of Add's ops are Adds or Muls with a constant, apply this
3190 // transformation as well.
3191 //
3192 // TODO: There are some cases where this transformation is not
3193 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3194 // this transformation should be narrowed down.
3195 const SCEV *Op0, *Op1;
3196 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3198 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3199 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3200 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3201 }
3202
3203 if (Ops[0]->isAllOnesValue()) {
3204 // If we have a mul by -1 of an add, try distributing the -1 among the
3205 // add operands.
3206 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3208 bool AnyFolded = false;
3209 for (const SCEV *AddOp : Add->operands()) {
3210 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3212 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3213 NewOps.push_back(Mul);
3214 }
3215 if (AnyFolded)
3216 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3217 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3218 // Negation preserves a recurrence's no self-wrap property.
3220 for (const SCEV *AddRecOp : AddRec->operands())
3221 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3222 SCEV::FlagAnyWrap, Depth + 1));
3223 // Let M be the minimum representable signed value. AddRec with nsw
3224 // multiplied by -1 can have signed overflow if and only if it takes a
3225 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3226 // maximum signed value. In all other cases signed overflow is
3227 // impossible.
3228 auto FlagsMask = SCEV::FlagNW;
3229 if (AddRec->hasNoSignedWrap()) {
3230 auto MinInt =
3231 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3232 if (getSignedRangeMin(AddRec) != MinInt)
3233 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3234 }
3235 return getAddRecExpr(Operands, AddRec->getLoop(),
3236 AddRec->getNoWrapFlags(FlagsMask));
3237 }
3238 }
3239
3240 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3241 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3242 const SCEVAddExpr *InnerAdd;
3243 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3244 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3245 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3246 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3247 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3249 SCEV::FlagNUW)) {
3250 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3251 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3252 };
3253 }
3254
3255 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3256 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3257 // of C1, fold to (D /u (C2 /u C1)).
3258 const SCEV *D;
3259 APInt C1V = LHSC->getAPInt();
3260 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3261 // as -1 * 1, as it won't enable additional folds.
3262 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3263 C1V = C1V.abs();
3264 const SCEVConstant *C2;
3265 if (C1V.isPowerOf2() &&
3267 C2->getAPInt().isPowerOf2() &&
3268 C1V.logBase2() <= getMinTrailingZeros(D)) {
3269 const SCEV *NewMul = nullptr;
3270 if (C1V.uge(C2->getAPInt())) {
3271 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3272 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3273 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3274 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3275 }
3276 if (NewMul)
3277 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3278 }
3279 }
3280 }
3281
3282 // Skip over the add expression until we get to a multiply.
3283 unsigned Idx = 0;
3284 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3285 ++Idx;
3286
3287 // If there are mul operands inline them all into this expression.
3288 if (Idx < Ops.size()) {
3289 bool DeletedMul = false;
3290 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3291 if (Ops.size() > MulOpsInlineThreshold)
3292 break;
3293 // If we have an mul, expand the mul operands onto the end of the
3294 // operands list.
3295 Ops.erase(Ops.begin()+Idx);
3296 append_range(Ops, Mul->operands());
3297 DeletedMul = true;
3298 }
3299
3300 // If we deleted at least one mul, we added operands to the end of the
3301 // list, and they are not necessarily sorted. Recurse to resort and
3302 // resimplify any operands we just acquired.
3303 if (DeletedMul)
3304 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3305 }
3306
3307 // If there are any add recurrences in the operands list, see if any other
3308 // added values are loop invariant. If so, we can fold them into the
3309 // recurrence.
3310 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3311 ++Idx;
3312
3313 // Scan over all recurrences, trying to fold loop invariants into them.
3314 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3315 // Scan all of the other operands to this mul and add them to the vector
3316 // if they are loop invariant w.r.t. the recurrence.
3318 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3319 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3320 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3321 LIOps.push_back(Ops[i]);
3322 Ops.erase(Ops.begin()+i);
3323 --i; --e;
3324 }
3325
3326 // If we found some loop invariants, fold them into the recurrence.
3327 if (!LIOps.empty()) {
3328 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3330 NewOps.reserve(AddRec->getNumOperands());
3331 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3332
3333 // If both the mul and addrec are nuw, we can preserve nuw.
3334 // If both the mul and addrec are nsw, we can only preserve nsw if either
3335 // a) they are also nuw, or
3336 // b) all multiplications of addrec operands with scale are nsw.
3337 SCEV::NoWrapFlags Flags =
3338 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3339
3340 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3341 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3342 SCEV::FlagAnyWrap, Depth + 1));
3343
3344 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3346 Instruction::Mul, getSignedRange(Scale),
3348 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3349 Flags = clearFlags(Flags, SCEV::FlagNSW);
3350 }
3351 }
3352
3353 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3354
3355 // If all of the other operands were loop invariant, we are done.
3356 if (Ops.size() == 1) return NewRec;
3357
3358 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3359 for (unsigned i = 0;; ++i)
3360 if (Ops[i] == AddRec) {
3361 Ops[i] = NewRec;
3362 break;
3363 }
3364 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3365 }
3366
3367 // Okay, if there weren't any loop invariants to be folded, check to see
3368 // if there are multiple AddRec's with the same loop induction variable
3369 // being multiplied together. If so, we can fold them.
3370
3371 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3372 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3373 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3374 // ]]],+,...up to x=2n}.
3375 // Note that the arguments to choose() are always integers with values
3376 // known at compile time, never SCEV objects.
3377 //
3378 // The implementation avoids pointless extra computations when the two
3379 // addrec's are of different length (mathematically, it's equivalent to
3380 // an infinite stream of zeros on the right).
3381 bool OpsModified = false;
3382 for (unsigned OtherIdx = Idx+1;
3383 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3384 ++OtherIdx) {
3385 const SCEVAddRecExpr *OtherAddRec =
3386 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3387 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3388 continue;
3389
3390 // Limit max number of arguments to avoid creation of unreasonably big
3391 // SCEVAddRecs with very complex operands.
3392 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3393 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3394 continue;
3395
3396 bool Overflow = false;
3397 Type *Ty = AddRec->getType();
3398 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3399 SmallVector<SCEVUse, 7> AddRecOps;
3400 for (int x = 0, xe = AddRec->getNumOperands() +
3401 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3403 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3404 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3405 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3406 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3407 z < ze && !Overflow; ++z) {
3408 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3409 uint64_t Coeff;
3410 if (LargerThan64Bits)
3411 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3412 else
3413 Coeff = Coeff1*Coeff2;
3414 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3415 const SCEV *Term1 = AddRec->getOperand(y-z);
3416 const SCEV *Term2 = OtherAddRec->getOperand(z);
3417 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3418 SCEV::FlagAnyWrap, Depth + 1));
3419 }
3420 }
3421 if (SumOps.empty())
3422 SumOps.push_back(getZero(Ty));
3423 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3424 }
3425 if (!Overflow) {
3426 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3428 if (Ops.size() == 2) return NewAddRec;
3429 Ops[Idx] = NewAddRec;
3430 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3431 OpsModified = true;
3432 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3433 if (!AddRec)
3434 break;
3435 }
3436 }
3437 if (OpsModified)
3438 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3439
3440 // Otherwise couldn't fold anything into this recurrence. Move onto the
3441 // next one.
3442 }
3443
3444 // Okay, it looks like we really DO need an mul expr. Check to see if we
3445 // already have one, otherwise create a new one.
3446 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3447}
3448
3449/// Represents an unsigned remainder expression based on unsigned division.
3451 assert(getEffectiveSCEVType(LHS->getType()) ==
3452 getEffectiveSCEVType(RHS->getType()) &&
3453 "SCEVURemExpr operand types don't match!");
3454
3455 // Short-circuit easy cases
3456 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3457 // If constant is one, the result is trivial
3458 if (RHSC->getValue()->isOne())
3459 return getZero(LHS->getType()); // X urem 1 --> 0
3460
3461 // If constant is a power of two, fold into a zext(trunc(LHS)).
3462 if (RHSC->getAPInt().isPowerOf2()) {
3463 Type *FullTy = LHS->getType();
3464 Type *TruncTy =
3465 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3466 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3467 }
3468 }
3469
3470 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3471 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3472 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3473 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3474}
3475
3476/// Get a canonical unsigned division expression, or something simpler if
3477/// possible.
3479 assert(!LHS->getType()->isPointerTy() &&
3480 "SCEVUDivExpr operand can't be pointer!");
3481 assert(LHS->getType() == RHS->getType() &&
3482 "SCEVUDivExpr operand types don't match!");
3483
3484 if (SCEV *S =
3485 findExistingSCEVInCache(scUDivExpr, ArrayRef<SCEVUse>({LHS, RHS})))
3486 return S;
3487
3488 // 0 udiv Y == 0
3489 if (match(LHS, m_scev_Zero()))
3490 return LHS;
3491
3492 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3493 if (RHSC->getValue()->isOne())
3494 return LHS; // X udiv 1 --> x
3495 // If the denominator is zero, the result of the udiv is undefined. Don't
3496 // try to analyze it, because the resolution chosen here may differ from
3497 // the resolution chosen in other parts of the compiler.
3498 if (!RHSC->getValue()->isZero()) {
3499 // Determine if the division can be folded into the operands of
3500 // its operands.
3501 // TODO: Generalize this to non-constants by using known-bits information.
3502 Type *Ty = LHS->getType();
3503 unsigned LZ = RHSC->getAPInt().countl_zero();
3504 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3505 // For non-power-of-two values, effectively round the value up to the
3506 // nearest power of two.
3507 if (!RHSC->getAPInt().isPowerOf2())
3508 ++MaxShiftAmt;
3509 IntegerType *ExtTy =
3510 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3511 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3512 if (const SCEVConstant *Step =
3513 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3514 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3515 const APInt &StepInt = Step->getAPInt();
3516 const APInt &DivInt = RHSC->getAPInt();
3517 if (!StepInt.urem(DivInt) &&
3518 getZeroExtendExpr(AR, ExtTy) ==
3519 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3520 getZeroExtendExpr(Step, ExtTy),
3521 AR->getLoop(), SCEV::FlagAnyWrap)) {
3523 for (const SCEV *Op : AR->operands())
3524 Operands.push_back(getUDivExpr(Op, RHS));
3525 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3526 }
3527 /// Get a canonical UDivExpr for a recurrence.
3528 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3529 const APInt *StartRem;
3530 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3531 m_scev_APInt(StartRem))) {
3532 bool NoWrap =
3533 getZeroExtendExpr(AR, ExtTy) ==
3534 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3535 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3537
3538 // With N <= C and both N, C as powers-of-2, the transformation
3539 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3540 // if wrapping occurs, as the division results remain equivalent for
3541 // all offsets in [[(X - X%N), X).
3542 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3543 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3544 // Only fold if the subtraction can be folded in the start
3545 // expression.
3546 const SCEV *NewStart =
3547 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3548 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3549 !isa<SCEVAddExpr>(NewStart)) {
3550 const SCEV *NewLHS =
3551 getAddRecExpr(NewStart, Step, AR->getLoop(),
3552 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3553 if (LHS != NewLHS)
3554 return getUDivExpr(NewLHS, RHS);
3555 }
3556 }
3557 }
3558 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3559 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3560 if (M->hasNoUnsignedWrap()) {
3561 // Find an operand that's safely divisible.
3562 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3563 const SCEV *Op = M->getOperand(i);
3564 const SCEV *Div = getUDivExpr(Op, RHSC);
3565 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3566 SmallVector<SCEVUse, 4> Operands(M->operands());
3567 Operands[i] = Div;
3568 return getMulExpr(Operands);
3569 }
3570 }
3571
3572 // Even if it's not divisible, try to remove a common factor.
3573 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3574 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3575 RHSC->getAPInt());
3576 if (!Factor.isIntN(1)) {
3577 SmallVector<SCEVUse, 2> NewOperands;
3578 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3579 append_range(NewOperands, M->operands().drop_front());
3580 const SCEV *NewMul = getMulExpr(NewOperands);
3581 return getUDivExpr(NewMul,
3582 getConstant(RHSC->getAPInt().udiv(Factor)));
3583 }
3584 }
3585 }
3586 }
3587
3588 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3589 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3590 if (auto *DivisorConstant =
3591 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3592 bool Overflow = false;
3593 APInt NewRHS =
3594 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3595 if (Overflow) {
3596 return getConstant(RHSC->getType(), 0, false);
3597 }
3598 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3599 }
3600 }
3601
3602 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3603 // B/C can be folded.
3604 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3605 if (A->hasNoUnsignedWrap()) {
3607 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3608 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3609 if (isa<SCEVUDivExpr>(Op) ||
3610 getMulExpr(Op, RHS) != A->getOperand(i))
3611 break;
3612 Operands.push_back(Op);
3613 }
3614 if (Operands.size() == A->getNumOperands())
3615 return getAddExpr(Operands);
3616 }
3617 }
3618
3619 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3620 // This is an idiom for rounding A up to the next multiple of N, where A
3621 // is aready known to be a multiple of M. In this case, instcombine can
3622 // see that some low bits of the added constant are unused, so can clear
3623 // them, but we want to canonicalise to set the low bits. This makes the
3624 // pattern easier to match, without needing to check for known bits in
3625 // A*M.
3626 const APInt &N = RHSC->getAPInt();
3627 const APInt *NMinusM, *M;
3628 const SCEV *A;
3629 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3630 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3631 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3632 *NMinusM == N - *M) {
3633 return getUDivExpr(
3635 RHS);
3636 }
3637 }
3638
3639 // Fold if both operands are constant.
3640 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3641 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3642 }
3643 }
3644
3645 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3646 const APInt *NegC, *C;
3647 if (match(LHS,
3650 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3651 return getZero(LHS->getType());
3652
3653 // (%a * %b)<nuw> / %b -> %a
3654 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3655 if (Mul && Mul->hasNoUnsignedWrap()) {
3656 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3657 if (Mul->getOperand(i) == RHS) {
3659 append_range(Operands, Mul->operands().take_front(i));
3660 append_range(Operands, Mul->operands().drop_front(i + 1));
3661 return getMulExpr(Operands);
3662 }
3663 }
3664 }
3665
3666 // TODO: Generalize to handle any common factors.
3667 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3668 const SCEV *NewLHS, *NewRHS;
3669 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3670 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3671 return getUDivExpr(NewLHS, NewRHS);
3672
3673 return getOrCreateUDivExpr(LHS, RHS);
3674}
3675
3676/// Get a canonical unsigned division expression, or something simpler if
3677/// possible. There is no representation for an exact udiv in SCEV IR, but we
3678/// can attempt to optimize it prior to construction.
3680 // Currently there is no exact specific logic.
3681
3682 return getUDivExpr(LHS, RHS);
3683}
3684
3685/// Get an add recurrence expression for the specified loop. Simplify the
3686/// expression as much as possible.
3688 const Loop *L,
3689 SCEV::NoWrapFlags Flags) {
3691 Operands.push_back(Start);
3692 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3693 if (StepChrec->getLoop() == L) {
3694 append_range(Operands, StepChrec->operands());
3695 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3696 }
3697
3698 Operands.push_back(Step);
3699 return getAddRecExpr(Operands, L, Flags);
3700}
3701
3702/// Get an add recurrence expression for the specified loop. Simplify the
3703/// expression as much as possible.
3705 const Loop *L,
3706 SCEV::NoWrapFlags Flags) {
3707 if (Operands.size() == 1) return Operands[0];
3708#ifndef NDEBUG
3710 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3711 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3712 "SCEVAddRecExpr operand types don't match!");
3713 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3714 }
3715 for (const SCEV *Op : Operands)
3717 "SCEVAddRecExpr operand is not available at loop entry!");
3718#endif
3719
3720 if (Operands.back()->isZero()) {
3721 Operands.pop_back();
3722 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3723 }
3724
3725 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3726 // use that information to infer NUW and NSW flags. However, computing a
3727 // BE count requires calling getAddRecExpr, so we may not yet have a
3728 // meaningful BE count at this point (and if we don't, we'd be stuck
3729 // with a SCEVCouldNotCompute as the cached BE count).
3730
3731 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3732
3733 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3734 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3735 const Loop *NestedLoop = NestedAR->getLoop();
3736 if (L->contains(NestedLoop)
3737 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3738 : (!NestedLoop->contains(L) &&
3739 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3740 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3741 Operands[0] = NestedAR->getStart();
3742 // AddRecs require their operands be loop-invariant with respect to their
3743 // loops. Don't perform this transformation if it would break this
3744 // requirement.
3745 bool AllInvariant = all_of(
3746 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3747
3748 if (AllInvariant) {
3749 // Create a recurrence for the outer loop with the same step size.
3750 //
3751 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3752 // inner recurrence has the same property.
3753 SCEV::NoWrapFlags OuterFlags =
3754 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3755
3756 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3757 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3758 return isLoopInvariant(Op, NestedLoop);
3759 });
3760
3761 if (AllInvariant) {
3762 // Ok, both add recurrences are valid after the transformation.
3763 //
3764 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3765 // the outer recurrence has the same property.
3766 SCEV::NoWrapFlags InnerFlags =
3767 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3768 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3769 }
3770 }
3771 // Reset Operands to its original state.
3772 Operands[0] = NestedAR;
3773 }
3774 }
3775
3776 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3777 // already have one, otherwise create a new one.
3778 return getOrCreateAddRecExpr(Operands, L, Flags);
3779}
3780
3782 ArrayRef<SCEVUse> IndexExprs) {
3783 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3784 // getSCEV(Base)->getType() has the same address space as Base->getType()
3785 // because SCEV::getType() preserves the address space.
3786 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3787 if (NW != GEPNoWrapFlags::none()) {
3788 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3789 // but to do that, we have to ensure that said flag is valid in the entire
3790 // defined scope of the SCEV.
3791 // TODO: non-instructions have global scope. We might be able to prove
3792 // some global scope cases
3793 auto *GEPI = dyn_cast<Instruction>(GEP);
3794 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3795 NW = GEPNoWrapFlags::none();
3796 }
3797
3798 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3799}
3800
3802 ArrayRef<SCEVUse> IndexExprs,
3803 Type *SrcElementTy, GEPNoWrapFlags NW) {
3805 if (NW.hasNoUnsignedSignedWrap())
3806 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3807 if (NW.hasNoUnsignedWrap())
3808 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3809
3810 Type *CurTy = BaseExpr->getType();
3811 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3812 bool FirstIter = true;
3814 for (SCEVUse IndexExpr : IndexExprs) {
3815 // Compute the (potentially symbolic) offset in bytes for this index.
3816 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3817 // For a struct, add the member offset.
3818 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3819 unsigned FieldNo = Index->getZExtValue();
3820 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3821 Offsets.push_back(FieldOffset);
3822
3823 // Update CurTy to the type of the field at Index.
3824 CurTy = STy->getTypeAtIndex(Index);
3825 } else {
3826 // Update CurTy to its element type.
3827 if (FirstIter) {
3828 assert(isa<PointerType>(CurTy) &&
3829 "The first index of a GEP indexes a pointer");
3830 CurTy = SrcElementTy;
3831 FirstIter = false;
3832 } else {
3833 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3834 }
3835 // For an array, add the element offset, explicitly scaled.
3836 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3837 // Getelementptr indices are signed.
3838 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3839
3840 // Multiply the index by the element size to compute the element offset.
3841 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3842 Offsets.push_back(LocalOffset);
3843 }
3844 }
3845
3846 // Handle degenerate case of GEP without offsets.
3847 if (Offsets.empty())
3848 return BaseExpr;
3849
3850 // Add the offsets together, assuming nsw if inbounds.
3851 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3852 // Add the base address and the offset. We cannot use the nsw flag, as the
3853 // base address is unsigned. However, if we know that the offset is
3854 // non-negative, we can use nuw.
3855 bool NUW = NW.hasNoUnsignedWrap() ||
3858 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3859 assert(BaseExpr->getType() == GEPExpr->getType() &&
3860 "GEP should not change type mid-flight.");
3861 return GEPExpr;
3862}
3863
3864SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3867 ID.AddInteger(SCEVType);
3868 for (SCEVUse Op : Ops)
3869 ID.AddPointer(Op.getOpaqueValue());
3871 return UniqueSCEVs.lookup(ID, Token);
3872}
3873
3874const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3876 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3877}
3878
3881 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3882 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3883 if (Ops.size() == 1) return Ops[0];
3884#ifndef NDEBUG
3885 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3886 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3887 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3888 "Operand types don't match!");
3889 assert(Ops[0]->getType()->isPointerTy() ==
3890 Ops[i]->getType()->isPointerTy() &&
3891 "min/max should be consistently pointerish");
3892 }
3893#endif
3894
3895 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3896 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3897
3898 const SCEV *Folded = constantFoldAndGroupOps(
3899 *this, LI, DT, Ops,
3900 [&](const APInt &C1, const APInt &C2) {
3901 switch (Kind) {
3902 case scSMaxExpr:
3903 return APIntOps::smax(C1, C2);
3904 case scSMinExpr:
3905 return APIntOps::smin(C1, C2);
3906 case scUMaxExpr:
3907 return APIntOps::umax(C1, C2);
3908 case scUMinExpr:
3909 return APIntOps::umin(C1, C2);
3910 default:
3911 llvm_unreachable("Unknown SCEV min/max opcode");
3912 }
3913 },
3914 [&](const APInt &C) {
3915 // identity
3916 if (IsMax)
3917 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3918 else
3919 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3920 },
3921 [&](const APInt &C) {
3922 // absorber
3923 if (IsMax)
3924 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3925 else
3926 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3927 });
3928 if (Folded)
3929 return Folded;
3930
3931 // Check if we have created the same expression before.
3932 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3933 return S;
3934 }
3935
3936 // Find the first operation of the same kind
3937 unsigned Idx = 0;
3938 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3939 ++Idx;
3940
3941 // Check to see if one of the operands is of the same kind. If so, expand its
3942 // operands onto our operand list, and recurse to simplify.
3943 if (Idx < Ops.size()) {
3944 bool DeletedAny = false;
3945 while (Ops[Idx]->getSCEVType() == Kind) {
3946 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3947 Ops.erase(Ops.begin()+Idx);
3948 append_range(Ops, SMME->operands());
3949 DeletedAny = true;
3950 }
3951
3952 if (DeletedAny)
3953 return getMinMaxExpr(Kind, Ops);
3954 }
3955
3956 // Okay, check to see if the same value occurs in the operand list twice. If
3957 // so, delete one. Since we sorted the list, these values are required to
3958 // be adjacent.
3963 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3964 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3965 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3966 if (Ops[i] == Ops[i + 1] ||
3967 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3968 // X op Y op Y --> X op Y
3969 // X op Y --> X, if we know X, Y are ordered appropriately
3970 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3971 --i;
3972 --e;
3973 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3974 Ops[i + 1])) {
3975 // X op Y --> Y, if we know X, Y are ordered appropriately
3976 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3977 --i;
3978 --e;
3979 }
3980 }
3981
3982 if (Ops.size() == 1) return Ops[0];
3983
3984 assert(!Ops.empty() && "Reduced smax down to nothing!");
3985
3986 // Okay, it looks like we really DO need an expr. Check to see if we
3987 // already have one, otherwise create a new one.
3989 ID.AddInteger(Kind);
3990 for (SCEVUse Op : Ops)
3991 ID.AddPointer(Op.getOpaqueValue());
3993 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3994 if (ExistingSCEV)
3995 return ExistingSCEV;
3996 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3998 SCEV *S = new (SCEVAllocator)
3999 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4000
4001 UniqueSCEVs.insert(S, Token);
4002 S->computeAndSetCanonical(*this);
4003 registerUser(S, Ops);
4004 return S;
4005}
4006
4007namespace {
4008
4009class SCEVSequentialMinMaxDeduplicatingVisitor final
4010 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4011 std::optional<const SCEV *>> {
4012 using RetVal = std::optional<const SCEV *>;
4013
4014 ScalarEvolution &SE;
4015 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4016 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4018
4019 bool canRecurseInto(SCEVTypes Kind) const {
4020 // We can only recurse into the SCEV expression of the same effective type
4021 // as the type of our root SCEV expression.
4022 return RootKind == Kind || NonSequentialRootKind == Kind;
4023 };
4024
4025 RetVal visit(const SCEV *S) {
4026 // Has the whole operand been seen already?
4027 if (!SeenOps.insert(S).second)
4028 return std::nullopt;
4030 SCEVTypes Kind = S->getSCEVType();
4031
4032 if (!canRecurseInto(Kind))
4033 return S;
4034
4035 auto *NAry = cast<SCEVNAryExpr>(S);
4036 SmallVector<SCEVUse> NewOps;
4037 bool Changed = visit(Kind, NAry->operands(), NewOps);
4038
4039 if (!Changed)
4040 return S;
4041 if (NewOps.empty())
4042 return std::nullopt;
4043
4045 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4046 : SE.getMinMaxExpr(Kind, NewOps);
4047 }
4048 return S;
4049 }
4050
4051public:
4052 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4053 SCEVTypes RootKind)
4054 : SE(SE), RootKind(RootKind),
4055 NonSequentialRootKind(
4056 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4057 RootKind)) {}
4058
4059 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4060 SmallVectorImpl<SCEVUse> &NewOps) {
4061 bool Changed = false;
4063 Ops.reserve(OrigOps.size());
4064
4065 for (const SCEV *Op : OrigOps) {
4066 RetVal NewOp = visit(Op);
4067 if (NewOp != Op)
4068 Changed = true;
4069 if (NewOp)
4070 Ops.emplace_back(*NewOp);
4071 }
4072
4073 if (Changed)
4074 NewOps = std::move(Ops);
4075 return Changed;
4076 }
4077};
4078
4079} // namespace
4080
4082 switch (Kind) {
4083 case scConstant:
4084 case scVScale:
4085 case scTruncate:
4086 case scZeroExtend:
4087 case scSignExtend:
4088 case scPtrToAddr:
4089 case scAddExpr:
4090 case scMulExpr:
4091 case scUDivExpr:
4092 case scAddRecExpr:
4093 case scUMaxExpr:
4094 case scSMaxExpr:
4095 case scUMinExpr:
4096 case scSMinExpr:
4097 case scUnknown:
4098 // If any operand is poison, the whole expression is poison.
4099 return true;
4101 // FIXME: if the *first* operand is poison, the whole expression is poison.
4102 return false; // Pessimistically, say that it does not propagate poison.
4103 case scCouldNotCompute:
4104 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4105 }
4106 llvm_unreachable("Unknown SCEV kind!");
4107}
4108
4109namespace {
4110// The only way poison may be introduced in a SCEV expression is from a
4111// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4112// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4113// introduce poison -- they encode guaranteed, non-speculated knowledge.
4114//
4115// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4116// with the notable exception of umin_seq, where only poison from the first
4117// operand is (unconditionally) propagated.
4118struct SCEVPoisonCollector {
4119 bool LookThroughMaybePoisonBlocking;
4120 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4121 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4122 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4123
4124 bool follow(const SCEV *S) {
4125 if (!LookThroughMaybePoisonBlocking &&
4127 return false;
4128
4129 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4130 if (!isGuaranteedNotToBePoison(SU->getValue()))
4131 MaybePoison.insert(SU);
4132 }
4133 return true;
4134 }
4135 bool isDone() const { return false; }
4136};
4137} // namespace
4138
4139/// Return true if V is poison given that AssumedPoison is already poison.
4140static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4141 // First collect all SCEVs that might result in AssumedPoison to be poison.
4142 // We need to look through potentially poison-blocking operations here,
4143 // because we want to find all SCEVs that *might* result in poison, not only
4144 // those that are *required* to.
4145 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4146 visitAll(AssumedPoison, PC1);
4147
4148 // AssumedPoison is never poison. As the assumption is false, the implication
4149 // is true. Don't bother walking the other SCEV in this case.
4150 if (PC1.MaybePoison.empty())
4151 return true;
4152
4153 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4154 // as well. We cannot look through potentially poison-blocking operations
4155 // here, as their arguments only *may* make the result poison.
4156 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4157 visitAll(S, PC2);
4158
4159 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4160 // it will also make S poison by being part of PC2.MaybePoison.
4161 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4162}
4163
4165 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4166 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4167 visitAll(S, PC);
4168 for (const SCEVUnknown *SU : PC.MaybePoison)
4169 Result.insert(SU->getValue());
4170}
4171
4173 const SCEV *S, Instruction *I,
4174 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4175 // If the instruction cannot be poison, it's always safe to reuse.
4177 return true;
4178
4179 // Otherwise, it is possible that I is more poisonous that S. Collect the
4180 // poison-contributors of S, and then check whether I has any additional
4181 // poison-contributors. Poison that is contributed through poison-generating
4182 // flags is handled by dropping those flags instead.
4184 getPoisonGeneratingValues(PoisonVals, S);
4185
4186 SmallVector<Value *> Worklist;
4188 Worklist.push_back(I);
4189 while (!Worklist.empty()) {
4190 Value *V = Worklist.pop_back_val();
4191 if (!Visited.insert(V).second)
4192 continue;
4193
4194 // Avoid walking large instruction graphs.
4195 if (Visited.size() > 16)
4196 return false;
4197
4198 // Either the value can't be poison, or the S would also be poison if it
4199 // is.
4200 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4201 continue;
4202
4203 auto *I = dyn_cast<Instruction>(V);
4204 if (!I)
4205 return false;
4206
4207 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4208 // can't replace an arbitrary add with disjoint or, even if we drop the
4209 // flag. We would need to convert the or into an add.
4210 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4211 if (PDI->isDisjoint())
4212 return false;
4213
4214 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4215 // because SCEV currently assumes it can't be poison. Remove this special
4216 // case once we proper model when vscale can be poison.
4217 if (auto *II = dyn_cast<IntrinsicInst>(I);
4218 II && II->getIntrinsicID() == Intrinsic::vscale)
4219 continue;
4220
4221 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4222 return false;
4223
4224 // If the instruction can't create poison, we can recurse to its operands.
4225 if (I->hasPoisonGeneratingAnnotations())
4226 DropPoisonGeneratingInsts.push_back(I);
4227
4228 llvm::append_range(Worklist, I->operands());
4229 }
4230 return true;
4231}
4232
4233const SCEV *
4236 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4237 "Not a SCEVSequentialMinMaxExpr!");
4238 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4239 if (Ops.size() == 1)
4240 return Ops[0];
4241#ifndef NDEBUG
4242 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4243 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4244 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4245 "Operand types don't match!");
4246 assert(Ops[0]->getType()->isPointerTy() ==
4247 Ops[i]->getType()->isPointerTy() &&
4248 "min/max should be consistently pointerish");
4249 }
4250#endif
4251
4252 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4253 // so we can *NOT* do any kind of sorting of the expressions!
4254
4255 // Check if we have created the same expression before.
4256 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4257 return S;
4258
4259 // FIXME: there are *some* simplifications that we can do here.
4260
4261 // Keep only the first instance of an operand.
4262 {
4263 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4264 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4265 if (Changed)
4266 return getSequentialMinMaxExpr(Kind, Ops);
4267 }
4268
4269 // Check to see if one of the operands is of the same kind. If so, expand its
4270 // operands onto our operand list, and recurse to simplify.
4271 {
4272 unsigned Idx = 0;
4273 bool DeletedAny = false;
4274 while (Idx < Ops.size()) {
4275 if (Ops[Idx]->getSCEVType() != Kind) {
4276 ++Idx;
4277 continue;
4278 }
4279 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4280 Ops.erase(Ops.begin() + Idx);
4281 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4282 SMME->operands().end());
4283 DeletedAny = true;
4284 }
4285
4286 if (DeletedAny)
4287 return getSequentialMinMaxExpr(Kind, Ops);
4288 }
4289
4290 const SCEV *SaturationPoint;
4292 switch (Kind) {
4294 SaturationPoint = getZero(Ops[0]->getType());
4295 Pred = ICmpInst::ICMP_ULE;
4296 break;
4297 default:
4298 llvm_unreachable("Not a sequential min/max type.");
4299 }
4300
4301 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4302 if (!isGuaranteedNotToCauseUB(Ops[i]))
4303 continue;
4304 // We can replace %x umin_seq %y with %x umin %y if either:
4305 // * %y being poison implies %x is also poison.
4306 // * %x cannot be the saturating value (e.g. zero for umin).
4307 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4308 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4309 SaturationPoint)) {
4310 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4311 Ops[i - 1] = getMinMaxExpr(
4313 SeqOps);
4314 Ops.erase(Ops.begin() + i);
4315 return getSequentialMinMaxExpr(Kind, Ops);
4316 }
4317 // Fold %x umin_seq %y to %x if %x ule %y.
4318 // TODO: We might be able to prove the predicate for a later operand.
4319 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4320 Ops.erase(Ops.begin() + i);
4321 return getSequentialMinMaxExpr(Kind, Ops);
4322 }
4323 }
4324
4325 // Okay, it looks like we really DO need an expr. Check to see if we
4326 // already have one, otherwise create a new one.
4328 ID.AddInteger(Kind);
4329 for (SCEVUse Op : Ops)
4330 ID.AddPointer(Op.getOpaqueValue());
4332 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4333 if (ExistingSCEV)
4334 return ExistingSCEV;
4335
4336 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4338 SCEV *S = new (SCEVAllocator)
4339 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4340
4341 UniqueSCEVs.insert(S, Token);
4342 S->computeAndSetCanonical(*this);
4343 registerUser(S, Ops);
4344 return S;
4345}
4346
4351
4355
4360
4364
4369
4373
4375 bool Sequential) {
4376 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4377 return getUMinExpr(Ops, Sequential);
4378}
4379
4385
4386const SCEV *
4388 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4389 if (Size.isScalable())
4390 Res = getMulExpr(Res, getVScale(IntTy));
4391 return Res;
4392}
4393
4395 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4396}
4397
4399 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4400}
4401
4403 StructType *STy,
4404 unsigned FieldNo) {
4405 // We can bypass creating a target-independent constant expression and then
4406 // folding it back into a ConstantInt. This is just a compile-time
4407 // optimization.
4408 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4409 assert(!SL->getSizeInBits().isScalable() &&
4410 "Cannot get offset for structure containing scalable vector types");
4411 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4412}
4413
4415 // Don't attempt to do anything other than create a SCEVUnknown object
4416 // here. createSCEV only calls getUnknown after checking for all other
4417 // interesting possibilities, and any other code that calls getUnknown
4418 // is doing so in order to hide a value from SCEV canonicalization.
4419
4422 ID.AddPointer(V);
4424 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4425 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4426 "Stale SCEVUnknown in uniquing map!");
4427 return S;
4428 }
4429 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4430 FirstUnknown);
4431 FirstUnknown = cast<SCEVUnknown>(S);
4432 UniqueSCEVs.insert(S, Token);
4433 S->computeAndSetCanonical(*this);
4434 return S;
4435}
4436
4437//===----------------------------------------------------------------------===//
4438// Basic SCEV Analysis and PHI Idiom Recognition Code
4439//
4440
4441/// Test if values of the given type are analyzable within the SCEV
4442/// framework. This primarily includes integer types, and it can optionally
4443/// include pointer types if the ScalarEvolution class has access to
4444/// target-specific information.
4446 // Integers and pointers are always SCEVable.
4447 return Ty->isIntOrPtrTy();
4448}
4449
4450/// Return the size in bits of the specified type, for which isSCEVable must
4451/// return true.
4453 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4454 if (Ty->isPointerTy())
4456 return getDataLayout().getTypeSizeInBits(Ty);
4457}
4458
4459/// Return a type with the same bitwidth as the given type and which represents
4460/// how SCEV will treat the given type, for which isSCEVable must return
4461/// true. For pointer types, this is the pointer index sized integer type.
4463 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4464
4465 if (Ty->isIntegerTy())
4466 return Ty;
4467
4468 // The only other support type is pointer.
4469 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4470 return getDataLayout().getIndexType(Ty);
4471}
4472
4474 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4475}
4476
4478 const SCEV *B) {
4479 /// For a valid use point to exist, the defining scope of one operand
4480 /// must dominate the other.
4481 bool PreciseA, PreciseB;
4482 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4483 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4484 if (!PreciseA || !PreciseB)
4485 // Can't tell.
4486 return false;
4487 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4488 DT.dominates(ScopeB, ScopeA);
4489}
4490
4492 return CouldNotCompute.get();
4493}
4494
4495bool ScalarEvolution::checkValidity(const SCEV *S) const {
4496 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4497 auto *SU = dyn_cast<SCEVUnknown>(S);
4498 return SU && SU->getValue() == nullptr;
4499 });
4500
4501 return !ContainsNulls;
4502}
4503
4505 HasRecMapType::iterator I = HasRecMap.find(S);
4506 if (I != HasRecMap.end())
4507 return I->second;
4508
4509 bool FoundAddRec =
4510 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4511 HasRecMap.insert({S, FoundAddRec});
4512 return FoundAddRec;
4513}
4514
4515/// Return the ValueOffsetPair set for \p S. \p S can be represented
4516/// by the value and offset from any ValueOffsetPair in the set.
4517ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4518 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4519 if (SI == ExprValueMap.end())
4520 return {};
4521 return SI->second.getArrayRef();
4522}
4523
4524/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4525/// cannot be used separately. eraseValueFromMap should be used to remove
4526/// V from ValueExprMap and ExprValueMap at the same time.
4527void ScalarEvolution::eraseValueFromMap(Value *V) {
4528 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4529 if (I != ValueExprMap.end()) {
4530 auto EVIt = ExprValueMap.find(I->second);
4531 bool Removed = EVIt->second.remove(V);
4532 (void) Removed;
4533 assert(Removed && "Value not in ExprValueMap?");
4534 ValueExprMap.erase(I);
4535 }
4536}
4537
4538void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4539 // A recursive query may have already computed the SCEV. It should be
4540 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4541 // inferred nowrap flags.
4542 auto It = ValueExprMap.find_as(V);
4543 if (It == ValueExprMap.end()) {
4544 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4545 ExprValueMap[S].insert(V);
4546 }
4547}
4548
4549/// Return an existing SCEV if it exists, otherwise analyze the expression and
4550/// create a new one.
4552 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4553
4554 if (const SCEV *S = getExistingSCEV(V))
4555 return S;
4556 return createSCEVIter(V);
4557}
4558
4560 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4561
4562 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4563 if (I != ValueExprMap.end()) {
4564 const SCEV *S = I->second;
4565 assert(checkValidity(S) &&
4566 "existing SCEV has not been properly invalidated");
4567 return S;
4568 }
4569 return nullptr;
4570}
4571
4572/// Return a SCEV corresponding to -V = -1*V
4574 SCEV::NoWrapFlags Flags) {
4575 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4576 return getConstant(
4577 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4578
4579 Type *Ty = V->getType();
4580 Ty = getEffectiveSCEVType(Ty);
4581 return getMulExpr(V, getMinusOne(Ty), Flags);
4582}
4583
4584/// If Expr computes ~A, return A else return nullptr
4585static const SCEV *MatchNotExpr(const SCEV *Expr) {
4586 const SCEV *MulOp;
4587 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4588 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4589 return MulOp;
4590 return nullptr;
4591}
4592
4593/// Return a SCEV corresponding to ~V = -1-V
4595 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4596
4597 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4598 return getConstant(
4599 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4600
4601 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4602 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4603 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4604 SmallVector<SCEVUse, 2> MatchedOperands;
4605 for (const SCEV *Operand : MME->operands()) {
4606 const SCEV *Matched = MatchNotExpr(Operand);
4607 if (!Matched)
4608 return (const SCEV *)nullptr;
4609 MatchedOperands.push_back(Matched);
4610 }
4611 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4612 MatchedOperands);
4613 };
4614 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4615 return Replaced;
4616 }
4617
4618 Type *Ty = V->getType();
4619 Ty = getEffectiveSCEVType(Ty);
4620 return getMinusSCEV(getMinusOne(Ty), V);
4621}
4622
4624 assert(P->getType()->isPointerTy());
4625
4626 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4627 // The base of an AddRec is the first operand.
4628 SmallVector<SCEVUse> Ops{AddRec->operands()};
4629 Ops[0] = removePointerBase(Ops[0]);
4630 // Don't try to transfer nowrap flags for now. We could in some cases
4631 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4632 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4633 }
4634 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4635 // The base of an Add is the pointer operand.
4636 SmallVector<SCEVUse> Ops{Add->operands()};
4637 SCEVUse *PtrOp = nullptr;
4638 for (SCEVUse &AddOp : Ops) {
4639 if (AddOp->getType()->isPointerTy()) {
4640 assert(!PtrOp && "Cannot have multiple pointer ops");
4641 PtrOp = &AddOp;
4642 }
4643 }
4644 *PtrOp = removePointerBase(*PtrOp);
4645 // Don't try to transfer nowrap flags for now. We could in some cases
4646 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4647 return getAddExpr(Ops);
4648 }
4649 // Any other expression must be a pointer base.
4650 return getZero(P->getType());
4651}
4652
4654 SCEV::NoWrapFlags Flags,
4655 unsigned Depth) {
4656 // Fast path: X - X --> 0.
4657 if (LHS == RHS)
4658 return getZero(LHS->getType());
4659
4660 // If we subtract two pointers with different pointer bases, bail.
4661 // Eventually, we're going to add an assertion to getMulExpr that we
4662 // can't multiply by a pointer.
4663 if (RHS->getType()->isPointerTy()) {
4664 if (!LHS->getType()->isPointerTy() ||
4665 getPointerBase(LHS) != getPointerBase(RHS))
4666 return getCouldNotCompute();
4667 LHS = removePointerBase(LHS);
4668 RHS = removePointerBase(RHS);
4669 }
4670
4671 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4672 // makes it so that we cannot make much use of NUW.
4673 auto AddFlags = SCEV::FlagAnyWrap;
4674 const bool RHSIsNotMinSigned =
4676 if (hasFlags(Flags, SCEV::FlagNSW)) {
4677 // Let M be the minimum representable signed value. Then (-1)*RHS
4678 // signed-wraps if and only if RHS is M. That can happen even for
4679 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4680 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4681 // (-1)*RHS, we need to prove that RHS != M.
4682 //
4683 // If LHS is non-negative and we know that LHS - RHS does not
4684 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4685 // either by proving that RHS > M or that LHS >= 0.
4686 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4687 AddFlags = SCEV::FlagNSW;
4688 }
4689 }
4690
4691 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4692 // RHS is NSW and LHS >= 0.
4693 //
4694 // The difficulty here is that the NSW flag may have been proven
4695 // relative to a loop that is to be found in a recurrence in LHS and
4696 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4697 // larger scope than intended.
4698 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4699
4700 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4701}
4702
4704 unsigned Depth) {
4705 Type *SrcTy = V->getType();
4706 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4707 "Cannot truncate or zero extend with non-integer arguments!");
4708 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4709 return V; // No conversion
4710 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4711 return getTruncateExpr(V, Ty, Depth);
4712 return getZeroExtendExpr(V, Ty, Depth);
4713}
4714
4716 unsigned Depth) {
4717 Type *SrcTy = V->getType();
4718 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4719 "Cannot truncate or zero extend with non-integer arguments!");
4720 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4721 return V; // No conversion
4722 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4723 return getTruncateExpr(V, Ty, Depth);
4724 return getSignExtendExpr(V, Ty, Depth);
4725}
4726
4728 Type *SrcTy = V->getType();
4729 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4730 "Cannot noop or zero extend with non-integer arguments!");
4732 "getNoopOrZeroExtend cannot truncate!");
4733 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4734 return V; // No conversion
4735 return getZeroExtendExpr(V, Ty);
4736}
4737
4739 Type *SrcTy = V->getType();
4740 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4741 "Cannot noop or sign extend with non-integer arguments!");
4743 "getNoopOrSignExtend cannot truncate!");
4744 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4745 return V; // No conversion
4746 return getSignExtendExpr(V, Ty);
4747}
4748
4750 Type *SrcTy = V->getType();
4751 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4752 "Cannot noop or any extend with non-integer arguments!");
4754 "getNoopOrAnyExtend cannot truncate!");
4755 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4756 return V; // No conversion
4757 return getAnyExtendExpr(V, Ty);
4758}
4759
4761 Type *SrcTy = V->getType();
4762 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4763 "Cannot truncate or noop with non-integer arguments!");
4765 "getTruncateOrNoop cannot extend!");
4766 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4767 return V; // No conversion
4768 return getTruncateExpr(V, Ty);
4769}
4770
4772 const SCEV *RHS) {
4773 const SCEV *PromotedLHS = LHS;
4774 const SCEV *PromotedRHS = RHS;
4775
4776 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4777 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4778 else
4779 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4780
4781 return getUMaxExpr(PromotedLHS, PromotedRHS);
4782}
4783
4785 const SCEV *RHS,
4786 bool Sequential) {
4787 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4788 return getUMinFromMismatchedTypes(Ops, Sequential);
4789}
4790
4791const SCEV *
4793 bool Sequential) {
4794 assert(!Ops.empty() && "At least one operand must be!");
4795 // Trivial case.
4796 if (Ops.size() == 1)
4797 return Ops[0];
4798
4799 // Find the max type first.
4800 Type *MaxType = nullptr;
4801 for (SCEVUse S : Ops)
4802 if (MaxType)
4803 MaxType = getWiderType(MaxType, S->getType());
4804 else
4805 MaxType = S->getType();
4806 assert(MaxType && "Failed to find maximum type!");
4807
4808 // Extend all ops to max type.
4809 SmallVector<SCEVUse, 2> PromotedOps;
4810 for (SCEVUse S : Ops)
4811 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4812
4813 // Generate umin.
4814 return getUMinExpr(PromotedOps, Sequential);
4815}
4816
4818 // A pointer operand may evaluate to a nonpointer expression, such as null.
4819 if (!V->getType()->isPointerTy())
4820 return V;
4821
4822 while (true) {
4823 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4824 V = AddRec->getStart();
4825 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4826 const SCEV *PtrOp = nullptr;
4827 for (const SCEV *AddOp : Add->operands()) {
4828 if (AddOp->getType()->isPointerTy()) {
4829 assert(!PtrOp && "Cannot have multiple pointer ops");
4830 PtrOp = AddOp;
4831 }
4832 }
4833 assert(PtrOp && "Must have pointer op");
4834 V = PtrOp;
4835 } else // Not something we can look further into.
4836 return V;
4837 }
4838}
4839
4840/// Push users of the given Instruction onto the given Worklist.
4844 // Push the def-use children onto the Worklist stack.
4845 for (User *U : I->users()) {
4846 auto *UserInsn = cast<Instruction>(U);
4847 if (Visited.insert(UserInsn).second)
4848 Worklist.push_back(UserInsn);
4849 }
4850}
4851
4852namespace {
4853
4854/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4855/// expression in case its Loop is L. If it is not L then
4856/// if IgnoreOtherLoops is true then use AddRec itself
4857/// otherwise rewrite cannot be done.
4858/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4859class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4860public:
4861 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4862 bool IgnoreOtherLoops = true) {
4863 SCEVInitRewriter Rewriter(L, SE);
4864 const SCEV *Result = Rewriter.visit(S);
4865 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4866 return SE.getCouldNotCompute();
4867 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4868 ? SE.getCouldNotCompute()
4869 : Result;
4870 }
4871
4872 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4873 if (!SE.isLoopInvariant(Expr, L))
4874 SeenLoopVariantSCEVUnknown = true;
4875 return Expr;
4876 }
4877
4878 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4879 // Only re-write AddRecExprs for this loop.
4880 if (Expr->getLoop() == L)
4881 return Expr->getStart();
4882 SeenOtherLoops = true;
4883 return Expr;
4884 }
4885
4886 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4887
4888 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4889
4890private:
4891 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4892 : SCEVRewriteVisitor(SE), L(L) {}
4893
4894 const Loop *L;
4895 bool SeenLoopVariantSCEVUnknown = false;
4896 bool SeenOtherLoops = false;
4897};
4898
4899/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4900/// increment expression in case its Loop is L. If it is not L then
4901/// use AddRec itself.
4902/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4903class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4904public:
4905 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4906 SCEVPostIncRewriter Rewriter(L, SE);
4907 const SCEV *Result = Rewriter.visit(S);
4908 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4909 ? SE.getCouldNotCompute()
4910 : Result;
4911 }
4912
4913 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4914 if (!SE.isLoopInvariant(Expr, L))
4915 SeenLoopVariantSCEVUnknown = true;
4916 return Expr;
4917 }
4918
4919 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4920 // Only re-write AddRecExprs for this loop.
4921 if (Expr->getLoop() == L)
4922 return Expr->getPostIncExpr(SE);
4923 SeenOtherLoops = true;
4924 return Expr;
4925 }
4926
4927 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4928
4929 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4930
4931private:
4932 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4933 : SCEVRewriteVisitor(SE), L(L) {}
4934
4935 const Loop *L;
4936 bool SeenLoopVariantSCEVUnknown = false;
4937 bool SeenOtherLoops = false;
4938};
4939
4940/// This class evaluates the compare condition by matching it against the
4941/// condition of loop latch. If there is a match we assume a true value
4942/// for the condition while building SCEV nodes.
4943class SCEVBackedgeConditionFolder
4944 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4945public:
4946 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4947 ScalarEvolution &SE) {
4948 bool IsPosBECond = false;
4949 Value *BECond = nullptr;
4950 if (BasicBlock *Latch = L->getLoopLatch()) {
4951 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4952 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4953 "Both outgoing branches should not target same header!");
4954 BECond = BI->getCondition();
4955 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4956 } else {
4957 return S;
4958 }
4959 }
4960 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4961 return Rewriter.visit(S);
4962 }
4963
4964 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4965 const SCEV *Result = Expr;
4966 bool InvariantF = SE.isLoopInvariant(Expr, L);
4967
4968 if (!InvariantF) {
4970 switch (I->getOpcode()) {
4971 case Instruction::Select: {
4972 SelectInst *SI = cast<SelectInst>(I);
4973 std::optional<const SCEV *> Res =
4974 compareWithBackedgeCondition(SI->getCondition());
4975 if (Res) {
4976 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4977 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4978 }
4979 break;
4980 }
4981 default: {
4982 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4983 if (Res)
4984 Result = *Res;
4985 break;
4986 }
4987 }
4988 }
4989 return Result;
4990 }
4991
4992private:
4993 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4994 bool IsPosBECond, ScalarEvolution &SE)
4995 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4996 IsPositiveBECond(IsPosBECond) {}
4997
4998 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4999
5000 const Loop *L;
5001 /// Loop back condition.
5002 Value *BackedgeCond = nullptr;
5003 /// Set to true if loop back is on positive branch condition.
5004 bool IsPositiveBECond;
5005};
5006
5007std::optional<const SCEV *>
5008SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5009
5010 // If value matches the backedge condition for loop latch,
5011 // then return a constant evolution node based on loopback
5012 // branch taken.
5013 if (BackedgeCond == IC)
5014 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5016 return std::nullopt;
5017}
5018
5019class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5020public:
5021 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5022 ScalarEvolution &SE) {
5023 SCEVShiftRewriter Rewriter(L, SE);
5024 const SCEV *Result = Rewriter.visit(S);
5025 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5026 }
5027
5028 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5029 // Only allow AddRecExprs for this loop.
5030 if (!SE.isLoopInvariant(Expr, L))
5031 Valid = false;
5032 return Expr;
5033 }
5034
5035 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5036 if (Expr->getLoop() == L && Expr->isAffine())
5037 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5038 Valid = false;
5039 return Expr;
5040 }
5041
5042 bool isValid() { return Valid; }
5043
5044private:
5045 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5046 : SCEVRewriteVisitor(SE), L(L) {}
5047
5048 const Loop *L;
5049 bool Valid = true;
5050};
5051
5052} // end anonymous namespace
5053
5054void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5055 if (!AR->isAffine())
5056 return;
5057
5058 // Force computation of ranges, which will also perform range-based flag
5059 // inference.
5060 if (!AR->hasNoSignedWrap())
5061 (void)getSignedRange(AR);
5062
5063 if (!AR->hasNoUnsignedWrap())
5064 (void)getUnsignedRange(AR);
5065
5066 if (!AR->hasNoSelfWrap()) {
5067 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5068 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5069 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5070 const APInt &BECountAP = BECountMax->getAPInt();
5071 unsigned NoOverflowBitWidth =
5072 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5073 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5074 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5075 }
5076 }
5077}
5078
5080ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5082
5083 if (AR->hasNoSignedWrap())
5084 return Result;
5085
5086 if (!AR->isAffine())
5087 return Result;
5088
5089 // This function can be expensive, only try to prove NSW once per AddRec.
5090 if (!SignedWrapViaInductionTried.insert(AR).second)
5091 return Result;
5092
5093 const SCEV *Step = AR->getStepRecurrence(*this);
5094 const Loop *L = AR->getLoop();
5095
5096 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5097 // Note that this serves two purposes: It filters out loops that are
5098 // simply not analyzable, and it covers the case where this code is
5099 // being called from within backedge-taken count analysis, such that
5100 // attempting to ask for the backedge-taken count would likely result
5101 // in infinite recursion. In the later case, the analysis code will
5102 // cope with a conservative value, and it will take care to purge
5103 // that value once it has finished.
5104 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5105
5106 // Normally, in the cases we can prove no-overflow via a
5107 // backedge guarding condition, we can also compute a backedge
5108 // taken count for the loop. The exceptions are assumptions and
5109 // guards present in the loop -- SCEV is not great at exploiting
5110 // these to compute max backedge taken counts, but can still use
5111 // these to prove lack of overflow. Use this fact to avoid
5112 // doing extra work that may not pay off.
5113
5114 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5115 AC.assumptions().empty())
5116 return Result;
5117
5118 // If the backedge is guarded by a comparison with the pre-inc value the
5119 // addrec is safe. Also, if the entry is guarded by a comparison with the
5120 // start value and the backedge is guarded by a comparison with the post-inc
5121 // value, the addrec is safe.
5123 const SCEV *OverflowLimit =
5124 getSignedOverflowLimitForStep(Step, &Pred, this);
5125 if (OverflowLimit &&
5126 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5127 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5128 Result = setFlags(Result, SCEV::FlagNSW);
5129 }
5130 return Result;
5131}
5133ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5135
5136 if (AR->hasNoUnsignedWrap())
5137 return Result;
5138
5139 if (!AR->isAffine())
5140 return Result;
5141
5142 // This function can be expensive, only try to prove NUW once per AddRec.
5143 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5144 return Result;
5145
5146 const SCEV *Step = AR->getStepRecurrence(*this);
5147 const Loop *L = AR->getLoop();
5148
5149 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5150 // Note that this serves two purposes: It filters out loops that are
5151 // simply not analyzable, and it covers the case where this code is
5152 // being called from within backedge-taken count analysis, such that
5153 // attempting to ask for the backedge-taken count would likely result
5154 // in infinite recursion. In the later case, the analysis code will
5155 // cope with a conservative value, and it will take care to purge
5156 // that value once it has finished.
5157 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5158
5159 // Normally, in the cases we can prove no-overflow via a
5160 // backedge guarding condition, we can also compute a backedge
5161 // taken count for the loop. The exceptions are assumptions and
5162 // guards present in the loop -- SCEV is not great at exploiting
5163 // these to compute max backedge taken counts, but can still use
5164 // these to prove lack of overflow. Use this fact to avoid
5165 // doing extra work that may not pay off.
5166
5167 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5168 AC.assumptions().empty())
5169 return Result;
5170
5171 // If the backedge is guarded by a comparison with the pre-inc value the
5172 // addrec is safe. Also, if the entry is guarded by a comparison with the
5173 // start value and the backedge is guarded by a comparison with the post-inc
5174 // value, the addrec is safe.
5175 if (isKnownPositive(Step)) {
5177 const SCEV *OverflowLimit =
5178 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5179 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5180 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5181 Result = setFlags(Result, SCEV::FlagNUW);
5182 }
5183 return Result;
5184}
5185
5186namespace {
5187
5188/// Represents an abstract binary operation. This may exist as a
5189/// normal instruction or constant expression, or may have been
5190/// derived from an expression tree.
5191struct BinaryOp {
5192 unsigned Opcode;
5193 Value *LHS;
5194 Value *RHS;
5195 bool IsNSW = false;
5196 bool IsNUW = false;
5197
5198 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5199 /// constant expression.
5200 Operator *Op = nullptr;
5201
5202 explicit BinaryOp(Operator *Op)
5203 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5204 Op(Op) {
5205 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5206 IsNSW = OBO->hasNoSignedWrap();
5207 IsNUW = OBO->hasNoUnsignedWrap();
5208 }
5209 }
5210
5211 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5212 bool IsNUW = false)
5213 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5214};
5215
5216} // end anonymous namespace
5217
5218/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5219static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5220 AssumptionCache &AC,
5221 const DominatorTree &DT,
5222 const Instruction *CxtI) {
5223 auto *Op = dyn_cast<Operator>(V);
5224 if (!Op)
5225 return std::nullopt;
5226
5227 // Implementation detail: all the cleverness here should happen without
5228 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5229 // SCEV expressions when possible, and we should not break that.
5230
5231 switch (Op->getOpcode()) {
5232 case Instruction::Add:
5233 case Instruction::Sub:
5234 case Instruction::Mul:
5235 case Instruction::UDiv:
5236 case Instruction::URem:
5237 case Instruction::And:
5238 case Instruction::AShr:
5239 case Instruction::Shl:
5240 return BinaryOp(Op);
5241
5242 case Instruction::Or: {
5243 // Convert or disjoint into add nuw nsw.
5244 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5245 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5246 /*IsNSW=*/true, /*IsNUW=*/true);
5247 // Keep the reference to the original instruction so that we can later
5248 // check whether it can produce poison value or not.
5249 BinOp.Op = Op;
5250 return BinOp;
5251 }
5252 return BinaryOp(Op);
5253 }
5254
5255 case Instruction::Xor:
5256 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5257 // If the RHS of the xor is a signmask, then this is just an add.
5258 // Instcombine turns add of signmask into xor as a strength reduction step.
5259 if (RHSC->getValue().isSignMask())
5260 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5261 // Binary `xor` is a bit-wise `add`.
5262 if (V->getType()->isIntegerTy(1))
5263 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5264 return BinaryOp(Op);
5265
5266 case Instruction::LShr:
5267 // Turn logical shift right of a constant into a unsigned divide.
5268 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5269 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5270
5271 // If the shift count is not less than the bitwidth, the result of
5272 // the shift is undefined. Don't try to analyze it, because the
5273 // resolution chosen here may differ from the resolution chosen in
5274 // other parts of the compiler.
5275 if (SA->getValue().ult(BitWidth)) {
5276 Constant *X =
5277 ConstantInt::get(SA->getContext(),
5278 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5279 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5280 }
5281 }
5282 return BinaryOp(Op);
5283
5284 case Instruction::ExtractValue: {
5285 auto *EVI = cast<ExtractValueInst>(Op);
5286 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5287 break;
5288
5289 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5290 if (!WO)
5291 break;
5292
5293 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5294 bool Signed = WO->isSigned();
5295 // TODO: Should add nuw/nsw flags for mul as well.
5296 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5297 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5298
5299 // Now that we know that all uses of the arithmetic-result component of
5300 // CI are guarded by the overflow check, we can go ahead and pretend
5301 // that the arithmetic is non-overflowing.
5302 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5303 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5304 }
5305
5306 default:
5307 break;
5308 }
5309
5310 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5311 // semantics as a Sub, return a binary sub expression.
5312 if (auto *II = dyn_cast<IntrinsicInst>(V))
5313 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5314 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5315
5316 return std::nullopt;
5317}
5318
5319/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5320/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5321/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5322/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5323/// follows one of the following patterns:
5324/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5325/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5326/// If the SCEV expression of \p Op conforms with one of the expected patterns
5327/// we return the type of the truncation operation, and indicate whether the
5328/// truncated type should be treated as signed/unsigned by setting
5329/// \p Signed to true/false, respectively.
5330static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5331 bool &Signed, ScalarEvolution &SE) {
5332 // The case where Op == SymbolicPHI (that is, with no type conversions on
5333 // the way) is handled by the regular add recurrence creating logic and
5334 // would have already been triggered in createAddRecForPHI. Reaching it here
5335 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5336 // because one of the other operands of the SCEVAddExpr updating this PHI is
5337 // not invariant).
5338 //
5339 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5340 // this case predicates that allow us to prove that Op == SymbolicPHI will
5341 // be added.
5342 if (Op == SymbolicPHI)
5343 return nullptr;
5344
5345 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5346 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5347 if (SourceBits != NewBits)
5348 return nullptr;
5349
5350 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5351 Signed = true;
5352 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5353 }
5354 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5355 Signed = false;
5356 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5357 }
5358 return nullptr;
5359}
5360
5361static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5362 if (!PN->getType()->isIntegerTy())
5363 return nullptr;
5364 const Loop *L = LI.getLoopFor(PN->getParent());
5365 if (!L || L->getHeader() != PN->getParent())
5366 return nullptr;
5367 return L;
5368}
5369
5370// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5371// computation that updates the phi follows the following pattern:
5372// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5373// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5374// If so, try to see if it can be rewritten as an AddRecExpr under some
5375// Predicates. If successful, return them as a pair. Also cache the results
5376// of the analysis.
5377//
5378// Example usage scenario:
5379// Say the Rewriter is called for the following SCEV:
5380// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5381// where:
5382// %X = phi i64 (%Start, %BEValue)
5383// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5384// and call this function with %SymbolicPHI = %X.
5385//
5386// The analysis will find that the value coming around the backedge has
5387// the following SCEV:
5388// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5389// Upon concluding that this matches the desired pattern, the function
5390// will return the pair {NewAddRec, SmallPredsVec} where:
5391// NewAddRec = {%Start,+,%Step}
5392// SmallPredsVec = {P1, P2, P3} as follows:
5393// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5394// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5395// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5396// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5397// under the predicates {P1,P2,P3}.
5398// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5399// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5400//
5401// TODO's:
5402//
5403// 1) Extend the Induction descriptor to also support inductions that involve
5404// casts: When needed (namely, when we are called in the context of the
5405// vectorizer induction analysis), a Set of cast instructions will be
5406// populated by this method, and provided back to isInductionPHI. This is
5407// needed to allow the vectorizer to properly record them to be ignored by
5408// the cost model and to avoid vectorizing them (otherwise these casts,
5409// which are redundant under the runtime overflow checks, will be
5410// vectorized, which can be costly).
5411//
5412// 2) Support additional induction/PHISCEV patterns: We also want to support
5413// inductions where the sext-trunc / zext-trunc operations (partly) occur
5414// after the induction update operation (the induction increment):
5415//
5416// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5417// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5418//
5419// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5420// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5421//
5422// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5423std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5424ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5426
5427 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5428 // return an AddRec expression under some predicate.
5429
5430 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5431 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5432 assert(L && "Expecting an integer loop header phi");
5433
5434 // The loop may have multiple entrances or multiple exits; we can analyze
5435 // this phi as an addrec if it has a unique entry value and a unique
5436 // backedge value.
5437 Value *BEValueV = nullptr, *StartValueV = nullptr;
5438 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5439 Value *V = PN->getIncomingValue(i);
5440 if (L->contains(PN->getIncomingBlock(i))) {
5441 if (!BEValueV) {
5442 BEValueV = V;
5443 } else if (BEValueV != V) {
5444 BEValueV = nullptr;
5445 break;
5446 }
5447 } else if (!StartValueV) {
5448 StartValueV = V;
5449 } else if (StartValueV != V) {
5450 StartValueV = nullptr;
5451 break;
5452 }
5453 }
5454 if (!BEValueV || !StartValueV)
5455 return std::nullopt;
5456
5457 const SCEV *BEValue = getSCEV(BEValueV);
5458
5459 // If the value coming around the backedge is an add with the symbolic
5460 // value we just inserted, possibly with casts that we can ignore under
5461 // an appropriate runtime guard, then we found a simple induction variable!
5462 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5463 if (!Add)
5464 return std::nullopt;
5465
5466 // If there is a single occurrence of the symbolic value, possibly
5467 // casted, replace it with a recurrence.
5468 unsigned FoundIndex = Add->getNumOperands();
5469 Type *TruncTy = nullptr;
5470 bool Signed;
5471 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5472 if ((TruncTy =
5473 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5474 if (FoundIndex == e) {
5475 FoundIndex = i;
5476 break;
5477 }
5478
5479 if (FoundIndex == Add->getNumOperands())
5480 return std::nullopt;
5481
5482 // Create an add with everything but the specified operand.
5484 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5485 if (i != FoundIndex)
5486 Ops.push_back(Add->getOperand(i));
5487 const SCEV *Accum = getAddExpr(Ops);
5488
5489 // The runtime checks will not be valid if the step amount is
5490 // varying inside the loop.
5491 if (!isLoopInvariant(Accum, L))
5492 return std::nullopt;
5493
5494 // *** Part2: Create the predicates
5495
5496 // Analysis was successful: we have a phi-with-cast pattern for which we
5497 // can return an AddRec expression under the following predicates:
5498 //
5499 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5500 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5501 // P2: An Equal predicate that guarantees that
5502 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5503 // P3: An Equal predicate that guarantees that
5504 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5505 //
5506 // As we next prove, the above predicates guarantee that:
5507 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5508 //
5509 //
5510 // More formally, we want to prove that:
5511 // Expr(i+1) = Start + (i+1) * Accum
5512 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5513 //
5514 // Given that:
5515 // 1) Expr(0) = Start
5516 // 2) Expr(1) = Start + Accum
5517 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5518 // 3) Induction hypothesis (step i):
5519 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5520 //
5521 // Proof:
5522 // Expr(i+1) =
5523 // = Start + (i+1)*Accum
5524 // = (Start + i*Accum) + Accum
5525 // = Expr(i) + Accum
5526 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5527 // :: from step i
5528 //
5529 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5530 //
5531 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5532 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5533 // + Accum :: from P3
5534 //
5535 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5536 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5537 //
5538 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5539 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5540 //
5541 // By induction, the same applies to all iterations 1<=i<n:
5542 //
5543
5544 // Create a truncated addrec for which we will add a no overflow check (P1).
5545 const SCEV *StartVal = getSCEV(StartValueV);
5546 const SCEV *PHISCEV =
5547 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5548 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5549
5550 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5551 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5552 // will be constant.
5553 //
5554 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5555 // add P1.
5556 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5560 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5561 Predicates.push_back(AddRecPred);
5562 }
5563
5564 // Create the Equal Predicates P2,P3:
5565
5566 // It is possible that the predicates P2 and/or P3 are computable at
5567 // compile time due to StartVal and/or Accum being constants.
5568 // If either one is, then we can check that now and escape if either P2
5569 // or P3 is false.
5570
5571 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5572 // for each of StartVal and Accum
5573 auto getExtendedExpr = [&](const SCEV *Expr,
5574 bool CreateSignExtend) -> const SCEV * {
5575 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5576 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5577 const SCEV *ExtendedExpr =
5578 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5579 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5580 return ExtendedExpr;
5581 };
5582
5583 // Given:
5584 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5585 // = getExtendedExpr(Expr)
5586 // Determine whether the predicate P: Expr == ExtendedExpr
5587 // is known to be false at compile time
5588 auto PredIsKnownFalse = [&](const SCEV *Expr,
5589 const SCEV *ExtendedExpr) -> bool {
5590 return Expr != ExtendedExpr &&
5591 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5592 };
5593
5594 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5595 if (PredIsKnownFalse(StartVal, StartExtended)) {
5596 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5597 return std::nullopt;
5598 }
5599
5600 // The Step is always Signed (because the overflow checks are either
5601 // NSSW or NUSW)
5602 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5603 if (PredIsKnownFalse(Accum, AccumExtended)) {
5604 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5605 return std::nullopt;
5606 }
5607
5608 auto AppendPredicate = [&](const SCEV *Expr,
5609 const SCEV *ExtendedExpr) -> void {
5610 if (Expr != ExtendedExpr &&
5611 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5612 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5613 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5614 Predicates.push_back(Pred);
5615 }
5616 };
5617
5618 AppendPredicate(StartVal, StartExtended);
5619 AppendPredicate(Accum, AccumExtended);
5620
5621 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5622 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5623 // into NewAR if it will also add the runtime overflow checks specified in
5624 // Predicates.
5625 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5626
5627 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5628 std::make_pair(NewAR, Predicates);
5629 // Remember the result of the analysis for this SCEV at this locayyytion.
5630 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5631 return PredRewrite;
5632}
5633
5634std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5636 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5637 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5638 if (!L)
5639 return std::nullopt;
5640
5641 // Check to see if we already analyzed this PHI.
5642 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5643 if (I != PredicatedSCEVRewrites.end()) {
5644 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5645 I->second;
5646 // Analysis was done before and failed to create an AddRec:
5647 if (Rewrite.first == SymbolicPHI)
5648 return std::nullopt;
5649 // Analysis was done before and succeeded to create an AddRec under
5650 // a predicate:
5651 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5652 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5653 return Rewrite;
5654 }
5655
5656 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5657 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5658
5659 // Record in the cache that the analysis failed
5660 if (!Rewrite) {
5662 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5663 return std::nullopt;
5664 }
5665
5666 return Rewrite;
5667}
5668
5669// FIXME: This utility is currently required because the Rewriter currently
5670// does not rewrite this expression:
5671// {0, +, (sext ix (trunc iy to ix) to iy)}
5672// into {0, +, %step},
5673// even when the following Equal predicate exists:
5674// "%step == (sext ix (trunc iy to ix) to iy)".
5676 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5677 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5678 if (AR1 == AR2)
5679 return true;
5680
5681 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5682 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5683 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5684 if (Expr1 != Expr2 &&
5685 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5686 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5687 return false;
5688 return true;
5689 };
5690
5691 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5692 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5693 return false;
5694 return true;
5695}
5696
5697/// A helper function for createAddRecFromPHI to handle simple cases.
5698///
5699/// This function tries to find an AddRec expression for the simplest (yet most
5700/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5701/// If it fails, createAddRecFromPHI will use a more general, but slow,
5702/// technique for finding the AddRec expression.
5703const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5704 Value *BEValueV,
5705 Value *StartValueV) {
5706 const Loop *L = LI.getLoopFor(PN->getParent());
5707 assert(L && L->getHeader() == PN->getParent());
5708 assert(BEValueV && StartValueV);
5709
5710 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5711 if (!BO)
5712 return nullptr;
5713
5714 if (BO->Opcode != Instruction::Add)
5715 return nullptr;
5716
5717 const SCEV *Accum = nullptr;
5718 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5719 Accum = getSCEV(BO->RHS);
5720 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5721 Accum = getSCEV(BO->LHS);
5722
5723 if (!Accum)
5724 return nullptr;
5725
5727 if (BO->IsNUW)
5728 Flags = setFlags(Flags, SCEV::FlagNUW);
5729 if (BO->IsNSW)
5730 Flags = setFlags(Flags, SCEV::FlagNSW);
5731
5732 const SCEV *StartVal = getSCEV(StartValueV);
5733 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5734 insertValueToMap(PN, PHISCEV);
5735
5736 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5737 inferNoWrapViaConstantRanges(AR);
5738
5739 // We can add Flags to the post-inc expression only if we
5740 // know that it is *undefined behavior* for BEValueV to
5741 // overflow.
5742 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5743 assert(isLoopInvariant(Accum, L) &&
5744 "Accum is defined outside L, but is not invariant?");
5745 if (isAddRecNeverPoison(BEInst, L))
5746 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5747 }
5748
5749 return PHISCEV;
5750}
5751
5752const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5753 const Loop *L = LI.getLoopFor(PN->getParent());
5754 if (!L || L->getHeader() != PN->getParent())
5755 return nullptr;
5756
5757 // The loop may have multiple entrances or multiple exits; we can analyze
5758 // this phi as an addrec if it has a unique entry value and a unique
5759 // backedge value.
5760 Value *BEValueV = nullptr, *StartValueV = nullptr;
5761 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5762 Value *V = PN->getIncomingValue(i);
5763 if (L->contains(PN->getIncomingBlock(i))) {
5764 if (!BEValueV) {
5765 BEValueV = V;
5766 } else if (BEValueV != V) {
5767 BEValueV = nullptr;
5768 break;
5769 }
5770 } else if (!StartValueV) {
5771 StartValueV = V;
5772 } else if (StartValueV != V) {
5773 StartValueV = nullptr;
5774 break;
5775 }
5776 }
5777 if (!BEValueV || !StartValueV)
5778 return nullptr;
5779
5780 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5781 "PHI node already processed?");
5782
5783 // First, try to find AddRec expression without creating a fictituos symbolic
5784 // value for PN.
5785 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5786 return S;
5787
5788 // Handle PHI node value symbolically.
5789 const SCEV *SymbolicName = getUnknown(PN);
5790 insertValueToMap(PN, SymbolicName);
5791
5792 // Using this symbolic name for the PHI, analyze the value coming around
5793 // the back-edge.
5794 const SCEV *BEValue = getSCEV(BEValueV);
5795
5796 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5797 // has a special value for the first iteration of the loop.
5798
5799 // If the value coming around the backedge is an add with the symbolic
5800 // value we just inserted, then we found a simple induction variable!
5801 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5802 // If there is a single occurrence of the symbolic value, replace it
5803 // with a recurrence.
5804 unsigned FoundIndex = Add->getNumOperands();
5805 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5806 if (Add->getOperand(i) == SymbolicName)
5807 if (FoundIndex == e) {
5808 FoundIndex = i;
5809 break;
5810 }
5811
5812 if (FoundIndex != Add->getNumOperands()) {
5813 // Create an add with everything but the specified operand.
5815 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5816 if (i != FoundIndex)
5817 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5818 L, *this));
5819 const SCEV *Accum = getAddExpr(Ops);
5820
5821 // This is not a valid addrec if the step amount is varying each
5822 // loop iteration, but is not itself an addrec in this loop.
5823 if (isLoopInvariant(Accum, L) ||
5824 (isa<SCEVAddRecExpr>(Accum) &&
5825 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5827
5828 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5829 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5830 if (BO->IsNUW)
5831 Flags = setFlags(Flags, SCEV::FlagNUW);
5832 if (BO->IsNSW)
5833 Flags = setFlags(Flags, SCEV::FlagNSW);
5834 }
5835 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5836 if (GEP->getOperand(0) == PN) {
5837 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5838 // If the increment has any nowrap flags, then we know the address
5839 // space cannot be wrapped around.
5840 if (NW != GEPNoWrapFlags::none())
5841 Flags = setFlags(Flags, SCEV::FlagNW);
5842 // If the GEP is nuw or nusw with non-negative offset, we know that
5843 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5844 // offset is treated as signed, while the base is unsigned.
5845 if (NW.hasNoUnsignedWrap() ||
5847 Flags = setFlags(Flags, SCEV::FlagNUW);
5848 }
5849
5850 // We cannot transfer nuw and nsw flags from subtraction
5851 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5852 // for instance.
5853 }
5854
5855 const SCEV *StartVal = getSCEV(StartValueV);
5856 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5857
5858 // Okay, for the entire analysis of this edge we assumed the PHI
5859 // to be symbolic. We now need to go back and purge all of the
5860 // entries for the scalars that use the symbolic expression.
5861 forgetMemoizedResults({SymbolicName});
5862 insertValueToMap(PN, PHISCEV);
5863
5864 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5865 inferNoWrapViaConstantRanges(AR);
5866
5867 // We can add Flags to the post-inc expression only if we
5868 // know that it is *undefined behavior* for BEValueV to
5869 // overflow.
5870 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5871 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5872 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5873
5874 return PHISCEV;
5875 }
5876 }
5877 } else {
5878 // Otherwise, this could be a loop like this:
5879 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5880 // In this case, j = {1,+,1} and BEValue is j.
5881 // Because the other in-value of i (0) fits the evolution of BEValue
5882 // i really is an addrec evolution.
5883 //
5884 // We can generalize this saying that i is the shifted value of BEValue
5885 // by one iteration:
5886 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5887
5888 // Do not allow refinement in rewriting of BEValue.
5889 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5890 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5891 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5892 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5893 const SCEV *StartVal = getSCEV(StartValueV);
5894 if (Start == StartVal) {
5895 // Okay, for the entire analysis of this edge we assumed the PHI
5896 // to be symbolic. We now need to go back and purge all of the
5897 // entries for the scalars that use the symbolic expression.
5898 forgetMemoizedResults({SymbolicName});
5899 insertValueToMap(PN, Shifted);
5900 return Shifted;
5901 }
5902 }
5903 }
5904
5905 // Remove the temporary PHI node SCEV that has been inserted while intending
5906 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5907 // as it will prevent later (possibly simpler) SCEV expressions to be added
5908 // to the ValueExprMap.
5909 eraseValueFromMap(PN);
5910
5911 return nullptr;
5912}
5913
5914// Try to match a control flow sequence that branches out at BI and merges back
5915// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5916// match.
5918 Value *&C, Value *&LHS, Value *&RHS) {
5919 C = BI->getCondition();
5920
5921 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5922 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5923
5924 Use &LeftUse = Merge->getOperandUse(0);
5925 Use &RightUse = Merge->getOperandUse(1);
5926
5927 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5928 LHS = LeftUse;
5929 RHS = RightUse;
5930 return true;
5931 }
5932
5933 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5934 LHS = RightUse;
5935 RHS = LeftUse;
5936 return true;
5937 }
5938
5939 return false;
5940}
5941
5943 Value *&Cond, Value *&LHS,
5944 Value *&RHS) {
5945 auto IsReachable =
5946 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5947 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5948 // Try to match
5949 //
5950 // br %cond, label %left, label %right
5951 // left:
5952 // br label %merge
5953 // right:
5954 // br label %merge
5955 // merge:
5956 // V = phi [ %x, %left ], [ %y, %right ]
5957 //
5958 // as "select %cond, %x, %y"
5959
5960 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5961 assert(IDom && "At least the entry block should dominate PN");
5962
5963 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5964 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5965 }
5966 return false;
5967}
5968
5969const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5970 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5971 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5974 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5975
5976 return nullptr;
5977}
5978
5980 BinaryOperator *CommonInst = nullptr;
5981 // Check if instructions are identical.
5982 for (Value *Incoming : PN->incoming_values()) {
5983 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5984 if (!IncomingInst)
5985 return nullptr;
5986 if (CommonInst) {
5987 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5988 return nullptr; // Not identical, give up
5989 } else {
5990 // Remember binary operator
5991 CommonInst = IncomingInst;
5992 }
5993 }
5994 return CommonInst;
5995}
5996
5997/// Returns SCEV for the first operand of a phi if all phi operands have
5998/// identical opcodes and operands
5999/// eg.
6000/// a: %add = %a + %b
6001/// br %c
6002/// b: %add1 = %a + %b
6003/// br %c
6004/// c: %phi = phi [%add, a], [%add1, b]
6005/// scev(%phi) => scev(%add)
6006const SCEV *
6007ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6008 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6009 if (!CommonInst)
6010 return nullptr;
6011
6012 // Check if SCEV exprs for instructions are identical.
6013 const SCEV *CommonSCEV = getSCEV(CommonInst);
6014 bool SCEVExprsIdentical =
6016 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6017 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6018}
6019
6020const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6021 if (const SCEV *S = createAddRecFromPHI(PN))
6022 return S;
6023
6024 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6025 // phi node for X.
6026 if (Value *V = simplifyInstruction(
6027 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6028 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6029 return getSCEV(V);
6030
6031 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6032 return S;
6033
6034 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6035 return S;
6036
6037 // If it's not a loop phi, we can't handle it yet.
6038 return getUnknown(PN);
6039}
6040
6041bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6042 SCEVTypes RootKind) {
6043 struct FindClosure {
6044 const SCEV *OperandToFind;
6045 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6046 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6047
6048 bool Found = false;
6049
6050 bool canRecurseInto(SCEVTypes Kind) const {
6051 // We can only recurse into the SCEV expression of the same effective type
6052 // as the type of our root SCEV expression, and into zero-extensions.
6053 return RootKind == Kind || NonSequentialRootKind == Kind ||
6054 scZeroExtend == Kind;
6055 };
6056
6057 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6058 : OperandToFind(OperandToFind), RootKind(RootKind),
6059 NonSequentialRootKind(
6061 RootKind)) {}
6062
6063 bool follow(const SCEV *S) {
6064 Found = S == OperandToFind;
6065
6066 return !isDone() && canRecurseInto(S->getSCEVType());
6067 }
6068
6069 bool isDone() const { return Found; }
6070 };
6071
6072 FindClosure FC(OperandToFind, RootKind);
6073 visitAll(Root, FC);
6074 return FC.Found;
6075}
6076
6077std::optional<const SCEV *>
6078ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6079 ICmpInst *Cond,
6080 Value *TrueVal,
6081 Value *FalseVal) {
6082 // Try to match some simple smax or umax patterns.
6083 auto *ICI = Cond;
6084
6085 Value *LHS = ICI->getOperand(0);
6086 Value *RHS = ICI->getOperand(1);
6087
6088 switch (ICI->getPredicate()) {
6089 case ICmpInst::ICMP_SLT:
6090 case ICmpInst::ICMP_SLE:
6091 case ICmpInst::ICMP_ULT:
6092 case ICmpInst::ICMP_ULE:
6093 std::swap(LHS, RHS);
6094 [[fallthrough]];
6095 case ICmpInst::ICMP_SGT:
6096 case ICmpInst::ICMP_SGE:
6097 case ICmpInst::ICMP_UGT:
6098 case ICmpInst::ICMP_UGE:
6099 // a > b ? a+x : b+x -> max(a, b)+x
6100 // a > b ? b+x : a+x -> min(a, b)+x
6102 bool Signed = ICI->isSigned();
6103 const SCEV *LA = getSCEV(TrueVal);
6104 const SCEV *RA = getSCEV(FalseVal);
6105 const SCEV *LS = getSCEV(LHS);
6106 const SCEV *RS = getSCEV(RHS);
6107 if (LA->getType()->isPointerTy()) {
6108 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6109 // Need to make sure we can't produce weird expressions involving
6110 // negated pointers.
6111 if (LA == LS && RA == RS)
6112 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6113 if (LA == RS && RA == LS)
6114 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6115 }
6116 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6117 if (Op->getType()->isPointerTy()) {
6120 return Op;
6121 }
6122 if (Signed)
6123 Op = getNoopOrSignExtend(Op, Ty);
6124 else
6125 Op = getNoopOrZeroExtend(Op, Ty);
6126 return Op;
6127 };
6128 LS = CoerceOperand(LS);
6129 RS = CoerceOperand(RS);
6131 break;
6132 const SCEV *LDiff = getMinusSCEV(LA, LS);
6133 const SCEV *RDiff = getMinusSCEV(RA, RS);
6134 if (LDiff == RDiff)
6135 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6136 LDiff);
6137 LDiff = getMinusSCEV(LA, RS);
6138 RDiff = getMinusSCEV(RA, LS);
6139 if (LDiff == RDiff)
6140 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6141 LDiff);
6142 }
6143 break;
6144 case ICmpInst::ICMP_NE:
6145 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6146 std::swap(TrueVal, FalseVal);
6147 [[fallthrough]];
6148 case ICmpInst::ICMP_EQ:
6149 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6152 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6153 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6154 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6155 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6156 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6157 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6158 return getAddExpr(getUMaxExpr(X, C), Y);
6159 }
6160 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6161 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6162 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6163 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6165 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6166 const SCEV *X = getSCEV(LHS);
6167 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6168 X = ZExt->getOperand();
6169 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6170 const SCEV *FalseValExpr = getSCEV(FalseVal);
6171 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6172 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6173 /*Sequential=*/true);
6174 }
6175 }
6176 break;
6177 default:
6178 break;
6179 }
6180
6181 return std::nullopt;
6182}
6183
6184static std::optional<const SCEV *>
6186 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6187 assert(CondExpr->getType()->isIntegerTy(1) &&
6188 TrueExpr->getType() == FalseExpr->getType() &&
6189 TrueExpr->getType()->isIntegerTy(1) &&
6190 "Unexpected operands of a select.");
6191
6192 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6193 // --> C + (umin_seq cond, x - C)
6194 //
6195 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6196 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6197 // --> C + (umin_seq ~cond, x - C)
6198
6199 // FIXME: while we can't legally model the case where both of the hands
6200 // are fully variable, we only require that the *difference* is constant.
6201 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6202 return std::nullopt;
6203
6204 const SCEV *X, *C;
6205 if (isa<SCEVConstant>(TrueExpr)) {
6206 CondExpr = SE->getNotSCEV(CondExpr);
6207 X = FalseExpr;
6208 C = TrueExpr;
6209 } else {
6210 X = TrueExpr;
6211 C = FalseExpr;
6212 }
6213 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6214 /*Sequential=*/true));
6215}
6216
6217static std::optional<const SCEV *>
6219 Value *FalseVal) {
6220 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6221 return std::nullopt;
6222
6223 const auto *SECond = SE->getSCEV(Cond);
6224 const auto *SETrue = SE->getSCEV(TrueVal);
6225 const auto *SEFalse = SE->getSCEV(FalseVal);
6226 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6227}
6228
6229const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6230 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6231 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6232 assert(TrueVal->getType() == FalseVal->getType() &&
6233 V->getType() == TrueVal->getType() &&
6234 "Types of select hands and of the result must match.");
6235
6236 // For now, only deal with i1-typed `select`s.
6237 if (!V->getType()->isIntegerTy(1))
6238 return getUnknown(V);
6239
6240 if (std::optional<const SCEV *> S =
6241 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6242 return *S;
6243
6244 return getUnknown(V);
6245}
6246
6247const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6248 Value *TrueVal,
6249 Value *FalseVal) {
6250 // Handle "constant" branch or select. This can occur for instance when a
6251 // loop pass transforms an inner loop and moves on to process the outer loop.
6252 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6253 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6254
6255 if (auto *I = dyn_cast<Instruction>(V)) {
6256 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6257 if (std::optional<const SCEV *> S =
6258 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6259 TrueVal, FalseVal))
6260 return *S;
6261 }
6262 }
6263
6264 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6265}
6266
6267/// Expand GEP instructions into add and multiply operations. This allows them
6268/// to be analyzed by regular SCEV code.
6269const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6270 assert(GEP->getSourceElementType()->isSized() &&
6271 "GEP source element type must be sized");
6272
6273 SmallVector<SCEVUse, 4> IndexExprs;
6274 for (Value *Index : GEP->indices())
6275 IndexExprs.push_back(getSCEV(Index));
6276 return getGEPExpr(GEP, IndexExprs);
6277}
6278
6279APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6280 const Instruction *CtxI) {
6282 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6283 return TrailingZeros >= BitWidth
6285 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6286 };
6287 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6288 // The result is GCD of all operands results.
6289 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6290 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6292 Res, getConstantMultiple(N->getOperand(I), CtxI));
6293 return Res;
6294 };
6295
6296 switch (S->getSCEVType()) {
6297 case scConstant:
6298 return cast<SCEVConstant>(S)->getAPInt();
6299 case scPtrToAddr:
6300 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6301 case scUDivExpr:
6302 case scVScale:
6303 return APInt(BitWidth, 1);
6304 case scTruncate: {
6305 // Only multiples that are a power of 2 will hold after truncation.
6306 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6307 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6308 return GetShiftedByZeros(TZ);
6309 }
6310 case scZeroExtend: {
6311 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6312 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6313 }
6314 case scSignExtend: {
6315 // Only multiples that are a power of 2 will hold after sext.
6316 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6317 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6318 return GetShiftedByZeros(TZ);
6319 }
6320 case scMulExpr: {
6321 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6322 if (M->hasNoUnsignedWrap()) {
6323 // The result is the product of all operand results.
6324 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6325 for (const SCEV *Operand : M->operands().drop_front())
6326 Res = Res * getConstantMultiple(Operand, CtxI);
6327 return Res;
6328 }
6329
6330 // If there are no wrap guarentees, find the trailing zeros, which is the
6331 // sum of trailing zeros for all its operands.
6332 uint32_t TZ = 0;
6333 for (const SCEV *Operand : M->operands())
6334 TZ += getMinTrailingZeros(Operand, CtxI);
6335 return GetShiftedByZeros(TZ);
6336 }
6337 case scAddExpr:
6338 case scAddRecExpr: {
6339 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6340 if (N->hasNoUnsignedWrap())
6341 return GetGCDMultiple(N);
6342 // Find the trailing bits, which is the minimum of its operands.
6343 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6344 for (const SCEV *Operand : N->operands().drop_front())
6345 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6346 return GetShiftedByZeros(TZ);
6347 }
6348 case scUMaxExpr:
6349 case scSMaxExpr:
6350 case scUMinExpr:
6351 case scSMinExpr:
6353 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6354 case scUnknown: {
6355 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6356 // the point their underlying IR instruction has been defined. If CtxI was
6357 // not provided, use:
6358 // * the first instruction in the entry block if it is an argument
6359 // * the instruction itself otherwise.
6360 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6361 if (!CtxI) {
6362 if (isa<Argument>(U->getValue()))
6363 CtxI = &*F.getEntryBlock().begin();
6364 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6365 CtxI = I;
6366 }
6367 unsigned Known =
6368 computeKnownBits(U->getValue(),
6369 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6370 .allowEphemerals(true))
6371 .countMinTrailingZeros();
6372 return GetShiftedByZeros(Known);
6373 }
6374 case scCouldNotCompute:
6375 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6376 }
6377 llvm_unreachable("Unknown SCEV kind!");
6378}
6379
6381 const Instruction *CtxI) {
6382 // Skip looking up and updating the cache if there is a context instruction,
6383 // as the result will only be valid in the specified context.
6384 if (CtxI)
6385 return getConstantMultipleImpl(S, CtxI);
6386
6387 auto I = ConstantMultipleCache.find(S);
6388 if (I != ConstantMultipleCache.end())
6389 return I->second;
6390
6391 APInt Result = getConstantMultipleImpl(S, CtxI);
6392 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6393 assert(InsertPair.second && "Should insert a new key");
6394 return InsertPair.first->second;
6395}
6396
6398 APInt Multiple = getConstantMultiple(S);
6399 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6400}
6401
6403 const Instruction *CtxI) {
6404 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6405 (unsigned)getTypeSizeInBits(S->getType()));
6406}
6407
6408/// Helper method to assign a range to V from metadata present in the IR.
6409static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6411 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6412 return getConstantRangeFromMetadata(*MD);
6413 if (const auto *CB = dyn_cast<CallBase>(V))
6414 if (std::optional<ConstantRange> Range = CB->getRange())
6415 return Range;
6416 }
6417 if (auto *A = dyn_cast<Argument>(V))
6418 if (std::optional<ConstantRange> Range = A->getRange())
6419 return Range;
6420
6421 return std::nullopt;
6422}
6423
6425 SCEV::NoWrapFlags Flags) {
6426 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6427 AddRec->setNoWrapFlags(Flags);
6428 UnsignedRanges.erase(AddRec);
6429 SignedRanges.erase(AddRec);
6430 ConstantMultipleCache.erase(AddRec);
6431 }
6432}
6433
6434ConstantRange ScalarEvolution::
6435getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6436 const DataLayout &DL = getDataLayout();
6437
6438 unsigned BitWidth = getTypeSizeInBits(U->getType());
6439 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6440
6441 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6442 // use information about the trip count to improve our available range. Note
6443 // that the trip count independent cases are already handled by known bits.
6444 // WARNING: The definition of recurrence used here is subtly different than
6445 // the one used by AddRec (and thus most of this file). Step is allowed to
6446 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6447 // and other addrecs in the same loop (for non-affine addrecs). The code
6448 // below intentionally handles the case where step is not loop invariant.
6449 auto *P = dyn_cast<PHINode>(U->getValue());
6450 if (!P)
6451 return FullSet;
6452
6453 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6454 // even the values that are not available in these blocks may come from them,
6455 // and this leads to false-positive recurrence test.
6456 for (auto *Pred : predecessors(P->getParent()))
6457 if (!DT.isReachableFromEntry(Pred))
6458 return FullSet;
6459
6460 BinaryOperator *BO;
6461 Value *Start, *Step;
6462 if (!matchSimpleRecurrence(P, BO, Start, Step))
6463 return FullSet;
6464
6465 // If we found a recurrence in reachable code, we must be in a loop. Note
6466 // that BO might be in some subloop of L, and that's completely okay.
6467 auto *L = LI.getLoopFor(P->getParent());
6468 assert(L && L->getHeader() == P->getParent());
6469 if (!L->contains(BO->getParent()))
6470 // NOTE: This bailout should be an assert instead. However, asserting
6471 // the condition here exposes a case where LoopFusion is querying SCEV
6472 // with malformed loop information during the midst of the transform.
6473 // There doesn't appear to be an obvious fix, so for the moment bailout
6474 // until the caller issue can be fixed. PR49566 tracks the bug.
6475 return FullSet;
6476
6477 // TODO: Extend to other opcodes such as mul, and div
6478 switch (BO->getOpcode()) {
6479 default:
6480 return FullSet;
6481 case Instruction::AShr:
6482 case Instruction::LShr:
6483 case Instruction::Shl:
6484 break;
6485 };
6486
6487 if (BO->getOperand(0) != P)
6488 // TODO: Handle the power function forms some day.
6489 return FullSet;
6490
6491 unsigned TC = getSmallConstantMaxTripCount(L);
6492 if (!TC || TC >= BitWidth)
6493 return FullSet;
6494
6495 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6496 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6497 assert(KnownStart.getBitWidth() == BitWidth &&
6498 KnownStep.getBitWidth() == BitWidth);
6499
6500 // Compute total shift amount, being careful of overflow and bitwidths.
6501 auto MaxShiftAmt = KnownStep.getMaxValue();
6502 APInt TCAP(BitWidth, TC-1);
6503 bool Overflow = false;
6504 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6505 if (Overflow)
6506 return FullSet;
6507
6508 switch (BO->getOpcode()) {
6509 default:
6510 llvm_unreachable("filtered out above");
6511 case Instruction::AShr: {
6512 // For each ashr, three cases:
6513 // shift = 0 => unchanged value
6514 // saturation => 0 or -1
6515 // other => a value closer to zero (of the same sign)
6516 // Thus, the end value is closer to zero than the start.
6517 auto KnownEnd = KnownBits::ashr(KnownStart,
6518 KnownBits::makeConstant(TotalShift));
6519 if (KnownStart.isNonNegative())
6520 // Analogous to lshr (simply not yet canonicalized)
6521 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6522 KnownStart.getMaxValue() + 1);
6523 if (KnownStart.isNegative())
6524 // End >=u Start && End <=s Start
6525 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6526 KnownEnd.getMaxValue() + 1);
6527 break;
6528 }
6529 case Instruction::LShr: {
6530 // For each lshr, three cases:
6531 // shift = 0 => unchanged value
6532 // saturation => 0
6533 // other => a smaller positive number
6534 // Thus, the low end of the unsigned range is the last value produced.
6535 auto KnownEnd = KnownBits::lshr(KnownStart,
6536 KnownBits::makeConstant(TotalShift));
6537 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6538 KnownStart.getMaxValue() + 1);
6539 }
6540 case Instruction::Shl: {
6541 // Iff no bits are shifted out, value increases on every shift.
6542 auto KnownEnd = KnownBits::shl(KnownStart,
6543 KnownBits::makeConstant(TotalShift));
6544 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6545 return ConstantRange(KnownStart.getMinValue(),
6546 KnownEnd.getMaxValue() + 1);
6547 break;
6548 }
6549 };
6550 return FullSet;
6551}
6552
6553// The goal of this function is to check if recursively visiting the operands
6554// of this PHI might lead to an infinite loop. If we do see such a loop,
6555// there's no good way to break it, so we avoid analyzing such cases.
6556//
6557// getRangeRef previously used a visited set to avoid infinite loops, but this
6558// caused other issues: the result was dependent on the order of getRangeRef
6559// calls, and the interaction with createSCEVIter could cause a stack overflow
6560// in some cases (see issue #148253).
6561//
6562// FIXME: The way this is implemented is overly conservative; this checks
6563// for a few obviously safe patterns, but anything that doesn't lead to
6564// recursion is fine.
6566 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6568 return true;
6569
6570 if (all_of(PHI->operands(),
6571 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6572 return true;
6573
6574 return false;
6575}
6576
6577const ConstantRange &
6578ScalarEvolution::getRangeRefIter(const SCEV *S,
6579 ScalarEvolution::RangeSignHint SignHint) {
6580 DenseMap<const SCEV *, ConstantRange> &Cache =
6581 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6582 : SignedRanges;
6583 SmallVector<SCEVUse> WorkList;
6584 SmallPtrSet<const SCEV *, 8> Seen;
6585
6586 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6587 // SCEVUnknown PHI node.
6588 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6589 if (!Seen.insert(Expr).second)
6590 return;
6591 if (Cache.contains(Expr))
6592 return;
6593 switch (Expr->getSCEVType()) {
6594 case scUnknown:
6596 break;
6597 [[fallthrough]];
6598 case scConstant:
6599 case scVScale:
6600 case scTruncate:
6601 case scZeroExtend:
6602 case scSignExtend:
6603 case scPtrToAddr:
6604 case scAddExpr:
6605 case scMulExpr:
6606 case scUDivExpr:
6607 case scAddRecExpr:
6608 case scUMaxExpr:
6609 case scSMaxExpr:
6610 case scUMinExpr:
6611 case scSMinExpr:
6613 WorkList.push_back(Expr);
6614 break;
6615 case scCouldNotCompute:
6616 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6617 }
6618 };
6619 AddToWorklist(S);
6620
6621 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6622 for (unsigned I = 0; I != WorkList.size(); ++I) {
6623 const SCEV *P = WorkList[I];
6624 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6625 // If it is not a `SCEVUnknown`, just recurse into operands.
6626 if (!UnknownS) {
6627 for (const SCEV *Op : P->operands())
6628 AddToWorklist(Op);
6629 continue;
6630 }
6631 // `SCEVUnknown`'s require special treatment.
6632 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6633 if (!RangeRefPHIAllowedOperands(DT, P))
6634 continue;
6635 for (auto &Op : reverse(P->operands()))
6636 AddToWorklist(getSCEV(Op));
6637 }
6638 }
6639
6640 if (!WorkList.empty()) {
6641 // Use getRangeRef to compute ranges for items in the worklist in reverse
6642 // order. This will force ranges for earlier operands to be computed before
6643 // their users in most cases.
6644 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6645 getRangeRef(P, SignHint);
6646 }
6647 }
6648
6649 return getRangeRef(S, SignHint, 0);
6650}
6651
6652const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6653 if (const auto *C = dyn_cast<SCEVConstant>(S))
6654 return &C->getAPInt();
6655 return nullptr;
6656}
6657
6658/// Determine the range for a particular SCEV. If SignHint is
6659/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6660/// with a "cleaner" unsigned (resp. signed) representation.
6661const ConstantRange &ScalarEvolution::getRangeRef(
6662 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6663 DenseMap<const SCEV *, ConstantRange> &Cache =
6664 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6665 : SignedRanges;
6667 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6669
6670 // See if we've computed this range already.
6671 auto I = Cache.find(S);
6672 if (I != Cache.end())
6673 return I->second;
6674
6675 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6676 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6677
6678 // Switch to iteratively computing the range for S, if it is part of a deeply
6679 // nested expression.
6681 return getRangeRefIter(S, SignHint);
6682
6683 unsigned BitWidth = getTypeSizeInBits(S->getType());
6684 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6685 using OBO = OverflowingBinaryOperator;
6686
6687 // If the value has known zeros, the maximum value will have those known zeros
6688 // as well.
6689 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6690 APInt Multiple = getNonZeroConstantMultiple(S);
6691 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6692 if (!Remainder.isZero())
6693 ConservativeResult =
6694 ConstantRange(APInt::getMinValue(BitWidth),
6695 APInt::getMaxValue(BitWidth) - Remainder + 1);
6696 }
6697 else {
6698 uint32_t TZ = getMinTrailingZeros(S);
6699 if (TZ != 0) {
6700 ConservativeResult = ConstantRange(
6702 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6703 }
6704 }
6705
6706 switch (S->getSCEVType()) {
6707 case scConstant:
6708 llvm_unreachable("Already handled above.");
6709 case scVScale:
6710 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6711 case scTruncate: {
6712 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6713 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6714 return setRange(
6715 Trunc, SignHint,
6716 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6717 }
6718 case scZeroExtend: {
6719 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6720 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6721 return setRange(
6722 ZExt, SignHint,
6723 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6724 }
6725 case scSignExtend: {
6726 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6727 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6728 return setRange(
6729 SExt, SignHint,
6730 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6731 }
6732 case scPtrToAddr: {
6733 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6734 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6735 return setRange(Cast, SignHint, X);
6736 }
6737 case scAddExpr: {
6738 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6739 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6740 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6741 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6742 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6743 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6744 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6745 ConservativeResult =
6746 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6747 }
6748 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6749 unsigned WrapType = OBO::AnyWrap;
6750 if (Add->hasNoSignedWrap())
6751 WrapType |= OBO::NoSignedWrap;
6752 if (Add->hasNoUnsignedWrap())
6753 WrapType |= OBO::NoUnsignedWrap;
6754 for (const SCEV *Op : drop_begin(Add->operands()))
6755 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6756 RangeType);
6757 return setRange(Add, SignHint,
6758 ConservativeResult.intersectWith(X, RangeType));
6759 }
6760 case scMulExpr: {
6761 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6762 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6763 for (const SCEV *Op : drop_begin(Mul->operands()))
6764 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6765 return setRange(Mul, SignHint,
6766 ConservativeResult.intersectWith(X, RangeType));
6767 }
6768 case scUDivExpr: {
6769 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6770 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6771 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6772 return setRange(UDiv, SignHint,
6773 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6774 }
6775 case scAddRecExpr: {
6776 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6777 // If there's no unsigned wrap, the value will never be less than its
6778 // initial value.
6779 if (AddRec->hasNoUnsignedWrap()) {
6780 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6781 if (!UnsignedMinValue.isZero())
6782 ConservativeResult = ConservativeResult.intersectWith(
6783 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6784 }
6785
6786 // If there's no signed wrap, and all the operands except initial value have
6787 // the same sign or zero, the value won't ever be:
6788 // 1: smaller than initial value if operands are non negative,
6789 // 2: bigger than initial value if operands are non positive.
6790 // For both cases, value can not cross signed min/max boundary.
6791 if (AddRec->hasNoSignedWrap()) {
6792 bool AllNonNeg = true;
6793 bool AllNonPos = true;
6794 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6795 if (!isKnownNonNegative(AddRec->getOperand(i)))
6796 AllNonNeg = false;
6797 if (!isKnownNonPositive(AddRec->getOperand(i)))
6798 AllNonPos = false;
6799 }
6800 if (AllNonNeg)
6801 ConservativeResult = ConservativeResult.intersectWith(
6804 RangeType);
6805 else if (AllNonPos)
6806 ConservativeResult = ConservativeResult.intersectWith(
6808 getSignedRangeMax(AddRec->getStart()) +
6809 1),
6810 RangeType);
6811 }
6812
6813 // TODO: non-affine addrec
6814 if (AddRec->isAffine()) {
6815 const SCEV *MaxBEScev =
6817 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6818 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6819
6820 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6821 // MaxBECount's active bits are all <= AddRec's bit width.
6822 if (MaxBECount.getBitWidth() > BitWidth &&
6823 MaxBECount.getActiveBits() <= BitWidth)
6824 MaxBECount = MaxBECount.trunc(BitWidth);
6825 else if (MaxBECount.getBitWidth() < BitWidth)
6826 MaxBECount = MaxBECount.zext(BitWidth);
6827
6828 if (MaxBECount.getBitWidth() == BitWidth) {
6829 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6830 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6831 ConservativeResult =
6832 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6833 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6834
6835 auto RangeFromFactoring = getRangeViaFactoring(
6836 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6837 ConservativeResult =
6838 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6839 }
6840 }
6841
6842 // Now try symbolic BE count and more powerful methods.
6844 const SCEV *SymbolicMaxBECount =
6846 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6847 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6848 AddRec->hasNoSelfWrap()) {
6849 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6850 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6851 ConservativeResult =
6852 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6853 }
6854 }
6855 }
6856
6857 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6858 }
6859 case scUMaxExpr:
6860 case scSMaxExpr:
6861 case scUMinExpr:
6862 case scSMinExpr:
6863 case scSequentialUMinExpr: {
6865 switch (S->getSCEVType()) {
6866 case scUMaxExpr:
6867 ID = Intrinsic::umax;
6868 break;
6869 case scSMaxExpr:
6870 ID = Intrinsic::smax;
6871 break;
6872 case scUMinExpr:
6874 ID = Intrinsic::umin;
6875 break;
6876 case scSMinExpr:
6877 ID = Intrinsic::smin;
6878 break;
6879 default:
6880 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6881 }
6882
6883 const auto *NAry = cast<SCEVNAryExpr>(S);
6884 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6885 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6886 X = X.intrinsic(
6887 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6888 return setRange(S, SignHint,
6889 ConservativeResult.intersectWith(X, RangeType));
6890 }
6891 case scUnknown: {
6892 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6893 Value *V = U->getValue();
6894
6895 // Check if the IR explicitly contains !range metadata.
6896 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6897 if (MDRange)
6898 ConservativeResult =
6899 ConservativeResult.intersectWith(*MDRange, RangeType);
6900
6901 // Use facts about recurrences in the underlying IR. Note that add
6902 // recurrences are AddRecExprs and thus don't hit this path. This
6903 // primarily handles shift recurrences.
6904 auto CR = getRangeForUnknownRecurrence(U);
6905 ConservativeResult = ConservativeResult.intersectWith(CR);
6906
6907 // See if ValueTracking can give us a useful range.
6908 const DataLayout &DL = getDataLayout();
6909 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6910 if (Known.getBitWidth() != BitWidth)
6911 Known = Known.zextOrTrunc(BitWidth);
6912
6913 // ValueTracking may be able to compute a tighter result for the number of
6914 // sign bits than for the value of those sign bits.
6915 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6916 if (U->getType()->isPointerTy()) {
6917 // If the pointer size is larger than the index size type, this can cause
6918 // NS to be larger than BitWidth. So compensate for this.
6919 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6920 int ptrIdxDiff = ptrSize - BitWidth;
6921 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6922 NS -= ptrIdxDiff;
6923 }
6924
6925 if (NS > 1) {
6926 // If we know any of the sign bits, we know all of the sign bits.
6927 if (!Known.Zero.getHiBits(NS).isZero())
6928 Known.Zero.setHighBits(NS);
6929 if (!Known.One.getHiBits(NS).isZero())
6930 Known.One.setHighBits(NS);
6931 }
6932
6933 if (Known.getMinValue() != Known.getMaxValue() + 1)
6934 ConservativeResult = ConservativeResult.intersectWith(
6935 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6936 RangeType);
6937 if (NS > 1)
6938 ConservativeResult = ConservativeResult.intersectWith(
6939 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6940 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6941 RangeType);
6942
6943 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6944 // Strengthen the range if the underlying IR value is a
6945 // global/alloca/heap allocation using the size of the object.
6946 bool CanBeNull;
6947 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6948 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6949 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6950 // The highest address the object can start is DerefBytes bytes before
6951 // the end (unsigned max value). If this value is not a multiple of the
6952 // alignment, the last possible start value is the next lowest multiple
6953 // of the alignment. Note: The computations below cannot overflow,
6954 // because if they would there's no possible start address for the
6955 // object.
6956 APInt MaxVal =
6957 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6958 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6959 uint64_t Rem = MaxVal.urem(Align);
6960 MaxVal -= APInt(BitWidth, Rem);
6961 APInt MinVal = APInt::getZero(BitWidth);
6962 if (llvm::isKnownNonZero(V, DL))
6963 MinVal = Align;
6964 ConservativeResult = ConservativeResult.intersectWith(
6965 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6966 }
6967 }
6968
6969 // A range of Phi is a subset of union of all ranges of its input.
6970 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6971 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6972 // AddRecs; return the range for the corresponding AddRec.
6973 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6974 return getRangeRef(AR, SignHint, Depth + 1);
6975
6976 // Make sure that we do not run over cycled Phis.
6977 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6978 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6979
6980 for (const auto &Op : Phi->operands()) {
6981 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6982 RangeFromOps = RangeFromOps.unionWith(OpRange);
6983 // No point to continue if we already have a full set.
6984 if (RangeFromOps.isFullSet())
6985 break;
6986 }
6987 ConservativeResult =
6988 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6989 }
6990 }
6991
6992 // vscale can't be equal to zero
6993 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6994 if (II->getIntrinsicID() == Intrinsic::vscale) {
6995 ConstantRange Disallowed = APInt::getZero(BitWidth);
6996 ConservativeResult = ConservativeResult.difference(Disallowed);
6997 }
6998
6999 return setRange(U, SignHint, std::move(ConservativeResult));
7000 }
7001 case scCouldNotCompute:
7002 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7003 }
7004
7005 return setRange(S, SignHint, std::move(ConservativeResult));
7006}
7007
7008// Given a StartRange, Step and MaxBECount for an expression compute a range of
7009// values that the expression can take. Initially, the expression has a value
7010// from StartRange and then is changed by Step up to MaxBECount times. Signed
7011// argument defines if we treat Step as signed or unsigned. The second return
7012// value indicates that no wrapping occurred.
7013static std::pair<ConstantRange, bool>
7015 const APInt &MaxBECount, bool Signed) {
7016 unsigned BitWidth = Step.getBitWidth();
7017 assert(BitWidth == StartRange.getBitWidth() &&
7018 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7019 // If either Step or MaxBECount is 0, then the expression won't change, and we
7020 // just need to return the initial range.
7021 if (Step == 0 || MaxBECount == 0)
7022 return {StartRange, true};
7023
7024 // If we don't know anything about the initial value (i.e. StartRange is
7025 // FullRange), then we don't know anything about the final range either.
7026 // Return FullRange.
7027 if (StartRange.isFullSet())
7028 return {ConstantRange::getFull(BitWidth), false};
7029
7030 // If Step is signed and negative, then we use its absolute value, but we also
7031 // note that we're moving in the opposite direction.
7032 bool Descending = Signed && Step.isNegative();
7033
7034 if (Signed)
7035 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7036 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7037 // This equations hold true due to the well-defined wrap-around behavior of
7038 // APInt.
7039 Step = Step.abs();
7040
7041 // Check if Offset is more than full span of BitWidth. If it is, the
7042 // expression is guaranteed to overflow.
7043 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7044 return {ConstantRange::getFull(BitWidth), false};
7045
7046 // Offset is by how much the expression can change. Checks above guarantee no
7047 // overflow here.
7048 APInt Offset = Step * MaxBECount;
7049
7050 // Minimum value of the final range will match the minimal value of StartRange
7051 // if the expression is increasing and will be decreased by Offset otherwise.
7052 // Maximum value of the final range will match the maximal value of StartRange
7053 // if the expression is decreasing and will be increased by Offset otherwise.
7054 APInt StartLower = StartRange.getLower();
7055 APInt StartUpper = StartRange.getUpper() - 1;
7056 bool Overflow;
7057 APInt MovedBoundary;
7058 if (Signed) {
7059 // This does not use sadd_ov, as we want to check overflow for a signed
7060 // start with an unsigned offset.
7061 if (Descending) {
7062 MovedBoundary = StartLower - std::move(Offset);
7063 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7064 } else {
7065 MovedBoundary = StartUpper + std::move(Offset);
7066 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7067 }
7068 } else {
7069 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7070 Overflow |= StartRange.isWrappedSet();
7071 }
7072
7073 // It's possible that the new minimum/maximum value will fall into the initial
7074 // range (due to wrap around). This means that the expression can take any
7075 // value in this bitwidth, and we have to return full range.
7076 if (StartRange.contains(MovedBoundary))
7077 return {ConstantRange::getFull(BitWidth), false};
7078
7079 APInt NewLower =
7080 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7081 APInt NewUpper =
7082 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7083 NewUpper += 1;
7084
7085 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7086 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7087 !Overflow};
7088}
7089
7090std::pair<ConstantRange, SCEV::NoWrapFlags>
7091ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7092 const APInt &MaxBECount) {
7093 assert(getTypeSizeInBits(Start->getType()) ==
7094 getTypeSizeInBits(Step->getType()) &&
7095 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7096 "mismatched bit widths");
7097
7098 // First, consider step signed.
7099 ConstantRange StartSRange = getSignedRange(Start);
7100 ConstantRange StepSRange = getSignedRange(Step);
7101
7102 // If Step can be both positive and negative, we need to find ranges for the
7103 // maximum absolute step values in both directions and union them.
7104 auto [SR1, NSW1] = getRangeForAffineARHelper(
7105 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7106 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7107 StartSRange, MaxBECount,
7108 /*Signed=*/true);
7109 ConstantRange SR = SR1.unionWith(SR2);
7110
7111 // Next, consider step unsigned.
7112 auto [UR, NUW] = getRangeForAffineARHelper(
7113 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7114 /*Signed=*/false);
7115
7117 if (NUW)
7119 if (NSW1 && NSW2)
7121
7122 // Finally, intersect signed and unsigned ranges.
7124}
7125
7126ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7127 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7128 ScalarEvolution::RangeSignHint SignHint) {
7129 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7130 assert(AddRec->hasNoSelfWrap() &&
7131 "This only works for non-self-wrapping AddRecs!");
7132 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7133 const SCEV *Step = AddRec->getStepRecurrence(*this);
7134 // Only deal with constant step to save compile time.
7135 if (!isa<SCEVConstant>(Step))
7136 return ConstantRange::getFull(BitWidth);
7137 // Let's make sure that we can prove that we do not self-wrap during
7138 // MaxBECount iterations. We need this because MaxBECount is a maximum
7139 // iteration count estimate, and we might infer nw from some exit for which we
7140 // do not know max exit count (or any other side reasoning).
7141 // TODO: Turn into assert at some point.
7142 if (getTypeSizeInBits(MaxBECount->getType()) >
7143 getTypeSizeInBits(AddRec->getType()))
7144 return ConstantRange::getFull(BitWidth);
7145 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7146 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7147 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7148 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7149 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7150 MaxItersWithoutWrap))
7151 return ConstantRange::getFull(BitWidth);
7152
7153 ICmpInst::Predicate LEPred =
7155 ICmpInst::Predicate GEPred =
7157 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7158
7159 // We know that there is no self-wrap. Let's take Start and End values and
7160 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7161 // the iteration. They either lie inside the range [Min(Start, End),
7162 // Max(Start, End)] or outside it:
7163 //
7164 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7165 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7166 //
7167 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7168 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7169 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7170 // Start <= End and step is positive, or Start >= End and step is negative.
7171 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7172 ConstantRange StartRange = getRangeRef(Start, SignHint);
7173 ConstantRange EndRange = getRangeRef(End, SignHint);
7174 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7175 // If they already cover full iteration space, we will know nothing useful
7176 // even if we prove what we want to prove.
7177 if (RangeBetween.isFullSet())
7178 return RangeBetween;
7179 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7180 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7181 : RangeBetween.isWrappedSet();
7182 if (IsWrappedSet)
7183 return ConstantRange::getFull(BitWidth);
7184
7185 if (isKnownPositive(Step) &&
7186 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7187 return RangeBetween;
7188 if (isKnownNegative(Step) &&
7189 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7190 return RangeBetween;
7191 return ConstantRange::getFull(BitWidth);
7192}
7193
7194ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7195 const SCEV *Step,
7196 const APInt &MaxBECount) {
7197 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7198 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7199
7200 unsigned BitWidth = MaxBECount.getBitWidth();
7201 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7202 getTypeSizeInBits(Step->getType()) == BitWidth &&
7203 "mismatched bit widths");
7204
7205 struct SelectPattern {
7206 Value *Condition = nullptr;
7207 APInt TrueValue;
7208 APInt FalseValue;
7209
7210 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7211 const SCEV *S) {
7212 std::optional<unsigned> CastOp;
7213 APInt Offset(BitWidth, 0);
7214
7216 "Should be!");
7217
7218 // Peel off a constant offset. In the future we could consider being
7219 // smarter here and handle {Start+Step,+,Step} too.
7220 const APInt *Off;
7221 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7222 Offset = *Off;
7223
7224 // Peel off a cast operation
7225 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7226 CastOp = SCast->getSCEVType();
7227 S = SCast->getOperand();
7228 }
7229
7230 using namespace llvm::PatternMatch;
7231
7232 auto *SU = dyn_cast<SCEVUnknown>(S);
7233 const APInt *TrueVal, *FalseVal;
7234 if (!SU ||
7235 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7236 m_APInt(FalseVal)))) {
7237 Condition = nullptr;
7238 return;
7239 }
7240
7241 TrueValue = *TrueVal;
7242 FalseValue = *FalseVal;
7243
7244 // Re-apply the cast we peeled off earlier
7245 if (CastOp)
7246 switch (*CastOp) {
7247 default:
7248 llvm_unreachable("Unknown SCEV cast type!");
7249
7250 case scTruncate:
7251 TrueValue = TrueValue.trunc(BitWidth);
7252 FalseValue = FalseValue.trunc(BitWidth);
7253 break;
7254 case scZeroExtend:
7255 TrueValue = TrueValue.zext(BitWidth);
7256 FalseValue = FalseValue.zext(BitWidth);
7257 break;
7258 case scSignExtend:
7259 TrueValue = TrueValue.sext(BitWidth);
7260 FalseValue = FalseValue.sext(BitWidth);
7261 break;
7262 }
7263
7264 // Re-apply the constant offset we peeled off earlier
7265 TrueValue += Offset;
7266 FalseValue += Offset;
7267 }
7268
7269 bool isRecognized() { return Condition != nullptr; }
7270 };
7271
7272 SelectPattern StartPattern(*this, BitWidth, Start);
7273 if (!StartPattern.isRecognized())
7274 return ConstantRange::getFull(BitWidth);
7275
7276 SelectPattern StepPattern(*this, BitWidth, Step);
7277 if (!StepPattern.isRecognized())
7278 return ConstantRange::getFull(BitWidth);
7279
7280 if (StartPattern.Condition != StepPattern.Condition) {
7281 // We don't handle this case today; but we could, by considering four
7282 // possibilities below instead of two. I'm not sure if there are cases where
7283 // that will help over what getRange already does, though.
7284 return ConstantRange::getFull(BitWidth);
7285 }
7286
7287 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7288 // construct arbitrary general SCEV expressions here. This function is called
7289 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7290 // say) can end up caching a suboptimal value.
7291
7292 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7293 // C2352 and C2512 (otherwise it isn't needed).
7294
7295 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7296 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7297 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7298 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7299
7300 ConstantRange TrueRange =
7301 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7302 ConstantRange FalseRange =
7303 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7304
7305 return TrueRange.unionWith(FalseRange);
7306}
7307
7308SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7309 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7310 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7311
7312 // Return early if there are no flags to propagate to the SCEV.
7314 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7315 PDI && PDI->isDisjoint()) {
7317 } else {
7318 if (BinOp->hasNoUnsignedWrap())
7320 if (BinOp->hasNoSignedWrap())
7322 }
7323 if (Flags == SCEV::FlagAnyWrap)
7324 return SCEV::FlagAnyWrap;
7325
7326 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7327}
7328
7329const Instruction *
7330ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7331 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7332 return &*AddRec->getLoop()->getHeader()->begin();
7333 if (auto *U = dyn_cast<SCEVUnknown>(S))
7334 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7335 return I;
7336 return nullptr;
7337}
7338
7339const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7340 bool &Precise) {
7341 Precise = true;
7342 // Do a bounded search of the def relation of the requested SCEVs.
7343 SmallPtrSet<const SCEV *, 16> Visited;
7344 SmallVector<SCEVUse> Worklist;
7345 auto pushOp = [&](const SCEV *S) {
7346 if (!Visited.insert(S).second)
7347 return;
7348 // Threshold of 30 here is arbitrary.
7349 if (Visited.size() > 30) {
7350 Precise = false;
7351 return;
7352 }
7353 Worklist.push_back(S);
7354 };
7355
7356 for (SCEVUse S : Ops)
7357 pushOp(S);
7358
7359 const Instruction *Bound = nullptr;
7360 while (!Worklist.empty()) {
7361 SCEVUse S = Worklist.pop_back_val();
7362 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7363 if (!Bound || DT.dominates(Bound, DefI))
7364 Bound = DefI;
7365 } else {
7366 for (SCEVUse Op : S->operands())
7367 pushOp(Op);
7368 }
7369 }
7370 return Bound ? Bound : &*F.getEntryBlock().begin();
7371}
7372
7373const Instruction *
7374ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7375 bool Discard;
7376 return getDefiningScopeBound(Ops, Discard);
7377}
7378
7379bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7380 const Instruction *B) {
7381 if (A->getParent() == B->getParent() &&
7383 B->getIterator()))
7384 return true;
7385
7386 auto *BLoop = LI.getLoopFor(B->getParent());
7387 if (BLoop && BLoop->getHeader() == B->getParent() &&
7388 BLoop->getLoopPreheader() == A->getParent() &&
7390 A->getParent()->end()) &&
7391 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7392 B->getIterator()))
7393 return true;
7394 return false;
7395}
7396
7398 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7399 visitAll(Op, PC);
7400 return PC.MaybePoison.empty();
7401}
7402
7403bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7404 return !SCEVExprContains(Op, [this](const SCEV *S) {
7405 const SCEV *Op1;
7406 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7407 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7408 // is a non-zero constant, we have to assume the UDiv may be UB.
7409 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7410 });
7411}
7412
7413bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7414 // Only proceed if we can prove that I does not yield poison.
7416 return false;
7417
7418 // At this point we know that if I is executed, then it does not wrap
7419 // according to at least one of NSW or NUW. If I is not executed, then we do
7420 // not know if the calculation that I represents would wrap. Multiple
7421 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7422 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7423 // derived from other instructions that map to the same SCEV. We cannot make
7424 // that guarantee for cases where I is not executed. So we need to find a
7425 // upper bound on the defining scope for the SCEV, and prove that I is
7426 // executed every time we enter that scope. When the bounding scope is a
7427 // loop (the common case), this is equivalent to proving I executes on every
7428 // iteration of that loop.
7429 SmallVector<SCEVUse> SCEVOps;
7430 for (const Use &Op : I->operands()) {
7431 // I could be an extractvalue from a call to an overflow intrinsic.
7432 // TODO: We can do better here in some cases.
7433 if (isSCEVable(Op->getType()))
7434 SCEVOps.push_back(getSCEV(Op));
7435 }
7436 auto *DefI = getDefiningScopeBound(SCEVOps);
7437 return isGuaranteedToTransferExecutionTo(DefI, I);
7438}
7439
7440bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7441 // If we know that \c I can never be poison period, then that's enough.
7442 if (isSCEVExprNeverPoison(I))
7443 return true;
7444
7445 // If the loop only has one exit, then we know that, if the loop is entered,
7446 // any instruction dominating that exit will be executed. If any such
7447 // instruction would result in UB, the addrec cannot be poison.
7448 //
7449 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7450 // also handles uses outside the loop header (they just need to dominate the
7451 // single exit).
7452
7453 auto *ExitingBB = L->getExitingBlock();
7454 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7455 return false;
7456
7457 SmallPtrSet<const Value *, 16> KnownPoison;
7459
7460 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7461 // things that are known to be poison under that assumption go on the
7462 // Worklist.
7463 KnownPoison.insert(I);
7464 Worklist.push_back(I);
7465
7466 while (!Worklist.empty()) {
7467 const Instruction *Poison = Worklist.pop_back_val();
7468
7469 for (const Use &U : Poison->uses()) {
7470 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7471 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7472 DT.dominates(PoisonUser->getParent(), ExitingBB))
7473 return true;
7474
7475 if (propagatesPoison(U) && L->contains(PoisonUser))
7476 if (KnownPoison.insert(PoisonUser).second)
7477 Worklist.push_back(PoisonUser);
7478 }
7479 }
7480
7481 return false;
7482}
7483
7484ScalarEvolution::LoopProperties
7485ScalarEvolution::getLoopProperties(const Loop *L) {
7486 using LoopProperties = ScalarEvolution::LoopProperties;
7487
7488 auto Itr = LoopPropertiesCache.find(L);
7489 if (Itr == LoopPropertiesCache.end()) {
7490 auto HasSideEffects = [](Instruction *I) {
7491 if (auto *SI = dyn_cast<StoreInst>(I))
7492 return !SI->isSimple();
7493
7494 if (I->mayThrow())
7495 return true;
7496
7497 // Non-volatile memset / memcpy do not count as side-effect for forward
7498 // progress.
7499 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7500 return false;
7501
7502 return I->mayWriteToMemory();
7503 };
7504
7505 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7506 /*HasNoSideEffects*/ true};
7507
7508 for (auto *BB : L->getBlocks())
7509 for (auto &I : *BB) {
7511 LP.HasNoAbnormalExits = false;
7512 if (HasSideEffects(&I))
7513 LP.HasNoSideEffects = false;
7514 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7515 break; // We're already as pessimistic as we can get.
7516 }
7517
7518 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7519 assert(InsertPair.second && "We just checked!");
7520 Itr = InsertPair.first;
7521 }
7522
7523 return Itr->second;
7524}
7525
7527 // A mustprogress loop without side effects must be finite.
7528 // TODO: The check used here is very conservative. It's only *specific*
7529 // side effects which are well defined in infinite loops.
7530 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7531}
7532
7533const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7534 // Worklist item with a Value and a bool indicating whether all operands have
7535 // been visited already.
7538
7539 Stack.emplace_back(V, false);
7540 while (!Stack.empty()) {
7541 auto E = Stack.back();
7542 Value *CurV = E.getPointer();
7543
7544 if (getExistingSCEV(CurV)) {
7545 Stack.pop_back();
7546 continue;
7547 }
7548
7550 const SCEV *CreatedSCEV = nullptr;
7551 // If all operands have been visited already, create the SCEV.
7552 if (E.getInt()) {
7553 CreatedSCEV = createSCEV(CurV);
7554 } else {
7555 // Otherwise get the operands we need to create SCEV's for before creating
7556 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7557 // just use it.
7558 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7559 }
7560
7561 if (CreatedSCEV) {
7562 insertValueToMap(CurV, CreatedSCEV);
7563 Stack.pop_back();
7564 } else {
7565 Stack.back().setInt(true);
7566 // Queue its operands which need to be constructed.
7567 for (Value *Op : Ops)
7568 Stack.emplace_back(Op, false);
7569 }
7570 }
7571
7572 return getExistingSCEV(V);
7573}
7574
7575const SCEV *
7576ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7577 if (!isSCEVable(V->getType()))
7578 return getUnknown(V);
7579
7580 if (Instruction *I = dyn_cast<Instruction>(V)) {
7581 // Don't attempt to analyze instructions in blocks that aren't
7582 // reachable. Such instructions don't matter, and they aren't required
7583 // to obey basic rules for definitions dominating uses which this
7584 // analysis depends on.
7585 if (!DT.isReachableFromEntry(I->getParent()))
7586 return getUnknown(PoisonValue::get(V->getType()));
7587 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7588 return getConstant(CI);
7589 else if (isa<GlobalAlias>(V))
7590 return getUnknown(V);
7591 else if (!isa<ConstantExpr>(V))
7592 return getUnknown(V);
7593
7595 if (auto BO =
7597 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7598 switch (BO->Opcode) {
7599 case Instruction::Add:
7600 case Instruction::Mul: {
7601 // For additions and multiplications, traverse add/mul chains for which we
7602 // can potentially create a single SCEV, to reduce the number of
7603 // get{Add,Mul}Expr calls.
7604 do {
7605 if (BO->Op) {
7606 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7607 Ops.push_back(BO->Op);
7608 break;
7609 }
7610 }
7611 Ops.push_back(BO->RHS);
7612 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7614 if (!NewBO ||
7615 (BO->Opcode == Instruction::Add &&
7616 (NewBO->Opcode != Instruction::Add &&
7617 NewBO->Opcode != Instruction::Sub)) ||
7618 (BO->Opcode == Instruction::Mul &&
7619 NewBO->Opcode != Instruction::Mul)) {
7620 Ops.push_back(BO->LHS);
7621 break;
7622 }
7623 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7624 // requires a SCEV for the LHS.
7625 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7626 auto *I = dyn_cast<Instruction>(BO->Op);
7627 if (I && programUndefinedIfPoison(I)) {
7628 Ops.push_back(BO->LHS);
7629 break;
7630 }
7631 }
7632 BO = NewBO;
7633 } while (true);
7634 return nullptr;
7635 }
7636 case Instruction::Sub:
7637 case Instruction::UDiv:
7638 case Instruction::URem:
7639 break;
7640 case Instruction::AShr:
7641 case Instruction::Shl:
7642 case Instruction::Xor:
7643 if (!IsConstArg)
7644 return nullptr;
7645 break;
7646 case Instruction::And:
7647 case Instruction::Or:
7648 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7649 return nullptr;
7650 break;
7651 case Instruction::LShr:
7652 return getUnknown(V);
7653 default:
7654 llvm_unreachable("Unhandled binop");
7655 break;
7656 }
7657
7658 Ops.push_back(BO->LHS);
7659 Ops.push_back(BO->RHS);
7660 return nullptr;
7661 }
7662
7663 switch (U->getOpcode()) {
7664 case Instruction::Trunc:
7665 case Instruction::ZExt:
7666 case Instruction::SExt:
7667 case Instruction::PtrToAddr:
7668 case Instruction::PtrToInt:
7669 Ops.push_back(U->getOperand(0));
7670 return nullptr;
7671
7672 case Instruction::BitCast:
7673 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7674 Ops.push_back(U->getOperand(0));
7675 return nullptr;
7676 }
7677 return getUnknown(V);
7678
7679 case Instruction::SDiv:
7680 case Instruction::SRem:
7681 Ops.push_back(U->getOperand(0));
7682 Ops.push_back(U->getOperand(1));
7683 return nullptr;
7684
7685 case Instruction::GetElementPtr:
7686 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7687 "GEP source element type must be sized");
7688 llvm::append_range(Ops, U->operands());
7689 return nullptr;
7690
7691 case Instruction::IntToPtr:
7692 return getUnknown(V);
7693
7694 case Instruction::PHI:
7695 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7696 // relevant nodes for each of them.
7697 //
7698 // The first is just to call simplifyInstruction, and get something back
7699 // that isn't a PHI.
7700 if (Value *V = simplifyInstruction(
7701 cast<PHINode>(U),
7702 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7703 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7704 assert(V);
7705 Ops.push_back(V);
7706 return nullptr;
7707 }
7708 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7709 // operands which all perform the same operation, but haven't been
7710 // CSE'ed for whatever reason.
7711 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7712 assert(BO);
7713 Ops.push_back(BO);
7714 return nullptr;
7715 }
7716 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7717 // is equivalent to a select, and analyzes it like a select.
7718 {
7719 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7721 assert(Cond);
7722 assert(LHS);
7723 assert(RHS);
7724 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7725 Ops.push_back(CondICmp->getOperand(0));
7726 Ops.push_back(CondICmp->getOperand(1));
7727 }
7728 Ops.push_back(Cond);
7729 Ops.push_back(LHS);
7730 Ops.push_back(RHS);
7731 return nullptr;
7732 }
7733 }
7734 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7735 // so just construct it recursively.
7736 //
7737 // In addition to getNodeForPHI, also construct nodes which might be needed
7738 // by getRangeRef.
7740 for (Value *V : cast<PHINode>(U)->operands())
7741 Ops.push_back(V);
7742 return nullptr;
7743 }
7744 return nullptr;
7745
7746 case Instruction::Select: {
7747 // Check if U is a select that can be simplified to a SCEVUnknown.
7748 auto CanSimplifyToUnknown = [this, U]() {
7749 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7750 return false;
7751
7752 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7753 if (!ICI)
7754 return false;
7755 Value *LHS = ICI->getOperand(0);
7756 Value *RHS = ICI->getOperand(1);
7757 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7758 ICI->getPredicate() == CmpInst::ICMP_NE) {
7760 return true;
7761 } else if (getTypeSizeInBits(LHS->getType()) >
7762 getTypeSizeInBits(U->getType()))
7763 return true;
7764 return false;
7765 };
7766 if (CanSimplifyToUnknown())
7767 return getUnknown(U);
7768
7769 llvm::append_range(Ops, U->operands());
7770 return nullptr;
7771 break;
7772 }
7773 case Instruction::Call:
7774 case Instruction::Invoke:
7775 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7776 Ops.push_back(RV);
7777 return nullptr;
7778 }
7779
7780 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7781 switch (II->getIntrinsicID()) {
7782 case Intrinsic::abs:
7783 Ops.push_back(II->getArgOperand(0));
7784 return nullptr;
7785 case Intrinsic::umax:
7786 case Intrinsic::umin:
7787 case Intrinsic::smax:
7788 case Intrinsic::smin:
7789 case Intrinsic::usub_sat:
7790 case Intrinsic::uadd_sat:
7791 Ops.push_back(II->getArgOperand(0));
7792 Ops.push_back(II->getArgOperand(1));
7793 return nullptr;
7794 case Intrinsic::start_loop_iterations:
7795 case Intrinsic::annotation:
7796 case Intrinsic::ptr_annotation:
7797 Ops.push_back(II->getArgOperand(0));
7798 return nullptr;
7799 default:
7800 break;
7801 }
7802 }
7803 break;
7804 }
7805
7806 return nullptr;
7807}
7808
7809const SCEV *ScalarEvolution::createSCEV(Value *V) {
7810 if (!isSCEVable(V->getType()))
7811 return getUnknown(V);
7812
7813 if (Instruction *I = dyn_cast<Instruction>(V)) {
7814 // Don't attempt to analyze instructions in blocks that aren't
7815 // reachable. Such instructions don't matter, and they aren't required
7816 // to obey basic rules for definitions dominating uses which this
7817 // analysis depends on.
7818 if (!DT.isReachableFromEntry(I->getParent()))
7819 return getUnknown(PoisonValue::get(V->getType()));
7820 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7821 return getConstant(CI);
7822 else if (isa<GlobalAlias>(V))
7823 return getUnknown(V);
7824 else if (!isa<ConstantExpr>(V))
7825 return getUnknown(V);
7826
7827 const SCEV *LHS;
7828 const SCEV *RHS;
7829
7831 if (auto BO =
7833 switch (BO->Opcode) {
7834 case Instruction::Add: {
7835 // The simple thing to do would be to just call getSCEV on both operands
7836 // and call getAddExpr with the result. However if we're looking at a
7837 // bunch of things all added together, this can be quite inefficient,
7838 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7839 // Instead, gather up all the operands and make a single getAddExpr call.
7840 // LLVM IR canonical form means we need only traverse the left operands.
7842 do {
7843 if (BO->Op) {
7844 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7845 AddOps.push_back(OpSCEV);
7846 break;
7847 }
7848
7849 // If a NUW or NSW flag can be applied to the SCEV for this
7850 // addition, then compute the SCEV for this addition by itself
7851 // with a separate call to getAddExpr. We need to do that
7852 // instead of pushing the operands of the addition onto AddOps,
7853 // since the flags are only known to apply to this particular
7854 // addition - they may not apply to other additions that can be
7855 // formed with operands from AddOps.
7856 const SCEV *RHS = getSCEV(BO->RHS);
7857 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7858 if (Flags != SCEV::FlagAnyWrap) {
7859 const SCEV *LHS = getSCEV(BO->LHS);
7860 if (BO->Opcode == Instruction::Sub)
7861 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7862 else
7863 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7864 break;
7865 }
7866 }
7867
7868 if (BO->Opcode == Instruction::Sub)
7869 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7870 else
7871 AddOps.push_back(getSCEV(BO->RHS));
7872
7873 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7875 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7876 NewBO->Opcode != Instruction::Sub)) {
7877 AddOps.push_back(getSCEV(BO->LHS));
7878 break;
7879 }
7880 BO = NewBO;
7881 } while (true);
7882
7883 return getAddExpr(AddOps);
7884 }
7885
7886 case Instruction::Mul: {
7888 do {
7889 if (BO->Op) {
7890 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7891 MulOps.push_back(OpSCEV);
7892 break;
7893 }
7894
7895 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7896 if (Flags != SCEV::FlagAnyWrap) {
7897 LHS = getSCEV(BO->LHS);
7898 RHS = getSCEV(BO->RHS);
7899 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7900 break;
7901 }
7902 }
7903
7904 MulOps.push_back(getSCEV(BO->RHS));
7905 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7907 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7908 MulOps.push_back(getSCEV(BO->LHS));
7909 break;
7910 }
7911 BO = NewBO;
7912 } while (true);
7913
7914 return getMulExpr(MulOps);
7915 }
7916 case Instruction::UDiv:
7917 LHS = getSCEV(BO->LHS);
7918 RHS = getSCEV(BO->RHS);
7919 return getUDivExpr(LHS, RHS);
7920 case Instruction::URem:
7921 LHS = getSCEV(BO->LHS);
7922 RHS = getSCEV(BO->RHS);
7923 return getURemExpr(LHS, RHS);
7924 case Instruction::Sub: {
7926 if (BO->Op)
7927 Flags = getNoWrapFlagsFromUB(BO->Op);
7928
7929 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7930 // operand. While we don't model ptrtoint directly in SCEV, the
7931 // difference between two pointer addresses is well-defined.
7932 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7933 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7934 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7935 if (HasPtrLHS || HasPtrRHS) {
7936 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7937 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7938 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7939 // useful structure.
7940 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7941 bool BothPtr) -> const SCEV * {
7942 if (!HasPtr)
7943 return getSCEV(OrigOp);
7944 const SCEV *PtrSCEV = getSCEV(PtrOp);
7945 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7946 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7947 if (!isa<SCEVCouldNotCompute>(Addr) &&
7948 getTypeSizeInBits(OrigOp->getType()) <=
7949 getTypeSizeInBits(Addr->getType()))
7950 return getTruncateOrNoop(Addr, OrigOp->getType());
7951 }
7952 return getSCEV(OrigOp);
7953 };
7954 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7955 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7956 return getMinusSCEV(L, R, Flags);
7957 }
7958
7959 LHS = getSCEV(BO->LHS);
7960 RHS = getSCEV(BO->RHS);
7961 return getMinusSCEV(LHS, RHS, Flags);
7962 }
7963 case Instruction::And:
7964 // For an expression like x&255 that merely masks off the high bits,
7965 // use zext(trunc(x)) as the SCEV expression.
7966 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7967 if (CI->isZero())
7968 return getSCEV(BO->RHS);
7969 if (CI->isMinusOne())
7970 return getSCEV(BO->LHS);
7971 const APInt &A = CI->getValue();
7972
7973 // Instcombine's ShrinkDemandedConstant may strip bits out of
7974 // constants, obscuring what would otherwise be a low-bits mask.
7975 // Use computeKnownBits to compute what ShrinkDemandedConstant
7976 // knew about to reconstruct a low-bits mask value.
7977 unsigned LZ = A.countl_zero();
7978 unsigned TZ = A.countr_zero();
7979 unsigned BitWidth = A.getBitWidth();
7980 KnownBits Known(BitWidth);
7981 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7982
7983 APInt EffectiveMask =
7984 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7985 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7986 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7987 const SCEV *LHS = getSCEV(BO->LHS);
7988 const SCEV *ShiftedLHS = nullptr;
7989 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
7990 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
7991 // For an expression like (x * 8) & 8, simplify the multiply.
7992 unsigned MulZeros = OpC->getAPInt().countr_zero();
7993 unsigned GCD = std::min(MulZeros, TZ);
7994 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
7996 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
7997 append_range(MulOps, LHSMul->operands().drop_front());
7998 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
7999 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8000 }
8001 }
8002 if (!ShiftedLHS)
8003 ShiftedLHS = getUDivExpr(LHS, MulCount);
8004 return getMulExpr(
8006 getTruncateExpr(ShiftedLHS,
8007 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8008 BO->LHS->getType()),
8009 MulCount);
8010 }
8011 }
8012 // Binary `and` is a bit-wise `umin`.
8013 if (BO->LHS->getType()->isIntegerTy(1)) {
8014 LHS = getSCEV(BO->LHS);
8015 RHS = getSCEV(BO->RHS);
8016 return getUMinExpr(LHS, RHS);
8017 }
8018 break;
8019
8020 case Instruction::Or:
8021 // Binary `or` is a bit-wise `umax`.
8022 if (BO->LHS->getType()->isIntegerTy(1)) {
8023 LHS = getSCEV(BO->LHS);
8024 RHS = getSCEV(BO->RHS);
8025 return getUMaxExpr(LHS, RHS);
8026 }
8027 break;
8028
8029 case Instruction::Xor:
8030 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8031 // If the RHS of xor is -1, then this is a not operation.
8032 if (CI->isMinusOne())
8033 return getNotSCEV(getSCEV(BO->LHS));
8034
8035 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8036 // This is a variant of the check for xor with -1, and it handles
8037 // the case where instcombine has trimmed non-demanded bits out
8038 // of an xor with -1.
8039 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8040 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8041 if (LBO->getOpcode() == Instruction::And &&
8042 LCI->getValue() == CI->getValue())
8043 if (const SCEVZeroExtendExpr *Z =
8045 Type *UTy = BO->LHS->getType();
8046 const SCEV *Z0 = Z->getOperand();
8047 Type *Z0Ty = Z0->getType();
8048 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8049
8050 // If C is a low-bits mask, the zero extend is serving to
8051 // mask off the high bits. Complement the operand and
8052 // re-apply the zext.
8053 if (CI->getValue().isMask(Z0TySize))
8054 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8055
8056 // If C is a single bit, it may be in the sign-bit position
8057 // before the zero-extend. In this case, represent the xor
8058 // using an add, which is equivalent, and re-apply the zext.
8059 APInt Trunc = CI->getValue().trunc(Z0TySize);
8060 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8061 Trunc.isSignMask())
8062 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8063 UTy);
8064 }
8065 }
8066 break;
8067
8068 case Instruction::Shl:
8069 // Turn shift left of a constant amount into a multiply.
8070 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8071 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8072
8073 // If the shift count is not less than the bitwidth, the result of
8074 // the shift is undefined. Don't try to analyze it, because the
8075 // resolution chosen here may differ from the resolution chosen in
8076 // other parts of the compiler.
8077 if (SA->getValue().uge(BitWidth))
8078 break;
8079
8080 // We can safely preserve the nuw flag in all cases. It's also safe to
8081 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8082 // requires special handling. It can be preserved as long as we're not
8083 // left shifting by bitwidth - 1.
8084 auto Flags = SCEV::FlagAnyWrap;
8085 if (BO->Op) {
8086 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8087 if (any(MulFlags & SCEV::FlagNSW) &&
8088 (any(MulFlags & SCEV::FlagNUW) ||
8089 SA->getValue().ult(BitWidth - 1)))
8091 if (any(MulFlags & SCEV::FlagNUW))
8093 }
8094
8095 ConstantInt *X = ConstantInt::get(
8096 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8097 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8098 }
8099 break;
8100
8101 case Instruction::AShr:
8102 // AShr X, C, where C is a constant.
8103 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8104 if (!CI)
8105 break;
8106
8107 Type *OuterTy = BO->LHS->getType();
8109 // If the shift count is not less than the bitwidth, the result of
8110 // the shift is undefined. Don't try to analyze it, because the
8111 // resolution chosen here may differ from the resolution chosen in
8112 // other parts of the compiler.
8113 if (CI->getValue().uge(BitWidth))
8114 break;
8115
8116 if (CI->isZero())
8117 return getSCEV(BO->LHS); // shift by zero --> noop
8118
8119 uint64_t AShrAmt = CI->getZExtValue();
8120 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8121
8122 Operator *L = dyn_cast<Operator>(BO->LHS);
8123 const SCEV *AddTruncateExpr = nullptr;
8124 ConstantInt *ShlAmtCI = nullptr;
8125 const SCEV *AddConstant = nullptr;
8126
8127 if (L && L->getOpcode() == Instruction::Add) {
8128 // X = Shl A, n
8129 // Y = Add X, c
8130 // Z = AShr Y, m
8131 // n, c and m are constants.
8132
8133 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8134 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8135 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8136 if (AddOperandCI) {
8137 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8138 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8139 // since we truncate to TruncTy, the AddConstant should be of the
8140 // same type, so create a new Constant with type same as TruncTy.
8141 // Also, the Add constant should be shifted right by AShr amount.
8142 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8143 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8144 // we model the expression as sext(add(trunc(A), c << n)), since the
8145 // sext(trunc) part is already handled below, we create a
8146 // AddExpr(TruncExp) which will be used later.
8147 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8148 }
8149 }
8150 } else if (L && L->getOpcode() == Instruction::Shl) {
8151 // X = Shl A, n
8152 // Y = AShr X, m
8153 // Both n and m are constant.
8154
8155 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8156 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8157 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8158 }
8159
8160 if (AddTruncateExpr && ShlAmtCI) {
8161 // We can merge the two given cases into a single SCEV statement,
8162 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8163 // a simpler case. The following code handles the two cases:
8164 //
8165 // 1) For a two-shift sext-inreg, i.e. n = m,
8166 // use sext(trunc(x)) as the SCEV expression.
8167 //
8168 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8169 // expression. We already checked that ShlAmt < BitWidth, so
8170 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8171 // ShlAmt - AShrAmt < Amt.
8172 const APInt &ShlAmt = ShlAmtCI->getValue();
8173 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8174 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8175 ShlAmtCI->getZExtValue() - AShrAmt);
8176 const SCEV *CompositeExpr =
8177 getMulExpr(AddTruncateExpr, getConstant(Mul));
8178 if (L->getOpcode() != Instruction::Shl)
8179 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8180
8181 return getSignExtendExpr(CompositeExpr, OuterTy);
8182 }
8183 }
8184 break;
8185 }
8186 }
8187
8188 switch (U->getOpcode()) {
8189 case Instruction::Trunc:
8190 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8191
8192 case Instruction::ZExt:
8193 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8194
8195 case Instruction::SExt:
8196 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8198 // The NSW flag of a subtract does not always survive the conversion to
8199 // A + (-1)*B. By pushing sign extension onto its operands we are much
8200 // more likely to preserve NSW and allow later AddRec optimisations.
8201 //
8202 // NOTE: This is effectively duplicating this logic from getSignExtend:
8203 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8204 // but by that point the NSW information has potentially been lost.
8205 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8206 Type *Ty = U->getType();
8207 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8208 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8209 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8210 }
8211 }
8212 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8213
8214 case Instruction::BitCast:
8215 // BitCasts are no-op casts so we just eliminate the cast.
8216 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8217 return getSCEV(U->getOperand(0));
8218 break;
8219
8220 case Instruction::PtrToAddr: {
8221 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8222 if (isa<SCEVCouldNotCompute>(IntOp))
8223 return getUnknown(V);
8224 return IntOp;
8225 }
8226
8227 case Instruction::PtrToInt:
8228 // SCEV only models ptrtoaddr.
8229 return getUnknown(V);
8230
8231 case Instruction::IntToPtr:
8232 // Just don't deal with inttoptr casts.
8233 return getUnknown(V);
8234
8235 case Instruction::SDiv:
8236 // If both operands are non-negative, this is just an udiv.
8237 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8238 isKnownNonNegative(getSCEV(U->getOperand(1))))
8239 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8240 break;
8241
8242 case Instruction::SRem:
8243 // If both operands are non-negative, this is just an urem.
8244 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8245 isKnownNonNegative(getSCEV(U->getOperand(1))))
8246 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8247 break;
8248
8249 case Instruction::GetElementPtr:
8250 return createNodeForGEP(cast<GEPOperator>(U));
8251
8252 case Instruction::PHI:
8253 return createNodeForPHI(cast<PHINode>(U));
8254
8255 case Instruction::Select:
8256 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8257 U->getOperand(2));
8258
8259 case Instruction::Call:
8260 case Instruction::Invoke:
8261 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8262 return getSCEV(RV);
8263
8264 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8265 switch (II->getIntrinsicID()) {
8266 case Intrinsic::abs:
8267 return getAbsExpr(
8268 getSCEV(II->getArgOperand(0)),
8269 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8270 case Intrinsic::umax:
8271 LHS = getSCEV(II->getArgOperand(0));
8272 RHS = getSCEV(II->getArgOperand(1));
8273 return getUMaxExpr(LHS, RHS);
8274 case Intrinsic::umin:
8275 LHS = getSCEV(II->getArgOperand(0));
8276 RHS = getSCEV(II->getArgOperand(1));
8277 return getUMinExpr(LHS, RHS);
8278 case Intrinsic::smax:
8279 LHS = getSCEV(II->getArgOperand(0));
8280 RHS = getSCEV(II->getArgOperand(1));
8281 return getSMaxExpr(LHS, RHS);
8282 case Intrinsic::smin:
8283 LHS = getSCEV(II->getArgOperand(0));
8284 RHS = getSCEV(II->getArgOperand(1));
8285 return getSMinExpr(LHS, RHS);
8286 case Intrinsic::usub_sat: {
8287 const SCEV *X = getSCEV(II->getArgOperand(0));
8288 const SCEV *Y = getSCEV(II->getArgOperand(1));
8289 const SCEV *ClampedY = getUMinExpr(X, Y);
8290 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8291 }
8292 case Intrinsic::uadd_sat: {
8293 const SCEV *X = getSCEV(II->getArgOperand(0));
8294 const SCEV *Y = getSCEV(II->getArgOperand(1));
8295 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8296 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8297 }
8298 case Intrinsic::start_loop_iterations:
8299 case Intrinsic::annotation:
8300 case Intrinsic::ptr_annotation:
8301 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8302 // just eqivalent to the first operand for SCEV purposes.
8303 return getSCEV(II->getArgOperand(0));
8304 case Intrinsic::vscale:
8305 return getVScale(II->getType());
8306 default:
8307 break;
8308 }
8309 }
8310 break;
8311 }
8312
8313 return getUnknown(V);
8314}
8315
8316//===----------------------------------------------------------------------===//
8317// Iteration Count Computation Code
8318//
8319
8321 if (isa<SCEVCouldNotCompute>(ExitCount))
8322 return getCouldNotCompute();
8323
8324 auto *ExitCountType = ExitCount->getType();
8325 assert(ExitCountType->isIntegerTy());
8326 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8327 1 + ExitCountType->getScalarSizeInBits());
8328 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8329}
8330
8332 Type *EvalTy,
8333 const Loop *L) {
8334 if (isa<SCEVCouldNotCompute>(ExitCount))
8335 return getCouldNotCompute();
8336
8337 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8338 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8339
8340 auto CanAddOneWithoutOverflow = [&]() {
8341 ConstantRange ExitCountRange =
8342 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8343 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8344 return true;
8345
8346 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8347 getMinusOne(ExitCount->getType()));
8348 };
8349
8350 // If we need to zero extend the backedge count, check if we can add one to
8351 // it prior to zero extending without overflow. Provided this is safe, it
8352 // allows better simplification of the +1.
8353 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8354 return getZeroExtendExpr(
8355 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8356
8357 // Get the total trip count from the count by adding 1. This may wrap.
8358 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8359}
8360
8361static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8362 if (!ExitCount)
8363 return 0;
8364
8365 ConstantInt *ExitConst = ExitCount->getValue();
8366
8367 // Guard against huge trip counts.
8368 if (ExitConst->getValue().getActiveBits() > 32)
8369 return 0;
8370
8371 // In case of integer overflow, this returns 0, which is correct.
8372 return ((unsigned)ExitConst->getZExtValue()) + 1;
8373}
8374
8376 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8377 return getConstantTripCount(ExitCount);
8378}
8379
8380unsigned
8382 const BasicBlock *ExitingBlock) {
8383 assert(ExitingBlock && "Must pass a non-null exiting block!");
8384 assert(L->isLoopExiting(ExitingBlock) &&
8385 "Exiting block must actually branch out of the loop!");
8386 const SCEVConstant *ExitCount =
8387 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8388 return getConstantTripCount(ExitCount);
8389}
8390
8392 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8393
8394 const auto *MaxExitCount =
8395 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8397 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8398}
8399
8401 SmallVector<BasicBlock *, 8> ExitingBlocks;
8402 L->getExitingBlocks(ExitingBlocks);
8403
8404 // An exit with an uncomputable exit count makes the result 1.
8405 if (ExitingBlocks.empty() ||
8406 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8407 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8408 }))
8409 return 1;
8410
8411 LoopGuards Guards = LoopGuards::collect(L, *this);
8412 unsigned Res = 0;
8413 for (BasicBlock *ExitingBB : ExitingBlocks)
8414 Res = std::gcd(
8415 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8416 return Res;
8417}
8418
8419unsigned
8421 const LoopGuards &Guards) {
8422 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8423
8424 // Get the trip count
8425 const SCEV *TCExpr =
8426 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8427
8428 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8429 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8430 // the greatest power of 2 divisor less than 2^32.
8431 return Multiple.getActiveBits() > 32
8432 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8433 : (unsigned)Multiple.getZExtValue();
8434}
8435
8437 const SCEV *ExitCount) {
8438 if (isa<SCEVCouldNotCompute>(ExitCount))
8439 return 1;
8440
8441 return getSmallConstantTripMultiple(ExitCount, LoopGuards::collect(L, *this));
8442}
8443
8444/// Returns the largest constant divisor of the trip count of this loop as a
8445/// normal unsigned value, if possible. This means that the actual trip count is
8446/// always a multiple of the returned value (don't forget the trip count could
8447/// very well be zero as well!).
8448///
8449/// Returns 1 if the trip count is unknown or not guaranteed to be the
8450/// multiple of a constant (which is also the case if the trip count is simply
8451/// constant, use getSmallConstantTripCount for that case), Will also return 1
8452/// if the trip count is very large (>= 2^32).
8453///
8454/// As explained in the comments for getSmallConstantTripCount, this assumes
8455/// that control exits the loop via ExitingBlock.
8456unsigned
8458 const BasicBlock *ExitingBlock) {
8459 assert(ExitingBlock && "Must pass a non-null exiting block!");
8460 assert(L->isLoopExiting(ExitingBlock) &&
8461 "Exiting block must actually branch out of the loop!");
8462 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8463 return getSmallConstantTripMultiple(L, ExitCount);
8464}
8465
8467 const BasicBlock *ExitingBlock,
8468 ExitCountKind Kind) {
8469 switch (Kind) {
8470 case Exact:
8471 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8472 case SymbolicMaximum:
8473 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8474 case ConstantMaximum:
8475 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8476 };
8477 llvm_unreachable("Invalid ExitCountKind!");
8478}
8479
8481 const Loop *L, const BasicBlock *ExitingBlock,
8483 switch (Kind) {
8484 case Exact:
8485 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8486 Predicates);
8487 case SymbolicMaximum:
8488 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8489 Predicates);
8490 case ConstantMaximum:
8491 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8492 Predicates);
8493 };
8494 llvm_unreachable("Invalid ExitCountKind!");
8495}
8496
8499 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8500}
8501
8503 ExitCountKind Kind) {
8504 switch (Kind) {
8505 case Exact:
8506 return getBackedgeTakenInfo(L).getExact(L, this);
8507 case ConstantMaximum:
8508 return getBackedgeTakenInfo(L).getConstantMax(this);
8509 case SymbolicMaximum:
8510 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8511 };
8512 llvm_unreachable("Invalid ExitCountKind!");
8513}
8514
8517 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8518}
8519
8522 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8523}
8524
8526 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8527}
8528
8529/// Push PHI nodes in the header of the given loop onto the given Worklist.
8530static void PushLoopPHIs(const Loop *L,
8533 BasicBlock *Header = L->getHeader();
8534
8535 // Push all Loop-header PHIs onto the Worklist stack.
8536 for (PHINode &PN : Header->phis())
8537 if (Visited.insert(&PN).second)
8538 Worklist.push_back(&PN);
8539}
8540
8541ScalarEvolution::BackedgeTakenInfo &
8542ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8543 auto &BTI = getBackedgeTakenInfo(L);
8544 if (BTI.hasFullInfo())
8545 return BTI;
8546
8547 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8548
8549 if (!Pair.second)
8550 return Pair.first->second;
8551
8552 BackedgeTakenInfo Result =
8553 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8554
8555 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8556}
8557
8558ScalarEvolution::BackedgeTakenInfo &
8559ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8560 // Initially insert an invalid entry for this loop. If the insertion
8561 // succeeds, proceed to actually compute a backedge-taken count and
8562 // update the value. The temporary CouldNotCompute value tells SCEV
8563 // code elsewhere that it shouldn't attempt to request a new
8564 // backedge-taken count, which could result in infinite recursion.
8565 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8566 BackedgeTakenCounts.try_emplace(L);
8567 if (!Pair.second)
8568 return Pair.first->second;
8569
8570 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8571 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8572 // must be cleared in this scope.
8573 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8574
8575 // Now that we know more about the trip count for this loop, forget any
8576 // existing SCEV values for PHI nodes in this loop since they are only
8577 // conservative estimates made without the benefit of trip count
8578 // information. This invalidation is not necessary for correctness, and is
8579 // only done to produce more precise results.
8580 if (Result.hasAnyInfo()) {
8581 // Invalidate any expression using an addrec in this loop.
8582 SmallVector<SCEVUse, 8> ToForget;
8583 auto LoopUsersIt = LoopUsers.find(L);
8584 if (LoopUsersIt != LoopUsers.end())
8585 append_range(ToForget, LoopUsersIt->second);
8586 forgetMemoizedResults(ToForget);
8587
8588 // Invalidate constant-evolved loop header phis.
8589 for (PHINode &PN : L->getHeader()->phis())
8590 ConstantEvolutionLoopExitValue.erase(&PN);
8591 }
8592
8593 // Re-lookup the insert position, since the call to
8594 // computeBackedgeTakenCount above could result in a
8595 // recusive call to getBackedgeTakenInfo (on a different
8596 // loop), which would invalidate the iterator computed
8597 // earlier.
8598 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8599}
8600
8602 // This method is intended to forget all info about loops. It should
8603 // invalidate caches as if the following happened:
8604 // - The trip counts of all loops have changed arbitrarily
8605 // - Every llvm::Value has been updated in place to produce a different
8606 // result.
8607 BackedgeTakenCounts.clear();
8608 PredicatedBackedgeTakenCounts.clear();
8609 BECountUsers.clear();
8610 LoopPropertiesCache.clear();
8611 ConstantEvolutionLoopExitValue.clear();
8612 ValueExprMap.clear();
8613 ValuesAtScopes.clear();
8614 ValuesAtScopesUsers.clear();
8615 LoopDispositions.clear();
8616 BlockDispositions.clear();
8617 UnsignedRanges.clear();
8618 SignedRanges.clear();
8619 ExprValueMap.clear();
8620 HasRecMap.clear();
8621 ConstantMultipleCache.clear();
8622 PredicatedSCEVRewrites.clear();
8623 FoldCache.clear();
8624 FoldCacheUser.clear();
8625}
8626void ScalarEvolution::visitAndClearUsers(
8629 SmallVectorImpl<SCEVUse> &ToForget) {
8630 while (!Worklist.empty()) {
8631 Instruction *I = Worklist.pop_back_val();
8632 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8633 continue;
8634
8636 ValueExprMap.find_as(static_cast<Value *>(I));
8637 if (It != ValueExprMap.end()) {
8638 ToForget.push_back(It->second);
8639 eraseValueFromMap(It->first);
8640 if (PHINode *PN = dyn_cast<PHINode>(I))
8641 ConstantEvolutionLoopExitValue.erase(PN);
8642 }
8643
8644 PushDefUseChildren(I, Worklist, Visited);
8645 }
8646}
8647
8649 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8652 SmallVector<SCEVUse, 16> ToForget;
8653
8654 // Iterate over all the loops and sub-loops to drop SCEV information.
8655 while (!LoopWorklist.empty()) {
8656 auto *CurrL = LoopWorklist.pop_back_val();
8657
8658 // Drop any stored trip count value.
8659 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8660 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8661
8662 // Drop information about predicated SCEV rewrites for this loop.
8663 PredicatedSCEVRewrites.remove_if(
8664 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8665
8666 auto LoopUsersItr = LoopUsers.find(CurrL);
8667 if (LoopUsersItr != LoopUsers.end())
8668 llvm::append_range(ToForget, LoopUsersItr->second);
8669
8670 // Drop information about expressions based on loop-header PHIs.
8671 PushLoopPHIs(CurrL, Worklist, Visited);
8672 visitAndClearUsers(Worklist, Visited, ToForget);
8673
8674 LoopPropertiesCache.erase(CurrL);
8675 // Forget all contained loops too, to avoid dangling entries in the
8676 // ValuesAtScopes map.
8677 LoopWorklist.append(CurrL->begin(), CurrL->end());
8678 }
8679 forgetMemoizedResults(ToForget);
8680}
8681
8683 forgetLoop(L->getOutermostLoop());
8684}
8685
8688 if (!I) return;
8689
8690 // Drop information about expressions based on loop-header PHIs.
8693 SmallVector<SCEVUse, 8> ToForget;
8694 Worklist.push_back(I);
8695 Visited.insert(I);
8696 visitAndClearUsers(Worklist, Visited, ToForget);
8697
8698 forgetMemoizedResults(ToForget);
8699}
8700
8702 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8703 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8704 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8705 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8706 auto InvalidateValue = [&](Value *Val) {
8707 if (!isSCEVable(Val->getType()))
8708 return;
8709 if (const SCEV *S = getExistingSCEV(Val)) {
8710 struct InvalidationRootCollector {
8711 Loop *L;
8713
8714 InvalidationRootCollector(Loop *L) : L(L) {}
8715
8716 bool follow(const SCEV *S) {
8717 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8718 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8719 if (L->contains(I))
8720 Roots.push_back(S);
8721 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8722 if (L->contains(AddRec->getLoop()))
8723 Roots.push_back(S);
8724 }
8725 return true;
8726 }
8727 bool isDone() const { return false; }
8728 };
8729
8730 InvalidationRootCollector C(L);
8731 visitAll(S, C);
8732 forgetMemoizedResults(C.Roots);
8733 }
8734 };
8735
8736 InvalidateValue(V);
8737
8738 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8739 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8740 // expressions referencing loop-internal values.
8741 if (!isSCEVable(V->getType()) &&
8742 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8743 for (User *U : V->users())
8744 InvalidateValue(U);
8745 // Also perform the normal invalidation.
8746 forgetValue(V);
8747}
8748
8749void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8750
8752 // Unless a specific value is passed to invalidation, completely clear both
8753 // caches.
8754 if (!V) {
8755 BlockDispositions.clear();
8756 LoopDispositions.clear();
8757 return;
8758 }
8759
8760 if (!isSCEVable(V->getType()))
8761 return;
8762
8763 const SCEV *S = getExistingSCEV(V);
8764 if (!S)
8765 return;
8766
8767 // Invalidate the block and loop dispositions cached for S. Dispositions of
8768 // S's users may change if S's disposition changes (i.e. a user may change to
8769 // loop-invariant, if S changes to loop invariant), so also invalidate
8770 // dispositions of S's users recursively.
8771 SmallVector<SCEVUse, 8> Worklist = {S};
8773 while (!Worklist.empty()) {
8774 const SCEV *Curr = Worklist.pop_back_val();
8775 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8776 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8777 if (!LoopDispoRemoved && !BlockDispoRemoved)
8778 continue;
8779 auto Users = SCEVUsers.find(Curr);
8780 if (Users != SCEVUsers.end())
8781 for (const auto *User : Users->second)
8782 if (Seen.insert(User).second)
8783 Worklist.push_back(User);
8784 }
8785}
8786
8787/// Get the exact loop backedge taken count considering all loop exits. A
8788/// computable result can only be returned for loops with all exiting blocks
8789/// dominating the latch. howFarToZero assumes that the limit of each loop test
8790/// is never skipped. This is a valid assumption as long as the loop exits via
8791/// that test. For precise results, it is the caller's responsibility to specify
8792/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8793const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8794 const Loop *L, ScalarEvolution *SE,
8796 // If any exits were not computable, the loop is not computable.
8797 if (!isComplete() || ExitNotTaken.empty())
8798 return SE->getCouldNotCompute();
8799
8800 const BasicBlock *Latch = L->getLoopLatch();
8801 // All exiting blocks we have collected must dominate the only backedge.
8802 if (!Latch)
8803 return SE->getCouldNotCompute();
8804
8805 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8806 // count is simply a minimum out of all these calculated exit counts.
8808 for (const auto &ENT : ExitNotTaken) {
8809 const SCEV *BECount = ENT.ExactNotTaken;
8810 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8811 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8812 "We should only have known counts for exiting blocks that dominate "
8813 "latch!");
8814
8815 Ops.push_back(BECount);
8816
8817 if (Preds)
8818 append_range(*Preds, ENT.Predicates);
8819
8820 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8821 "Predicate should be always true!");
8822 }
8823
8824 // If an earlier exit exits on the first iteration (exit count zero), then
8825 // a later poison exit count should not propagate into the result. This are
8826 // exactly the semantics provided by umin_seq.
8827 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8828}
8829
8830const ScalarEvolution::ExitNotTakenInfo *
8831ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8832 const BasicBlock *ExitingBlock,
8833 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8834 for (const auto &ENT : ExitNotTaken)
8835 if (ENT.ExitingBlock == ExitingBlock) {
8836 if (ENT.hasAlwaysTruePredicate())
8837 return &ENT;
8838 else if (Predicates) {
8839 append_range(*Predicates, ENT.Predicates);
8840 return &ENT;
8841 }
8842 }
8843
8844 return nullptr;
8845}
8846
8847/// getConstantMax - Get the constant max backedge taken count for the loop.
8848const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8849 ScalarEvolution *SE,
8850 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8851 if (!getConstantMax())
8852 return SE->getCouldNotCompute();
8853
8854 for (const auto &ENT : ExitNotTaken)
8855 if (!ENT.hasAlwaysTruePredicate()) {
8856 if (!Predicates)
8857 return SE->getCouldNotCompute();
8858 append_range(*Predicates, ENT.Predicates);
8859 }
8860
8861 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8862 isa<SCEVConstant>(getConstantMax())) &&
8863 "No point in having a non-constant max backedge taken count!");
8864 return getConstantMax();
8865}
8866
8867const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8868 const Loop *L, ScalarEvolution *SE,
8869 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8870 if (!SymbolicMax) {
8871 // Form an expression for the maximum exit count possible for this loop. We
8872 // merge the max and exact information to approximate a version of
8873 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8874 // constants.
8875 SmallVector<SCEVUse, 4> ExitCounts;
8876
8877 for (const auto &ENT : ExitNotTaken) {
8878 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8879 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8880 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8881 "We should only have known counts for exiting blocks that "
8882 "dominate latch!");
8883 ExitCounts.push_back(ExitCount);
8884 if (Predicates)
8885 append_range(*Predicates, ENT.Predicates);
8886
8887 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8888 "Predicate should be always true!");
8889 }
8890 }
8891 if (ExitCounts.empty())
8892 SymbolicMax = SE->getCouldNotCompute();
8893 else
8894 SymbolicMax =
8895 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8896 }
8897 return SymbolicMax;
8898}
8899
8900bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8901 ScalarEvolution *SE) const {
8902 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8903 return !ENT.hasAlwaysTruePredicate();
8904 };
8905 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8906}
8907
8910
8912 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8913 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8917 // If we prove the max count is zero, so is the symbolic bound. This happens
8918 // in practice due to differences in a) how context sensitive we've chosen
8919 // to be and b) how we reason about bounds implied by UB.
8920 if (ConstantMaxNotTaken->isZero()) {
8921 this->ExactNotTaken = E = ConstantMaxNotTaken;
8922 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8923 }
8924
8927 "Exact is not allowed to be less precise than Constant Max");
8930 "Exact is not allowed to be less precise than Symbolic Max");
8933 "Symbolic Max is not allowed to be less precise than Constant Max");
8936 "No point in having a non-constant max backedge taken count!");
8938 for (const auto PredList : PredLists)
8939 for (const auto *P : PredList) {
8940 if (SeenPreds.contains(P))
8941 continue;
8942 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8943 SeenPreds.insert(P);
8944 Predicates.push_back(P);
8945 }
8946 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8947 "Backedge count should be int");
8949 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8950 "Max backedge count should be int");
8951}
8952
8960
8961/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8962/// computable exit into a persistent ExitNotTakenInfo array.
8963ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8965 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8966 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8967 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8968
8969 ExitNotTaken.reserve(ExitCounts.size());
8970 std::transform(ExitCounts.begin(), ExitCounts.end(),
8971 std::back_inserter(ExitNotTaken),
8972 [&](const EdgeExitInfo &EEI) {
8973 BasicBlock *ExitBB = EEI.first;
8974 const ExitLimit &EL = EEI.second;
8975 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8976 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8977 EL.Predicates);
8978 });
8979 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8980 isa<SCEVConstant>(ConstantMax)) &&
8981 "No point in having a non-constant max backedge taken count!");
8982}
8983
8984/// Compute the number of times the backedge of the specified loop will execute.
8985ScalarEvolution::BackedgeTakenInfo
8986ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8987 bool AllowPredicates) {
8988 SmallVector<BasicBlock *, 8> ExitingBlocks;
8989 L->getExitingBlocks(ExitingBlocks);
8990
8991 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8992
8994 bool CouldComputeBECount = true;
8995 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8996 const SCEV *MustExitMaxBECount = nullptr;
8997 const SCEV *MayExitMaxBECount = nullptr;
8998 bool MustExitMaxOrZero = false;
8999 bool IsOnlyExit = ExitingBlocks.size() == 1;
9000
9001 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9002 // and compute maxBECount.
9003 // Do a union of all the predicates here.
9004 for (BasicBlock *ExitBB : ExitingBlocks) {
9005 // We canonicalize untaken exits to br (constant), ignore them so that
9006 // proving an exit untaken doesn't negatively impact our ability to reason
9007 // about the loop as whole.
9008 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9009 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9010 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9011 if (ExitIfTrue == CI->isZero())
9012 continue;
9013 }
9014
9015 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9016
9017 assert((AllowPredicates || EL.Predicates.empty()) &&
9018 "Predicated exit limit when predicates are not allowed!");
9019
9020 // 1. For each exit that can be computed, add an entry to ExitCounts.
9021 // CouldComputeBECount is true only if all exits can be computed.
9022 if (EL.ExactNotTaken != getCouldNotCompute())
9023 ++NumExitCountsComputed;
9024 else
9025 // We couldn't compute an exact value for this exit, so
9026 // we won't be able to compute an exact value for the loop.
9027 CouldComputeBECount = false;
9028 // Remember exit count if either exact or symbolic is known. Because
9029 // Exact always implies symbolic, only check symbolic.
9030 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9031 ExitCounts.emplace_back(ExitBB, EL);
9032 else {
9033 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9034 "Exact is known but symbolic isn't?");
9035 ++NumExitCountsNotComputed;
9036 }
9037
9038 // 2. Derive the loop's MaxBECount from each exit's max number of
9039 // non-exiting iterations. Partition the loop exits into two kinds:
9040 // LoopMustExits and LoopMayExits.
9041 //
9042 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9043 // is a LoopMayExit. If any computable LoopMustExit is found, then
9044 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9045 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9046 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9047 // any
9048 // computable EL.ConstantMaxNotTaken.
9049 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9050 DT.dominates(ExitBB, Latch)) {
9051 if (!MustExitMaxBECount) {
9052 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9053 MustExitMaxOrZero = EL.MaxOrZero;
9054 } else {
9055 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9056 EL.ConstantMaxNotTaken);
9057 }
9058 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9059 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9060 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9061 else {
9062 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9063 EL.ConstantMaxNotTaken);
9064 }
9065 }
9066 }
9067 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9068 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9069 // The loop backedge will be taken the maximum or zero times if there's
9070 // a single exit that must be taken the maximum or zero times.
9071 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9072
9073 // Remember which SCEVs are used in exit limits for invalidation purposes.
9074 // We only care about non-constant SCEVs here, so we can ignore
9075 // EL.ConstantMaxNotTaken
9076 // and MaxBECount, which must be SCEVConstant.
9077 for (const auto &Pair : ExitCounts) {
9078 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9079 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9080 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9081 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9082 {L, AllowPredicates});
9083 }
9084 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9085 MaxBECount, MaxOrZero);
9086}
9087
9088ScalarEvolution::ExitLimit
9089ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9090 bool IsOnlyExit, bool AllowPredicates) {
9091 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9092 // If our exiting block does not dominate the latch, then its connection with
9093 // loop's exit limit may be far from trivial.
9094 const BasicBlock *Latch = L->getLoopLatch();
9095 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9096 return getCouldNotCompute();
9097
9098 Instruction *Term = ExitingBlock->getTerminator();
9099 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9100 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9101 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9102 "It should have one successor in loop and one exit block!");
9103 // Proceed to the next level to examine the exit condition expression.
9104 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9105 /*ControlsOnlyExit=*/IsOnlyExit,
9106 AllowPredicates);
9107 }
9108
9109 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9110 // For switch, make sure that there is a single exit from the loop.
9111 BasicBlock *Exit = nullptr;
9112 for (auto *SBB : successors(ExitingBlock))
9113 if (!L->contains(SBB)) {
9114 if (Exit) // Multiple exit successors.
9115 return getCouldNotCompute();
9116 Exit = SBB;
9117 }
9118 assert(Exit && "Exiting block must have at least one exit");
9119 return computeExitLimitFromSingleExitSwitch(
9120 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9121 }
9122
9123 return getCouldNotCompute();
9124}
9125
9127 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9128 bool AllowPredicates) {
9129 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9130 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9131 ControlsOnlyExit, AllowPredicates);
9132}
9133
9134std::optional<ScalarEvolution::ExitLimit>
9135ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9136 bool ExitIfTrue, bool ControlsOnlyExit,
9137 bool AllowPredicates) {
9138 (void)this->L;
9139 (void)this->ExitIfTrue;
9140 (void)this->AllowPredicates;
9141
9142 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9143 this->AllowPredicates == AllowPredicates &&
9144 "Variance in assumed invariant key components!");
9145 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9146 if (Itr == TripCountMap.end())
9147 return std::nullopt;
9148 return Itr->second;
9149}
9150
9151void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9152 bool ExitIfTrue,
9153 bool ControlsOnlyExit,
9154 bool AllowPredicates,
9155 const ExitLimit &EL) {
9156 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9157 this->AllowPredicates == AllowPredicates &&
9158 "Variance in assumed invariant key components!");
9159
9160 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9161 assert(InsertResult.second && "Expected successful insertion!");
9162 (void)InsertResult;
9163 (void)ExitIfTrue;
9164}
9165
9166ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9167 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9168 bool ControlsOnlyExit, bool AllowPredicates) {
9169
9170 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9171 AllowPredicates))
9172 return *MaybeEL;
9173
9174 ExitLimit EL = computeExitLimitFromCondImpl(
9175 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9176 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9177 return EL;
9178}
9179
9180ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9181 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9182 bool ControlsOnlyExit, bool AllowPredicates) {
9183 // Handle BinOp conditions (And, Or).
9184 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9185 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9186 return *LimitFromBinOp;
9187
9188 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9189 // Proceed to the next level to examine the icmp.
9190 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9191 ExitLimit EL =
9192 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9193 if (EL.hasFullInfo() || !AllowPredicates)
9194 return EL;
9195
9196 // Try again, but use SCEV predicates this time.
9197 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9198 ControlsOnlyExit,
9199 /*AllowPredicates=*/true);
9200 }
9201
9202 // Check for a constant condition. These are normally stripped out by
9203 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9204 // preserve the CFG and is temporarily leaving constant conditions
9205 // in place.
9206 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9207 if (ExitIfTrue == !CI->getZExtValue())
9208 // The backedge is always taken.
9209 return getCouldNotCompute();
9210 // The backedge is never taken.
9211 return getZero(CI->getType());
9212 }
9213
9214 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9215 // with a constant step, we can form an equivalent icmp predicate and figure
9216 // out how many iterations will be taken before we exit.
9217 const WithOverflowInst *WO;
9218 const APInt *C;
9219 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9220 match(WO->getRHS(), m_APInt(C))) {
9221 ConstantRange NWR =
9223 WO->getNoWrapKind());
9224 CmpInst::Predicate Pred;
9225 APInt NewRHSC, Offset;
9226 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9227 if (!ExitIfTrue)
9228 Pred = ICmpInst::getInversePredicate(Pred);
9229 auto *LHS = getSCEV(WO->getLHS());
9230 if (Offset != 0)
9232 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9233 ControlsOnlyExit, AllowPredicates);
9234 if (EL.hasAnyInfo())
9235 return EL;
9236 }
9237
9238 // If it's not an integer or pointer comparison then compute it the hard way.
9239 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9240}
9241
9242std::optional<ScalarEvolution::ExitLimit>
9243ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9244 const Loop *L,
9245 Value *ExitCond,
9246 bool ExitIfTrue,
9247 bool AllowPredicates) {
9248 // Check if the controlling expression for this loop is an And or Or.
9249 Value *Op0, *Op1;
9250 bool IsAnd;
9251 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9252 IsAnd = true;
9253 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9254 IsAnd = false;
9255 else
9256 return std::nullopt;
9257
9258 // A sub-condition of a non-trivial binop never solely controls the exit,
9259 // whether we exit always depends on both conditions.
9260 ExitLimit EL0 = computeExitLimitFromCondCached(
9261 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9262 ExitLimit EL1 = computeExitLimitFromCondCached(
9263 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9264
9265 // EitherMayExit is true in these two cases:
9266 // br (and Op0 Op1), loop, exit
9267 // br (or Op0 Op1), exit, loop
9268 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9269
9270 const SCEV *BECount = getCouldNotCompute();
9271 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9272 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9273 if (EitherMayExit) {
9274 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9275 // Both conditions must be same for the loop to continue executing.
9276 // Choose the less conservative count.
9277 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9278 EL1.ExactNotTaken != getCouldNotCompute()) {
9279 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9280 UseSequentialUMin);
9281 }
9282 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9283 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9284 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9285 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9286 else
9287 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9288 EL1.ConstantMaxNotTaken);
9289 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9290 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9291 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9292 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9293 else
9294 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9295 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9296 } else {
9297 // Both conditions must be same at the same time for the loop to exit.
9298 // For now, be conservative.
9299 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9300 BECount = EL0.ExactNotTaken;
9301 }
9302
9303 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9304 // to be more aggressive when computing BECount than when computing
9305 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9306 // and
9307 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9308 // EL1.ConstantMaxNotTaken to not.
9309 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9310 !isa<SCEVCouldNotCompute>(BECount))
9311 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9312 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9313 SymbolicMaxBECount =
9314 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9315 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9316 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9317}
9318
9319ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9320 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9321 bool AllowPredicates) {
9322 // If the condition was exit on true, convert the condition to exit on false
9323 CmpPredicate Pred;
9324 if (!ExitIfTrue)
9325 Pred = ExitCond->getCmpPredicate();
9326 else
9327 Pred = ExitCond->getInverseCmpPredicate();
9328 const ICmpInst::Predicate OriginalPred = Pred;
9329
9330 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9331 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9332
9333 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9334 AllowPredicates);
9335 if (EL.hasAnyInfo())
9336 return EL;
9337
9338 auto *ExhaustiveCount =
9339 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9340
9341 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9342 return ExhaustiveCount;
9343
9344 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9345 ExitCond->getOperand(1), L, OriginalPred);
9346}
9347ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9348 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9349 bool ControlsOnlyExit, bool AllowPredicates) {
9350
9351 // Try to evaluate any dependencies out of the loop.
9352 LHS = getSCEVAtScope(LHS, L);
9353 RHS = getSCEVAtScope(RHS, L);
9354
9355 // At this point, we would like to compute how many iterations of the
9356 // loop the predicate will return true for these inputs.
9357 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9358 // If there is a loop-invariant, force it into the RHS.
9359 std::swap(LHS, RHS);
9361 }
9362
9363 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9365 // Simplify the operands before analyzing them.
9366 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9367
9368 // If we have a comparison of a chrec against a constant, try to use value
9369 // ranges to answer this query.
9370 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9371 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9372 if (AddRec->getLoop() == L) {
9373 // Form the constant range.
9374 ConstantRange CompRange =
9375 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9376
9377 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9378 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9379 }
9380
9381 // If this loop must exit based on this condition (or execute undefined
9382 // behaviour), see if we can improve wrap flags. This is essentially
9383 // a must execute style proof.
9384 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9385 // If we can prove the test sequence produced must repeat the same values
9386 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9387 // because if it did, we'd have an infinite (undefined) loop.
9388 // TODO: We can peel off any functions which are invertible *in L*. Loop
9389 // invariant terms are effectively constants for our purposes here.
9390 SCEVUse InnerLHS = LHS;
9391 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9392 InnerLHS = ZExt->getOperand();
9393 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9394 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9395 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9396 /*OrNegative=*/true)) {
9397 auto Flags = AR->getNoWrapFlags();
9398 Flags = setFlags(Flags, SCEV::FlagNW);
9401 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9402 }
9403
9404 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9405 // From no-self-wrap, this follows trivially from the fact that every
9406 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9407 // last value before (un)signed wrap. Since we know that last value
9408 // didn't exit, nor will any smaller one.
9409 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9410 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9411 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9412 AR && AR->getLoop() == L && AR->isAffine() &&
9413 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9414 isKnownPositive(AR->getStepRecurrence(*this))) {
9415 auto Flags = AR->getNoWrapFlags();
9416 Flags = setFlags(Flags, WrapType);
9419 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9420 }
9421 }
9422 }
9423
9424 switch (Pred) {
9425 case ICmpInst::ICMP_NE: { // while (X != Y)
9426 // Convert to: while (X-Y != 0)
9427 if (LHS->getType()->isPointerTy()) {
9430 return LHS;
9431 }
9432 if (RHS->getType()->isPointerTy()) {
9435 return RHS;
9436 }
9437 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9438 AllowPredicates);
9439 if (EL.hasAnyInfo())
9440 return EL;
9441 break;
9442 }
9443 case ICmpInst::ICMP_EQ: { // while (X == Y)
9444 // Convert to: while (X-Y == 0)
9445 if (LHS->getType()->isPointerTy()) {
9448 return LHS;
9449 }
9450 if (RHS->getType()->isPointerTy()) {
9453 return RHS;
9454 }
9455 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9456 if (EL.hasAnyInfo()) return EL;
9457 break;
9458 }
9459 case ICmpInst::ICMP_SLE:
9460 case ICmpInst::ICMP_ULE:
9461 // Since the loop is finite, an invariant RHS cannot include the boundary
9462 // value, otherwise it would loop forever.
9463 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9464 !isLoopInvariant(RHS, L)) {
9465 // Otherwise, perform the addition in a wider type, to avoid overflow.
9466 // If the LHS is an addrec with the appropriate nowrap flag, the
9467 // extension will be sunk into it and the exit count can be analyzed.
9468 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9469 if (!OldType)
9470 break;
9471 // Prefer doubling the bitwidth over adding a single bit to make it more
9472 // likely that we use a legal type.
9473 auto *NewType =
9474 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9475 if (ICmpInst::isSigned(Pred)) {
9476 LHS = getSignExtendExpr(LHS, NewType);
9477 RHS = getSignExtendExpr(RHS, NewType);
9478 } else {
9479 LHS = getZeroExtendExpr(LHS, NewType);
9480 RHS = getZeroExtendExpr(RHS, NewType);
9481 }
9482 }
9484 [[fallthrough]];
9485 case ICmpInst::ICMP_SLT:
9486 case ICmpInst::ICMP_ULT: { // while (X < Y)
9487 bool IsSigned = ICmpInst::isSigned(Pred);
9488 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9489 AllowPredicates);
9490 if (EL.hasAnyInfo())
9491 return EL;
9492 break;
9493 }
9494 case ICmpInst::ICMP_SGE:
9495 case ICmpInst::ICMP_UGE:
9496 // Since the loop is finite, an invariant RHS cannot include the boundary
9497 // value, otherwise it would loop forever.
9498 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9499 !isLoopInvariant(RHS, L))
9500 break;
9502 [[fallthrough]];
9503 case ICmpInst::ICMP_SGT:
9504 case ICmpInst::ICMP_UGT: { // while (X > Y)
9505 bool IsSigned = ICmpInst::isSigned(Pred);
9506 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9507 AllowPredicates);
9508 if (EL.hasAnyInfo())
9509 return EL;
9510 break;
9511 }
9512 default:
9513 break;
9514 }
9515
9516 return getCouldNotCompute();
9517}
9518
9519ScalarEvolution::ExitLimit
9520ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9521 SwitchInst *Switch,
9522 BasicBlock *ExitingBlock,
9523 bool ControlsOnlyExit) {
9524 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9525
9526 // Give up if the exit is the default dest of a switch.
9527 if (Switch->getDefaultDest() == ExitingBlock)
9528 return getCouldNotCompute();
9529
9530 assert(L->contains(Switch->getDefaultDest()) &&
9531 "Default case must not exit the loop!");
9532 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9533 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9534
9535 // while (X != Y) --> while (X-Y != 0)
9536 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9537 if (EL.hasAnyInfo())
9538 return EL;
9539
9540 return getCouldNotCompute();
9541}
9542
9543static ConstantInt *
9545 ScalarEvolution &SE) {
9546 const SCEV *InVal = SE.getConstant(C);
9547 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9549 "Evaluation of SCEV at constant didn't fold correctly?");
9550 return cast<SCEVConstant>(Val)->getValue();
9551}
9552
9553ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9554 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9555 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9556 if (!RHS)
9557 return getCouldNotCompute();
9558
9559 const BasicBlock *Latch = L->getLoopLatch();
9560 if (!Latch)
9561 return getCouldNotCompute();
9562
9563 const BasicBlock *Predecessor = L->getLoopPredecessor();
9564 if (!Predecessor)
9565 return getCouldNotCompute();
9566
9567 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9568 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9569 // OutShiftAmt.
9570 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9571 Instruction::BinaryOps &OutOpCode,
9572 unsigned &OutShiftAmt) {
9573 using namespace PatternMatch;
9574
9575 ConstantInt *ShiftAmt;
9576 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9577 OutOpCode = Instruction::LShr;
9578 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9579 OutOpCode = Instruction::AShr;
9580 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9581 OutOpCode = Instruction::Shl;
9582 else
9583 return false;
9584
9585 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9586 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9587 return false;
9588 OutShiftAmt = Amt;
9589 return true;
9590 };
9591
9592 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9593 //
9594 // loop:
9595 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9596 // %iv.shifted = lshr i32 %iv, <positive constant>
9597 //
9598 // Return true on a successful match. Return the corresponding PHI node (%iv
9599 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9600 // shift amount in ShiftAmtOut.
9601 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9602 Instruction::BinaryOps &OpCodeOut,
9603 unsigned &ShiftAmtOut) {
9604 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9605
9606 {
9608 Value *V;
9609 unsigned Amt;
9610
9611 // If we encounter a shift instruction, "peel off" the shift operation,
9612 // and remember that we did so. Later when we inspect %iv's backedge
9613 // value, we will make sure that the backedge value uses the same
9614 // operation.
9615 //
9616 // Note: the peeled shift operation does not have to be the same
9617 // instruction as the one feeding into the PHI's backedge value. We only
9618 // really care about it being the same *kind* of shift instruction --
9619 // that's all that is required for our later inferences to hold.
9620 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9621 PostShiftOpCode = OpC;
9622 LHS = V;
9623 }
9624 }
9625
9626 PNOut = dyn_cast<PHINode>(LHS);
9627 if (!PNOut || PNOut->getParent() != L->getHeader())
9628 return false;
9629
9630 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9631 Value *OpLHS;
9632
9633 return
9634 // The backedge value for the PHI node must be a shift by a positive
9635 // amount
9636 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9637
9638 // of the PHI node itself
9639 OpLHS == PNOut &&
9640
9641 // and the kind of shift should be match the kind of shift we peeled
9642 // off, if any.
9643 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9644 };
9645
9646 PHINode *PN;
9648 unsigned ShiftAmt;
9649 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9650 return getCouldNotCompute();
9651
9652 const DataLayout &DL = getDataLayout();
9653
9654 // The key rationale for this optimization is that for some kinds of shift
9655 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9656 // within a finite number of iterations. If the condition guarding the
9657 // backedge (in the sense that the backedge is taken if the condition is true)
9658 // is false for the value the shift recurrence stabilizes to, then we know
9659 // that the backedge is taken only a finite number of times.
9660
9661 ConstantInt *StableValue = nullptr;
9662 switch (OpCode) {
9663 default:
9664 llvm_unreachable("Impossible case!");
9665
9666 case Instruction::AShr: {
9667 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9668 // bitwidth(K) iterations.
9669 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9670 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9671 Predecessor->getTerminator(), &DT);
9672 auto *Ty = cast<IntegerType>(RHS->getType());
9673 if (Known.isNonNegative())
9674 StableValue = ConstantInt::get(Ty, 0);
9675 else if (Known.isNegative())
9676 StableValue = ConstantInt::get(Ty, -1, true);
9677 else
9678 return getCouldNotCompute();
9679
9680 break;
9681 }
9682 case Instruction::LShr:
9683 case Instruction::Shl:
9684 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9685 // stabilize to 0 in at most bitwidth(K) iterations.
9686 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9687 break;
9688 }
9689
9690 auto *Result =
9691 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9692 assert(Result->getType()->isIntegerTy(1) &&
9693 "Otherwise cannot be an operand to a branch instruction");
9694
9695 if (Result->isNullValue()) {
9696 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9697 unsigned MaxBTC = BitWidth;
9698
9699 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9700 // compute a tighter max backedge-taken count from the range of the start
9701 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9702 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9703 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9704 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9705 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9706 const SCEV *StartSCEV = getSCEV(StartValue);
9707 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9708 if (MaxStart.isStrictlyPositive()) {
9709 unsigned ActiveBits = MaxStart.getActiveBits();
9710 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9711 MaxBTC = std::min(MaxBTC, RangeBTC);
9712 }
9713 }
9714
9715 const SCEV *UpperBound =
9717 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9718 }
9719
9720 return getCouldNotCompute();
9721}
9722
9723/// Return true if we can constant fold an instruction of the specified type,
9724/// assuming that all operands were constants.
9725static bool CanConstantFold(const Instruction *I) {
9729 return true;
9730
9731 if (const CallInst *CI = dyn_cast<CallInst>(I))
9732 if (const Function *F = CI->getCalledFunction())
9733 return canConstantFoldCallTo(CI, F);
9734 return false;
9735}
9736
9737/// Determine whether this instruction can constant evolve within this loop
9738/// assuming its operands can all constant evolve.
9739static bool canConstantEvolve(Instruction *I, const Loop *L) {
9740 // An instruction outside of the loop can't be derived from a loop PHI.
9741 if (!L->contains(I)) return false;
9742
9743 if (isa<PHINode>(I)) {
9744 // We don't currently keep track of the control flow needed to evaluate
9745 // PHIs, so we cannot handle PHIs inside of loops.
9746 return L->getHeader() == I->getParent();
9747 }
9748
9749 // If we won't be able to constant fold this expression even if the operands
9750 // are constants, bail early.
9751 return CanConstantFold(I);
9752}
9753
9754/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9755/// recursing through each instruction operand until reaching a loop header phi.
9756static PHINode *
9759 unsigned Depth) {
9761 return nullptr;
9762
9763 // Otherwise, we can evaluate this instruction if all of its operands are
9764 // constant or derived from a PHI node themselves.
9765 PHINode *PHI = nullptr;
9766 for (Value *Op : UseInst->operands()) {
9767 if (isa<Constant>(Op)) continue;
9768
9770 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9771
9772 PHINode *P = dyn_cast<PHINode>(OpInst);
9773 if (!P)
9774 // If this operand is already visited, reuse the prior result.
9775 // We may have P != PHI if this is the deepest point at which the
9776 // inconsistent paths meet.
9777 P = PHIMap.lookup(OpInst);
9778 if (!P) {
9779 // Recurse and memoize the results, whether a phi is found or not.
9780 // This recursive call invalidates pointers into PHIMap.
9781 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9782 PHIMap[OpInst] = P;
9783 }
9784 if (!P)
9785 return nullptr; // Not evolving from PHI
9786 if (PHI && PHI != P)
9787 return nullptr; // Evolving from multiple different PHIs.
9788 PHI = P;
9789 }
9790 // This is a expression evolving from a constant PHI!
9791 return PHI;
9792}
9793
9794/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9795/// in the loop that V is derived from. We allow arbitrary operations along the
9796/// way, but the operands of an operation must either be constants or a value
9797/// derived from a constant PHI. If this expression does not fit with these
9798/// constraints, return null.
9801 if (!I || !canConstantEvolve(I, L)) return nullptr;
9802
9803 if (PHINode *PN = dyn_cast<PHINode>(I))
9804 return PN;
9805
9806 // Record non-constant instructions contained by the loop.
9808 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9809}
9810
9811/// EvaluateExpression - Given an expression that passes the
9812/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9813/// in the loop has the value PHIVal. If we can't fold this expression for some
9814/// reason, return null.
9817 const DataLayout &DL,
9818 const TargetLibraryInfo *TLI) {
9819 // Convenient constant check, but redundant for recursive calls.
9820 if (Constant *C = dyn_cast<Constant>(V)) return C;
9822 if (!I) return nullptr;
9823
9824 if (Constant *C = Vals.lookup(I)) return C;
9825
9826 // An instruction inside the loop depends on a value outside the loop that we
9827 // weren't given a mapping for, or a value such as a call inside the loop.
9828 if (!canConstantEvolve(I, L)) return nullptr;
9829
9830 // An unmapped PHI can be due to a branch or another loop inside this loop,
9831 // or due to this not being the initial iteration through a loop where we
9832 // couldn't compute the evolution of this particular PHI last time.
9833 if (isa<PHINode>(I)) return nullptr;
9834
9835 std::vector<Constant*> Operands(I->getNumOperands());
9836
9837 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9838 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9839 if (!Operand) {
9840 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9841 if (!Operands[i]) return nullptr;
9842 continue;
9843 }
9844 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9845 Vals[Operand] = C;
9846 if (!C) return nullptr;
9847 Operands[i] = C;
9848 }
9849
9850 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9851 /*AllowNonDeterministic=*/false);
9852}
9853
9854
9855// If every incoming value to PN except the one for BB is a specific Constant,
9856// return that, else return nullptr.
9858 Constant *IncomingVal = nullptr;
9859
9860 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9861 if (PN->getIncomingBlock(i) == BB)
9862 continue;
9863
9864 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9865 if (!CurrentVal)
9866 return nullptr;
9867
9868 if (IncomingVal != CurrentVal) {
9869 if (IncomingVal)
9870 return nullptr;
9871 IncomingVal = CurrentVal;
9872 }
9873 }
9874
9875 return IncomingVal;
9876}
9877
9878/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9879/// in the header of its containing loop, we know the loop executes a
9880/// constant number of times, and the PHI node is just a recurrence
9881/// involving constants, fold it.
9882Constant *
9883ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9884 const APInt &BEs,
9885 const Loop *L) {
9886 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9887 if (!Inserted)
9888 return I->second;
9889
9891 return nullptr; // Not going to evaluate it.
9892
9893 Constant *&RetVal = I->second;
9894
9895 DenseMap<Instruction *, Constant *> CurrentIterVals;
9896 BasicBlock *Header = L->getHeader();
9897 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9898
9899 BasicBlock *Latch = L->getLoopLatch();
9900 if (!Latch)
9901 return nullptr;
9902
9903 for (PHINode &PHI : Header->phis()) {
9904 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9905 CurrentIterVals[&PHI] = StartCST;
9906 }
9907 if (!CurrentIterVals.count(PN))
9908 return RetVal = nullptr;
9909
9910 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9911
9912 // Execute the loop symbolically to determine the exit value.
9913 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9914 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9915
9916 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9917 unsigned IterationNum = 0;
9918 const DataLayout &DL = getDataLayout();
9919 for (; ; ++IterationNum) {
9920 if (IterationNum == NumIterations)
9921 return RetVal = CurrentIterVals[PN]; // Got exit value!
9922
9923 // Compute the value of the PHIs for the next iteration.
9924 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9925 DenseMap<Instruction *, Constant *> NextIterVals;
9926 Constant *NextPHI =
9927 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9928 if (!NextPHI)
9929 return nullptr; // Couldn't evaluate!
9930 NextIterVals[PN] = NextPHI;
9931
9932 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9933
9934 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9935 // cease to be able to evaluate one of them or if they stop evolving,
9936 // because that doesn't necessarily prevent us from computing PN.
9938 for (const auto &I : CurrentIterVals) {
9939 PHINode *PHI = dyn_cast<PHINode>(I.first);
9940 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9941 PHIsToCompute.emplace_back(PHI, I.second);
9942 }
9943 // We use two distinct loops because EvaluateExpression may invalidate any
9944 // iterators into CurrentIterVals.
9945 for (const auto &I : PHIsToCompute) {
9946 PHINode *PHI = I.first;
9947 Constant *&NextPHI = NextIterVals[PHI];
9948 if (!NextPHI) { // Not already computed.
9949 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9950 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9951 }
9952 if (NextPHI != I.second)
9953 StoppedEvolving = false;
9954 }
9955
9956 // If all entries in CurrentIterVals == NextIterVals then we can stop
9957 // iterating, the loop can't continue to change.
9958 if (StoppedEvolving)
9959 return RetVal = CurrentIterVals[PN];
9960
9961 CurrentIterVals.swap(NextIterVals);
9962 }
9963}
9964
9965const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9966 Value *Cond,
9967 bool ExitWhen) {
9968 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9969 if (!PN) return getCouldNotCompute();
9970
9971 // If the loop is canonicalized, the PHI will have exactly two entries.
9972 // That's the only form we support here.
9973 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9974
9975 DenseMap<Instruction *, Constant *> CurrentIterVals;
9976 BasicBlock *Header = L->getHeader();
9977 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9978
9979 BasicBlock *Latch = L->getLoopLatch();
9980 assert(Latch && "Should follow from NumIncomingValues == 2!");
9981
9982 for (PHINode &PHI : Header->phis()) {
9983 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9984 CurrentIterVals[&PHI] = StartCST;
9985 }
9986 if (!CurrentIterVals.count(PN))
9987 return getCouldNotCompute();
9988
9989 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9990 // the loop symbolically to determine when the condition gets a value of
9991 // "ExitWhen".
9992 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9993 const DataLayout &DL = getDataLayout();
9994 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9995 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9996 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9997
9998 // Couldn't symbolically evaluate.
9999 if (!CondVal) return getCouldNotCompute();
10000
10001 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10002 ++NumBruteForceTripCountsComputed;
10003 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10004 }
10005
10006 // Update all the PHI nodes for the next iteration.
10007 DenseMap<Instruction *, Constant *> NextIterVals;
10008
10009 // Create a list of which PHIs we need to compute. We want to do this before
10010 // calling EvaluateExpression on them because that may invalidate iterators
10011 // into CurrentIterVals.
10012 SmallVector<PHINode *, 8> PHIsToCompute;
10013 for (const auto &I : CurrentIterVals) {
10014 PHINode *PHI = dyn_cast<PHINode>(I.first);
10015 if (!PHI || PHI->getParent() != Header) continue;
10016 PHIsToCompute.push_back(PHI);
10017 }
10018 for (PHINode *PHI : PHIsToCompute) {
10019 Constant *&NextPHI = NextIterVals[PHI];
10020 if (NextPHI) continue; // Already computed!
10021
10022 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10023 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10024 }
10025 CurrentIterVals.swap(NextIterVals);
10026 }
10027
10028 // Too many iterations were needed to evaluate.
10029 return getCouldNotCompute();
10030}
10031
10033 auto &Values = ValuesAtScopes[V];
10034 // Check to see if we've folded this expression at this loop before.
10035 for (auto &LS : Values)
10036 if (LS.first == L)
10037 return LS.second ? LS.second : SCEVUse(V);
10038
10039 Values.emplace_back(L, nullptr);
10040
10041 // Otherwise compute it.
10042 SCEVUse C = computeSCEVAtScope(V, L);
10043 for (auto &LS : reverse(ValuesAtScopes[V]))
10044 if (LS.first == L) {
10045 LS.second = C;
10046 // Record the dependency under the bare expression: invalidation walks
10047 // expressions, and any use flags on C do not change which expression
10048 // this is the value at scope of.
10049 if (!isa<SCEVConstant>(C))
10050 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10051 break;
10052 }
10053 return C;
10054}
10055
10056/// This builds up a Constant using the ConstantExpr interface. That way, we
10057/// will return Constants for objects which aren't represented by a
10058/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10059/// Returns NULL if the SCEV isn't representable as a Constant.
10061 switch (V->getSCEVType()) {
10062 case scCouldNotCompute:
10063 case scAddRecExpr:
10064 case scVScale:
10065 return nullptr;
10066 case scConstant:
10067 return cast<SCEVConstant>(V)->getValue();
10068 case scUnknown:
10070 case scPtrToAddr: {
10072 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10073 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10074
10075 return nullptr;
10076 }
10077 case scTruncate: {
10079 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10080 return ConstantExpr::getTrunc(CastOp, ST->getType());
10081 return nullptr;
10082 }
10083 case scAddExpr: {
10084 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10085 Constant *C = nullptr;
10086 for (const SCEV *Op : SA->operands()) {
10088 if (!OpC)
10089 return nullptr;
10090 if (!C) {
10091 C = OpC;
10092 continue;
10093 }
10094 assert(!C->getType()->isPointerTy() &&
10095 "Can only have one pointer, and it must be last");
10096 if (OpC->getType()->isPointerTy()) {
10097 // The offsets have been converted to bytes. We can add bytes using
10098 // an i8 GEP.
10099 C = ConstantExpr::getPtrAdd(OpC, C);
10100 } else {
10101 C = ConstantExpr::getAdd(C, OpC);
10102 }
10103 }
10104 return C;
10105 }
10106 case scMulExpr:
10107 case scSignExtend:
10108 case scZeroExtend:
10109 case scUDivExpr:
10110 case scSMaxExpr:
10111 case scUMaxExpr:
10112 case scSMinExpr:
10113 case scUMinExpr:
10115 return nullptr;
10116 }
10117 llvm_unreachable("Unknown SCEV kind!");
10118}
10119
10120const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10121 SmallVectorImpl<SCEVUse> &NewOps) {
10122 switch (S->getSCEVType()) {
10123 case scTruncate:
10124 case scZeroExtend:
10125 case scSignExtend:
10126 case scPtrToAddr:
10127 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10128 case scAddRecExpr: {
10129 auto *AddRec = cast<SCEVAddRecExpr>(S);
10130 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10131 }
10132 case scAddExpr:
10133 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10134 case scMulExpr:
10135 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10136 case scUDivExpr:
10137 return getUDivExpr(NewOps[0], NewOps[1]);
10138 case scUMaxExpr:
10139 case scSMaxExpr:
10140 case scUMinExpr:
10141 case scSMinExpr:
10142 return getMinMaxExpr(S->getSCEVType(), NewOps);
10144 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10145 case scConstant:
10146 case scVScale:
10147 case scUnknown:
10148 return S;
10149 case scCouldNotCompute:
10150 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10151 }
10152 llvm_unreachable("Unknown SCEV kind!");
10153}
10154
10155SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10156 switch (V->getSCEVType()) {
10157 case scConstant:
10158 case scVScale:
10159 return V;
10160 case scAddRecExpr: {
10161 // If this is a loop recurrence for a loop that does not contain L, then we
10162 // are dealing with the final value computed by the loop.
10163 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10164 // First, attempt to evaluate each operand.
10165 // Avoid performing the look-up in the common case where the specified
10166 // expression has no loop-variant portions.
10167 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10168 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10169 if (OpAtScope == AddRec->getOperand(i))
10170 continue;
10171
10172 // Okay, at least one of these operands is loop variant but might be
10173 // foldable. Build a new instance of the folded commutative expression.
10175 NewOps.reserve(AddRec->getNumOperands());
10176 append_range(NewOps, AddRec->operands().take_front(i));
10177 NewOps.push_back(OpAtScope);
10178 for (++i; i != e; ++i)
10179 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10180
10181 const SCEV *FoldedRec = getAddRecExpr(
10182 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10183 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10184 // The addrec may be folded to a nonrecurrence, for example, if the
10185 // induction variable is multiplied by zero after constant folding. Go
10186 // ahead and return the folded value.
10187 if (!AddRec)
10188 return FoldedRec;
10189 break;
10190 }
10191
10192 // If the scope is outside the addrec's loop, evaluate it by using the
10193 // loop exit value of the addrec.
10194 if (!AddRec->getLoop()->contains(L)) {
10195 SCEVUse ExitValue = AddRec->getExitValue(*this);
10196 if (isa<SCEVCouldNotCompute>(ExitValue))
10197 return AddRec;
10198 return ExitValue;
10199 }
10200
10201 return AddRec;
10202 }
10203 case scTruncate:
10204 case scZeroExtend:
10205 case scSignExtend:
10206 case scPtrToAddr:
10207 case scAddExpr:
10208 case scMulExpr:
10209 case scUDivExpr:
10210 case scUMaxExpr:
10211 case scSMaxExpr:
10212 case scUMinExpr:
10213 case scSMinExpr:
10214 case scSequentialUMinExpr: {
10215 ArrayRef<SCEVUse> Ops = V->operands();
10216 // Avoid performing the look-up in the common case where the specified
10217 // expression has no loop-variant portions.
10218 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10219 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10220 if (OpAtScope != Ops[i].getPointer()) {
10221 // Okay, at least one of these operands is loop variant but might be
10222 // foldable. Build a new instance of the folded commutative expression.
10224 NewOps.reserve(Ops.size());
10225 append_range(NewOps, Ops.take_front(i));
10226 NewOps.push_back(OpAtScope);
10227
10228 for (++i; i != e; ++i) {
10229 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10230 NewOps.push_back(OpAtScope);
10231 }
10232
10233 return getWithOperands(V, NewOps);
10234 }
10235 }
10236 // If we got here, all operands are loop invariant.
10237 return V;
10238 }
10239 case scUnknown: {
10240 // If this instruction is evolved from a constant-evolving PHI, compute the
10241 // exit value from the loop without using SCEVs.
10242 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10244 if (!I)
10245 return V; // This is some other type of SCEVUnknown, just return it.
10246
10247 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10248 const Loop *CurrLoop = this->LI[I->getParent()];
10249 // Looking for loop exit value.
10250 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10251 PN->getParent() == CurrLoop->getHeader()) {
10252 // Okay, there is no closed form solution for the PHI node. Check
10253 // to see if the loop that contains it has a known backedge-taken
10254 // count. If so, we may be able to force computation of the exit
10255 // value.
10256 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10257 // This trivial case can show up in some degenerate cases where
10258 // the incoming IR has not yet been fully simplified.
10259 if (BackedgeTakenCount->isZero()) {
10260 Value *InitValue = nullptr;
10261 bool MultipleInitValues = false;
10262 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10263 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10264 if (!InitValue)
10265 InitValue = PN->getIncomingValue(i);
10266 else if (InitValue != PN->getIncomingValue(i)) {
10267 MultipleInitValues = true;
10268 break;
10269 }
10270 }
10271 }
10272 if (!MultipleInitValues && InitValue)
10273 return getSCEV(InitValue);
10274 }
10275 // Do we have a loop invariant value flowing around the backedge
10276 // for a loop which must execute the backedge?
10277 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10278 isKnownNonZero(BackedgeTakenCount) &&
10279 PN->getNumIncomingValues() == 2) {
10280
10281 unsigned InLoopPred =
10282 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10283 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10284 if (CurrLoop->isLoopInvariant(BackedgeVal))
10285 return getSCEV(BackedgeVal);
10286 }
10287 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10288 // Okay, we know how many times the containing loop executes. If
10289 // this is a constant evolving PHI node, get the final value at
10290 // the specified iteration number.
10291 Constant *RV =
10292 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10293 if (RV)
10294 return getSCEV(RV);
10295 }
10296 }
10297 }
10298
10299 // Okay, this is an expression that we cannot symbolically evaluate
10300 // into a SCEV. Check to see if it's possible to symbolically evaluate
10301 // the arguments into constants, and if so, try to constant propagate the
10302 // result. This is particularly useful for computing loop exit values.
10303 if (!CanConstantFold(I))
10304 return V; // This is some other type of SCEVUnknown, just return it.
10305
10306 SmallVector<Constant *, 4> Operands;
10307 Operands.reserve(I->getNumOperands());
10308 bool MadeImprovement = false;
10309 for (Value *Op : I->operands()) {
10310 if (Constant *C = dyn_cast<Constant>(Op)) {
10311 Operands.push_back(C);
10312 continue;
10313 }
10314
10315 // If any of the operands is non-constant and if they are
10316 // non-integer and non-pointer, don't even try to analyze them
10317 // with scev techniques.
10318 if (!isSCEVable(Op->getType()))
10319 return V;
10320
10321 const SCEV *OrigV = getSCEV(Op);
10322 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10323 MadeImprovement |= OrigV != OpV;
10324
10326 if (!C)
10327 return V;
10328 assert(C->getType() == Op->getType() && "Type mismatch");
10329 Operands.push_back(C);
10330 }
10331
10332 // Check to see if getSCEVAtScope actually made an improvement.
10333 if (!MadeImprovement)
10334 return V; // This is some other type of SCEVUnknown, just return it.
10335
10336 Constant *C = nullptr;
10337 const DataLayout &DL = getDataLayout();
10338 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10339 /*AllowNonDeterministic=*/false);
10340 if (!C)
10341 return V;
10342 return getSCEV(C);
10343 }
10344 case scCouldNotCompute:
10345 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10346 }
10347 llvm_unreachable("Unknown SCEV type!");
10348}
10349
10351 return getSCEVAtScope(getSCEV(V), L);
10352}
10353
10354const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10356 return stripInjectiveFunctions(ZExt->getOperand());
10358 return stripInjectiveFunctions(SExt->getOperand());
10359 return S;
10360}
10361
10362/// Finds the minimum unsigned root of the following equation:
10363///
10364/// A * X = B (mod N)
10365///
10366/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10367/// A and B isn't important.
10368///
10369/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10370static const SCEV *
10373 ScalarEvolution &SE, const Loop *L) {
10374 uint32_t BW = A.getBitWidth();
10375 assert(BW == SE.getTypeSizeInBits(B->getType()));
10376 assert(A != 0 && "A must be non-zero.");
10377
10378 // 1. D = gcd(A, N)
10379 //
10380 // The gcd of A and N may have only one prime factor: 2. The number of
10381 // trailing zeros in A is its multiplicity
10382 uint32_t Mult2 = A.countr_zero();
10383 // D = 2^Mult2
10384
10385 // 2. Check if B is divisible by D.
10386 //
10387 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10388 // is not less than multiplicity of this prime factor for D.
10389 unsigned MinTZ = SE.getMinTrailingZeros(B);
10390 // Try again with the terminator of the loop predecessor for context-specific
10391 // result, if MinTZ s too small.
10392 if (MinTZ < Mult2 && L->getLoopPredecessor())
10393 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10394 if (MinTZ < Mult2) {
10395 // Check if we can prove there's no remainder using URem.
10396 const SCEV *URem =
10397 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10398 const SCEV *Zero = SE.getZero(B->getType());
10399 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10400 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10401 if (!Predicates)
10402 return SE.getCouldNotCompute();
10403
10404 // Avoid adding a predicate that is known to be false.
10405 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10406 return SE.getCouldNotCompute();
10407 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10408 }
10409 }
10410
10411 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10412 // modulo (N / D).
10413 //
10414 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10415 // (N / D) in general. The inverse itself always fits into BW bits, though,
10416 // so we immediately truncate it.
10417 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10418 APInt I = AD.multiplicativeInverse().zext(BW);
10419
10420 // 4. Compute the minimum unsigned root of the equation:
10421 // I * (B / D) mod (N / D)
10422 // To simplify the computation, we factor out the divide by D:
10423 // (I * B mod N) / D
10424 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10425 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10426}
10427
10428/// For a given quadratic addrec, generate coefficients of the corresponding
10429/// quadratic equation, multiplied by a common value to ensure that they are
10430/// integers.
10431/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10432/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10433/// were multiplied by, and BitWidth is the bit width of the original addrec
10434/// coefficients.
10435/// This function returns std::nullopt if the addrec coefficients are not
10436/// compile- time constants.
10437static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10439 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10440 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10441 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10442 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10443 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10444 << *AddRec << '\n');
10445
10446 // We currently can only solve this if the coefficients are constants.
10447 if (!LC || !MC || !NC) {
10448 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10449 return std::nullopt;
10450 }
10451
10452 APInt L = LC->getAPInt();
10453 APInt M = MC->getAPInt();
10454 APInt N = NC->getAPInt();
10455 assert(!N.isZero() && "This is not a quadratic addrec");
10456
10457 unsigned BitWidth = LC->getAPInt().getBitWidth();
10458 unsigned NewWidth = BitWidth + 1;
10459 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10460 << BitWidth << '\n');
10461 // The sign-extension (as opposed to a zero-extension) here matches the
10462 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10463 N = N.sext(NewWidth);
10464 M = M.sext(NewWidth);
10465 L = L.sext(NewWidth);
10466
10467 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10468 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10469 // L+M, L+2M+N, L+3M+3N, ...
10470 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10471 //
10472 // The equation Acc = 0 is then
10473 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10474 // In a quadratic form it becomes:
10475 // N n^2 + (2M-N) n + 2L = 0.
10476
10477 APInt A = N;
10478 APInt B = 2 * M - A;
10479 APInt C = 2 * L;
10480 APInt T = APInt(NewWidth, 2);
10481 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10482 << "x + " << C << ", coeff bw: " << NewWidth
10483 << ", multiplied by " << T << '\n');
10484 return std::make_tuple(A, B, C, T, BitWidth);
10485}
10486
10487/// Helper function to compare optional APInts:
10488/// (a) if X and Y both exist, return min(X, Y),
10489/// (b) if neither X nor Y exist, return std::nullopt,
10490/// (c) if exactly one of X and Y exists, return that value.
10491static std::optional<APInt> MinOptional(std::optional<APInt> X,
10492 std::optional<APInt> Y) {
10493 if (X && Y) {
10494 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10495 APInt XW = X->sext(W);
10496 APInt YW = Y->sext(W);
10497 return XW.slt(YW) ? *X : *Y;
10498 }
10499 if (!X && !Y)
10500 return std::nullopt;
10501 return X ? *X : *Y;
10502}
10503
10504/// Helper function to truncate an optional APInt to a given BitWidth.
10505/// When solving addrec-related equations, it is preferable to return a value
10506/// that has the same bit width as the original addrec's coefficients. If the
10507/// solution fits in the original bit width, truncate it (except for i1).
10508/// Returning a value of a different bit width may inhibit some optimizations.
10509///
10510/// In general, a solution to a quadratic equation generated from an addrec
10511/// may require BW+1 bits, where BW is the bit width of the addrec's
10512/// coefficients. The reason is that the coefficients of the quadratic
10513/// equation are BW+1 bits wide (to avoid truncation when converting from
10514/// the addrec to the equation).
10515static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10516 unsigned BitWidth) {
10517 if (!X)
10518 return std::nullopt;
10519 unsigned W = X->getBitWidth();
10521 return X->trunc(BitWidth);
10522 return X;
10523}
10524
10525/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10526/// iterations. The values L, M, N are assumed to be signed, and they
10527/// should all have the same bit widths.
10528/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10529/// where BW is the bit width of the addrec's coefficients.
10530/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10531/// returned as such, otherwise the bit width of the returned value may
10532/// be greater than BW.
10533///
10534/// This function returns std::nullopt if
10535/// (a) the addrec coefficients are not constant, or
10536/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10537/// like x^2 = 5, no integer solutions exist, in other cases an integer
10538/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10539static std::optional<APInt>
10541 APInt A, B, C, M;
10542 unsigned BitWidth;
10543 auto T = GetQuadraticEquation(AddRec);
10544 if (!T)
10545 return std::nullopt;
10546
10547 std::tie(A, B, C, M, BitWidth) = *T;
10548 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10549 std::optional<APInt> X =
10551 if (!X)
10552 return std::nullopt;
10553
10554 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10555 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10556 if (!V->isZero())
10557 return std::nullopt;
10558
10559 return TruncIfPossible(X, BitWidth);
10560}
10561
10562/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10563/// iterations. The values M, N are assumed to be signed, and they
10564/// should all have the same bit widths.
10565/// Find the least n such that c(n) does not belong to the given range,
10566/// while c(n-1) does.
10567///
10568/// This function returns std::nullopt if
10569/// (a) the addrec coefficients are not constant, or
10570/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10571/// bounds of the range.
10572static std::optional<APInt>
10574 const ConstantRange &Range, ScalarEvolution &SE) {
10575 assert(AddRec->getOperand(0)->isZero() &&
10576 "Starting value of addrec should be 0");
10577 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10578 << Range << ", addrec " << *AddRec << '\n');
10579 // This case is handled in getNumIterationsInRange. Here we can assume that
10580 // we start in the range.
10581 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10582 "Addrec's initial value should be in range");
10583
10584 APInt A, B, C, M;
10585 unsigned BitWidth;
10586 auto T = GetQuadraticEquation(AddRec);
10587 if (!T)
10588 return std::nullopt;
10589
10590 // Be careful about the return value: there can be two reasons for not
10591 // returning an actual number. First, if no solutions to the equations
10592 // were found, and second, if the solutions don't leave the given range.
10593 // The first case means that the actual solution is "unknown", the second
10594 // means that it's known, but not valid. If the solution is unknown, we
10595 // cannot make any conclusions.
10596 // Return a pair: the optional solution and a flag indicating if the
10597 // solution was found.
10598 auto SolveForBoundary =
10599 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10600 // Solve for signed overflow and unsigned overflow, pick the lower
10601 // solution.
10602 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10603 << Bound << " (before multiplying by " << M << ")\n");
10604 Bound *= M; // The quadratic equation multiplier.
10605
10606 std::optional<APInt> SO;
10607 if (BitWidth > 1) {
10608 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10609 "signed overflow\n");
10611 }
10612 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10613 "unsigned overflow\n");
10614 std::optional<APInt> UO =
10616
10617 auto LeavesRange = [&] (const APInt &X) {
10618 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10619 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10620 if (Range.contains(V0->getValue()))
10621 return false;
10622 // X should be at least 1, so X-1 is non-negative.
10623 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10625 if (Range.contains(V1->getValue()))
10626 return true;
10627 return false;
10628 };
10629
10630 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10631 // can be a solution, but the function failed to find it. We cannot treat it
10632 // as "no solution".
10633 if (!SO || !UO)
10634 return {std::nullopt, false};
10635
10636 // Check the smaller value first to see if it leaves the range.
10637 // At this point, both SO and UO must have values.
10638 std::optional<APInt> Min = MinOptional(SO, UO);
10639 if (LeavesRange(*Min))
10640 return { Min, true };
10641 std::optional<APInt> Max = Min == SO ? UO : SO;
10642 if (LeavesRange(*Max))
10643 return { Max, true };
10644
10645 // Solutions were found, but were eliminated, hence the "true".
10646 return {std::nullopt, true};
10647 };
10648
10649 std::tie(A, B, C, M, BitWidth) = *T;
10650 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10651 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10652 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10653 auto SL = SolveForBoundary(Lower);
10654 auto SU = SolveForBoundary(Upper);
10655 // If any of the solutions was unknown, no meaninigful conclusions can
10656 // be made.
10657 if (!SL.second || !SU.second)
10658 return std::nullopt;
10659
10660 // Claim: The correct solution is not some value between Min and Max.
10661 //
10662 // Justification: Assuming that Min and Max are different values, one of
10663 // them is when the first signed overflow happens, the other is when the
10664 // first unsigned overflow happens. Crossing the range boundary is only
10665 // possible via an overflow (treating 0 as a special case of it, modeling
10666 // an overflow as crossing k*2^W for some k).
10667 //
10668 // The interesting case here is when Min was eliminated as an invalid
10669 // solution, but Max was not. The argument is that if there was another
10670 // overflow between Min and Max, it would also have been eliminated if
10671 // it was considered.
10672 //
10673 // For a given boundary, it is possible to have two overflows of the same
10674 // type (signed/unsigned) without having the other type in between: this
10675 // can happen when the vertex of the parabola is between the iterations
10676 // corresponding to the overflows. This is only possible when the two
10677 // overflows cross k*2^W for the same k. In such case, if the second one
10678 // left the range (and was the first one to do so), the first overflow
10679 // would have to enter the range, which would mean that either we had left
10680 // the range before or that we started outside of it. Both of these cases
10681 // are contradictions.
10682 //
10683 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10684 // solution is not some value between the Max for this boundary and the
10685 // Min of the other boundary.
10686 //
10687 // Justification: Assume that we had such Max_A and Min_B corresponding
10688 // to range boundaries A and B and such that Max_A < Min_B. If there was
10689 // a solution between Max_A and Min_B, it would have to be caused by an
10690 // overflow corresponding to either A or B. It cannot correspond to B,
10691 // since Min_B is the first occurrence of such an overflow. If it
10692 // corresponded to A, it would have to be either a signed or an unsigned
10693 // overflow that is larger than both eliminated overflows for A. But
10694 // between the eliminated overflows and this overflow, the values would
10695 // cover the entire value space, thus crossing the other boundary, which
10696 // is a contradiction.
10697
10698 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10699}
10700
10701ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10702 const Loop *L,
10703 bool ControlsOnlyExit,
10704 bool AllowPredicates) {
10705
10706 // This is only used for loops with a "x != y" exit test. The exit condition
10707 // is now expressed as a single expression, V = x-y. So the exit test is
10708 // effectively V != 0. We know and take advantage of the fact that this
10709 // expression only being used in a comparison by zero context.
10710
10712 // If the value is a constant
10713 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10714 // If the value is already zero, the branch will execute zero times.
10715 if (C->getValue()->isZero()) return C;
10716 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10717 }
10718
10719 const SCEVAddRecExpr *AddRec =
10720 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10721
10722 if (!AddRec && AllowPredicates)
10723 // Try to make this an AddRec using runtime tests, in the first X
10724 // iterations of this loop, where X is the SCEV expression found by the
10725 // algorithm below.
10726 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10727
10728 if (!AddRec || AddRec->getLoop() != L)
10729 return getCouldNotCompute();
10730
10731 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10732 // the quadratic equation to solve it.
10733 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10734 // We can only use this value if the chrec ends up with an exact zero
10735 // value at this index. When solving for "X*X != 5", for example, we
10736 // should not accept a root of 2.
10737 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10738 const auto *R = cast<SCEVConstant>(getConstant(*S));
10739 return ExitLimit(R, R, R, false, Predicates);
10740 }
10741 return getCouldNotCompute();
10742 }
10743
10744 // Otherwise we can only handle this if it is affine.
10745 if (!AddRec->isAffine())
10746 return getCouldNotCompute();
10747
10748 // If this is an affine expression, the execution count of this branch is
10749 // the minimum unsigned root of the following equation:
10750 //
10751 // Start + Step*N = 0 (mod 2^BW)
10752 //
10753 // equivalent to:
10754 //
10755 // Step*N = -Start (mod 2^BW)
10756 //
10757 // where BW is the common bit width of Start and Step.
10758
10759 // Get the initial value for the loop.
10760 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10761 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10762
10763 if (!isLoopInvariant(Step, L))
10764 return getCouldNotCompute();
10765
10766 LoopGuards Guards = LoopGuards::collect(L, *this);
10767 // Specialize step for this loop so we get context sensitive facts below.
10768 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10769
10770 // For positive steps (counting up until unsigned overflow):
10771 // N = -Start/Step (as unsigned)
10772 // For negative steps (counting down to zero):
10773 // N = Start/-Step
10774 // First compute the unsigned distance from zero in the direction of Step.
10775 bool CountDown = isKnownNegative(StepWLG);
10776 if (!CountDown && !isKnownNonNegative(StepWLG))
10777 return getCouldNotCompute();
10778
10779 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10780 // Handle unitary steps, which cannot wraparound.
10781 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10782 // N = Distance (as unsigned)
10783
10784 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10785 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10786 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10787
10788 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10789 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10790 // case, and see if we can improve the bound.
10791 //
10792 // Explicitly handling this here is necessary because getUnsignedRange
10793 // isn't context-sensitive; it doesn't know that we only care about the
10794 // range inside the loop.
10795 const SCEV *Zero = getZero(Distance->getType());
10796 const SCEV *One = getOne(Distance->getType());
10797 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10798 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10799 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10800 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10801 // Distance + 1; the range of Distance itself may be a wrapped set even
10802 // when the guards bound Distance + 1 tightly.
10803 APInt Max = APIntOps::umin(
10804 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10805 getUnsignedRangeMax(DistancePlusOne));
10806 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10807 }
10808 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10809 Predicates);
10810 }
10811
10812 // If the condition controls loop exit (the loop exits only if the expression
10813 // is true) and the addition is no-wrap we can use unsigned divide to
10814 // compute the backedge count. In this case, the step may not divide the
10815 // distance, but we don't care because if the condition is "missed" the loop
10816 // will have undefined behavior due to wrapping.
10817 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10818 loopHasNoAbnormalExits(AddRec->getLoop())) {
10819
10820 // If the stride is zero and the start is non-zero, the loop must be
10821 // infinite. In C++, most loops are finite by assumption, in which case the
10822 // step being zero implies UB must execute if the loop is entered.
10823 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10824 !isKnownNonZero(StepWLG))
10825 return getCouldNotCompute();
10826
10827 const SCEV *Exact =
10828 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10829 const SCEV *ConstantMax = getCouldNotCompute();
10830 if (Exact != getCouldNotCompute()) {
10831 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10832 ConstantMax =
10834 }
10835 const SCEV *SymbolicMax =
10836 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10837 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10838 }
10839
10840 // Solve the general equation.
10841 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10842 if (!StepC || StepC->getValue()->isZero())
10843 return getCouldNotCompute();
10844 const SCEV *E = SolveLinEquationWithOverflow(
10845 StepC->getAPInt(), getNegativeSCEV(Start),
10846 AllowPredicates ? &Predicates : nullptr, *this, L);
10847
10848 const SCEV *M = E;
10849 if (E != getCouldNotCompute()) {
10850 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10851 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10852 }
10853 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10854 return ExitLimit(E, M, S, false, Predicates);
10855}
10856
10857ScalarEvolution::ExitLimit
10858ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10859 // Loops that look like: while (X == 0) are very strange indeed. We don't
10860 // handle them yet except for the trivial case. This could be expanded in the
10861 // future as needed.
10862
10863 // If the value is a constant, check to see if it is known to be non-zero
10864 // already. If so, the backedge will execute zero times.
10865 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10866 if (!C->getValue()->isZero())
10867 return getZero(C->getType());
10868 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10869 }
10870
10871 // We could implement others, but I really doubt anyone writes loops like
10872 // this, and if they did, they would already be constant folded.
10873 return getCouldNotCompute();
10874}
10875
10876std::pair<const BasicBlock *, const BasicBlock *>
10877ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10878 const {
10879 // If the block has a unique predecessor, then there is no path from the
10880 // predecessor to the block that does not go through the direct edge
10881 // from the predecessor to the block.
10882 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10883 return {Pred, BB};
10884
10885 // A loop's header is defined to be a block that dominates the loop.
10886 // If the header has a unique predecessor outside the loop, it must be
10887 // a block that has exactly one successor that can reach the loop.
10888 if (const Loop *L = LI.getLoopFor(BB))
10889 return {L->getLoopPredecessor(), L->getHeader()};
10890
10891 return {nullptr, BB};
10892}
10893
10894/// SCEV structural equivalence is usually sufficient for testing whether two
10895/// expressions are equal, however for the purposes of looking for a condition
10896/// guarding a loop, it can be useful to be a little more general, since a
10897/// front-end may have replicated the controlling expression.
10898static bool HasSameValue(const SCEV *A, const SCEV *B) {
10899 // Quick check to see if they are the same SCEV.
10900 if (A == B) return true;
10901
10902 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10903 // Not all instructions that are "identical" compute the same value. For
10904 // instance, two distinct alloca instructions allocating the same type are
10905 // identical and do not read memory; but compute distinct values.
10906 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10907 };
10908
10909 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10910 // two different instructions with the same value. Check for this case.
10911 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10912 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10913 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10914 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10915 if (ComputesEqualValues(AI, BI))
10916 return true;
10917
10918 // Otherwise assume they may have a different value.
10919 return false;
10920}
10921
10922static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10923 const SCEV *Op0, *Op1;
10924 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10925 return false;
10926 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10927 LHS = Op1;
10928 return true;
10929 }
10930 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10931 LHS = Op0;
10932 return true;
10933 }
10934 return false;
10935}
10936
10938 SCEVUse &RHS, unsigned Depth) {
10939 bool Changed = false;
10940 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10941 // '0 != 0'.
10942 auto TrivialCase = [&](bool TriviallyTrue) {
10944 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10945 return true;
10946 };
10947 // If we hit the max recursion limit bail out.
10948 if (Depth >= 3)
10949 return false;
10950
10951 const SCEV *NewLHS, *NewRHS;
10952 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10953 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10954 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10955 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10956
10957 // (X * vscale) pred (Y * vscale) ==> X pred Y
10958 // when both multiples are NSW.
10959 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10960 // when both multiples are NUW.
10961 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10962 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10963 !ICmpInst::isSigned(Pred))) {
10964 LHS = NewLHS;
10965 RHS = NewRHS;
10966 Changed = true;
10967 }
10968 }
10969
10970 // Canonicalize a constant to the right side.
10971 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10972 // Check for both operands constant.
10973 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10974 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10975 return TrivialCase(false);
10976 return TrivialCase(true);
10977 }
10978 // Otherwise swap the operands to put the constant on the right.
10979 std::swap(LHS, RHS);
10981 Changed = true;
10982 }
10983
10984 // (K + A) pred (K + B) --> A pred B
10985 // For equality, no flags are needed.
10986 // For signed, both adds must be NSW. For unsigned, both must be NUW.
10987 {
10988 const SCEVConstant *C = nullptr;
10989 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10990 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10991 const auto *LAdd = cast<SCEVAddExpr>(LHS);
10992 const auto *RAdd = cast<SCEVAddExpr>(RHS);
10993 if (ICmpInst::isEquality(Pred) ||
10994 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
10995 RAdd->hasNoSignedWrap()) ||
10996 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
10997 RAdd->hasNoUnsignedWrap())) {
10998 LHS = NewLHS;
10999 RHS = NewRHS;
11000 Changed = true;
11001 }
11002 }
11003 }
11004
11005 // (C * A) pred (C * B) --> A pred B
11006 // For equality predicates, both muls must be NUW or both must be NSW
11007 // (either suffices to make multiplication by C injective; C == 0 is
11008 // impossible because SCEV folds 0 * X to 0).
11009 // For signed ordering, C must be positive and both muls must be NSW.
11010 // For unsigned ordering, both muls must be NUW.
11011 {
11012 const SCEVConstant *C = nullptr;
11013 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11014 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11015 const auto *LMul = cast<SCEVMulExpr>(LHS);
11016 const auto *RMul = cast<SCEVMulExpr>(RHS);
11017 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11018 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11019 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11020 (ICmpInst::isSigned(Pred) && BothNSW &&
11021 C->getAPInt().isStrictlyPositive()) ||
11022 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11023 LHS = NewLHS;
11024 RHS = NewRHS;
11025 Changed = true;
11026 }
11027 }
11028 }
11029
11030 // If we're comparing an addrec with a value which is loop-invariant in the
11031 // addrec's loop, put the addrec on the left. Also make a dominance check,
11032 // as both operands could be addrecs loop-invariant in each other's loop.
11033 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11034 const Loop *L = AR->getLoop();
11035 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11036 std::swap(LHS, RHS);
11038 Changed = true;
11039 }
11040 }
11041
11042 // If there's a constant operand, canonicalize comparisons with boundary
11043 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11044 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11045 const APInt &RA = RC->getAPInt();
11046
11047 bool SimplifiedByConstantRange = false;
11048
11049 if (!ICmpInst::isEquality(Pred)) {
11051 if (ExactCR.isFullSet())
11052 return TrivialCase(true);
11053 if (ExactCR.isEmptySet())
11054 return TrivialCase(false);
11055
11056 APInt NewRHS;
11057 CmpInst::Predicate NewPred;
11058 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11059 ICmpInst::isEquality(NewPred)) {
11060 // We were able to convert an inequality to an equality.
11061 Pred = NewPred;
11062 RHS = getConstant(NewRHS);
11063 Changed = SimplifiedByConstantRange = true;
11064 }
11065 }
11066
11067 if (!SimplifiedByConstantRange) {
11068 switch (Pred) {
11069 default:
11070 break;
11071 case ICmpInst::ICMP_EQ:
11072 case ICmpInst::ICMP_NE:
11073 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11074 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11075 Changed = true;
11076 break;
11077
11078 // The "Should have been caught earlier!" messages refer to the fact
11079 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11080 // should have fired on the corresponding cases, and canonicalized the
11081 // check to trivial case.
11082
11083 case ICmpInst::ICMP_UGE:
11084 assert(!RA.isMinValue() && "Should have been caught earlier!");
11085 Pred = ICmpInst::ICMP_UGT;
11086 RHS = getConstant(RA - 1);
11087 Changed = true;
11088 break;
11089 case ICmpInst::ICMP_ULE:
11090 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11091 Pred = ICmpInst::ICMP_ULT;
11092 RHS = getConstant(RA + 1);
11093 Changed = true;
11094 break;
11095 case ICmpInst::ICMP_SGE:
11096 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11097 Pred = ICmpInst::ICMP_SGT;
11098 RHS = getConstant(RA - 1);
11099 Changed = true;
11100 break;
11101 case ICmpInst::ICMP_SLE:
11102 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11103 Pred = ICmpInst::ICMP_SLT;
11104 RHS = getConstant(RA + 1);
11105 Changed = true;
11106 break;
11107 }
11108 }
11109 }
11110
11111 // a /u b == 0 => a < b
11112 // a /u b != 0 => a >= b
11113 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11114 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11116 Changed = true;
11117 }
11118
11119 // Check for obvious equality.
11120 if (HasSameValue(LHS, RHS)) {
11121 if (ICmpInst::isTrueWhenEqual(Pred))
11122 return TrivialCase(true);
11124 return TrivialCase(false);
11125 }
11126
11127 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11128 // adding or subtracting 1 from one of the operands.
11129 switch (Pred) {
11130 case ICmpInst::ICMP_SLE:
11131 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11132 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11134 Pred = ICmpInst::ICMP_SLT;
11135 Changed = true;
11136 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11137 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11139 Pred = ICmpInst::ICMP_SLT;
11140 Changed = true;
11141 }
11142 break;
11143 case ICmpInst::ICMP_SGE:
11144 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11145 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11147 Pred = ICmpInst::ICMP_SGT;
11148 Changed = true;
11149 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11150 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11152 Pred = ICmpInst::ICMP_SGT;
11153 Changed = true;
11154 }
11155 break;
11156 case ICmpInst::ICMP_ULE:
11157 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11158 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11160 Pred = ICmpInst::ICMP_ULT;
11161 Changed = true;
11162 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11163 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11164 Pred = ICmpInst::ICMP_ULT;
11165 Changed = true;
11166 }
11167 break;
11168 case ICmpInst::ICMP_UGE:
11169 // If RHS is an op we can fold the -1, try that first.
11170 // Otherwise prefer LHS to preserve the nuw flag.
11171 if ((isa<SCEVConstant>(RHS) ||
11173 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11174 !getUnsignedRangeMin(RHS).isMinValue()) {
11175 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11176 Pred = ICmpInst::ICMP_UGT;
11177 Changed = true;
11178 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11179 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11181 Pred = ICmpInst::ICMP_UGT;
11182 Changed = true;
11183 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11184 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11185 Pred = ICmpInst::ICMP_UGT;
11186 Changed = true;
11187 }
11188 break;
11189 default:
11190 break;
11191 }
11192
11193 // TODO: More simplifications are possible here.
11194
11195 // Recursively simplify until we either hit a recursion limit or nothing
11196 // changes.
11197 if (Changed)
11198 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11199
11200 return Changed;
11201}
11202
11204 return getSignedRangeMax(S).isNegative();
11205}
11206
11210
11212 return !getSignedRangeMin(S).isNegative();
11213}
11214
11218
11220 // Query push down for cases where the unsigned range is
11221 // less than sufficient.
11222 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11223 return isKnownNonZero(SExt->getOperand(0));
11224 return getUnsignedRangeMin(S) != 0;
11225}
11226
11228 bool OrNegative) {
11229 auto NonRecursive = [OrNegative](const SCEV *S) {
11230 if (auto *C = dyn_cast<SCEVConstant>(S))
11231 return C->getAPInt().isPowerOf2() ||
11232 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11233
11234 // vscale is a power-of-two.
11235 return isa<SCEVVScale>(S);
11236 };
11237
11238 if (NonRecursive(S))
11239 return true;
11240
11241 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11242 if (!Mul)
11243 return false;
11244 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11245}
11246
11248 const SCEV *S, uint64_t M,
11250 if (M == 0)
11251 return false;
11252 if (M == 1)
11253 return true;
11254
11255 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11256 // starts with a multiple of M and at every iteration step S only adds
11257 // multiples of M.
11258 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11259 return isKnownMultipleOf(AddRec->getStart(), M, Predicates) &&
11260 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Predicates);
11261
11262 // For a constant, check that "S % M == 0".
11263 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11264 APInt C = Cst->getAPInt();
11265 return C.urem(M) == 0;
11266 }
11267
11268 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11269
11270 // Basic tests have failed.
11271 // Check "S % M == 0" at compile time and record runtime Assumptions.
11272 auto *STy = dyn_cast<IntegerType>(S->getType());
11273 const SCEV *SmodM =
11274 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11275 const SCEV *Zero = getZero(STy);
11276
11277 // Check whether "S % M == 0" is known at compile time.
11278 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11279 return true;
11280
11281 // Check whether "S % M != 0" is known at compile time.
11282 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11283 return false;
11284
11285 if (!Predicates)
11286 return false;
11287
11289
11290 // Detect redundant predicates.
11291 for (auto *A : *Predicates)
11292 if (A->implies(P, *this))
11293 return true;
11294
11295 // Only record non-redundant predicates.
11296 Predicates->push_back(P);
11297 return true;
11298}
11299
11301 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11303}
11304
11305std::pair<const SCEV *, const SCEV *>
11307 // Compute SCEV on entry of loop L.
11308 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11309 if (Start == getCouldNotCompute())
11310 return { Start, Start };
11311 // Compute post increment SCEV for loop L.
11312 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11313 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11314 return { Start, PostInc };
11315}
11316
11318 SCEVUse RHS) {
11319 // First collect all loops.
11321 getUsedLoops(LHS, LoopsUsed);
11322 getUsedLoops(RHS, LoopsUsed);
11323
11324 if (LoopsUsed.empty())
11325 return false;
11326
11327 // Domination relationship must be a linear order on collected loops.
11328#ifndef NDEBUG
11329 for (const auto *L1 : LoopsUsed)
11330 for (const auto *L2 : LoopsUsed)
11331 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11332 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11333 "Domination relationship is not a linear order");
11334#endif
11335
11336 const Loop *MDL =
11337 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11338 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11339 });
11340
11341 // Get init and post increment value for LHS.
11342 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11343 // if LHS contains unknown non-invariant SCEV then bail out.
11344 if (SplitLHS.first == getCouldNotCompute())
11345 return false;
11346 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11347 // Get init and post increment value for RHS.
11348 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11349 // if RHS contains unknown non-invariant SCEV then bail out.
11350 if (SplitRHS.first == getCouldNotCompute())
11351 return false;
11352 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11353 // It is possible that init SCEV contains an invariant load but it does
11354 // not dominate MDL and is not available at MDL loop entry, so we should
11355 // check it here.
11356 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11357 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11358 return false;
11359
11360 // It seems backedge guard check is faster than entry one so in some cases
11361 // it can speed up whole estimation by short circuit
11362 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11363 SplitRHS.second) &&
11364 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11365}
11366
11368 SCEVUse RHS) {
11369 // Canonicalize the inputs first.
11370 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11371
11372 return isKnownViaInduction(Pred, LHS, RHS) ||
11373 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11374 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11375}
11376
11378 const SCEV *LHS,
11379 const SCEV *RHS) {
11380 if (isKnownPredicate(Pred, LHS, RHS))
11381 return true;
11383 return false;
11384 return std::nullopt;
11385}
11386
11388 const SCEV *RHS,
11389 const Instruction *CtxI) {
11390 // TODO: Analyze guards and assumes from Context's block.
11391 return isKnownPredicate(Pred, LHS, RHS) ||
11392 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11393}
11394
11395std::optional<bool>
11397 const SCEV *RHS, const Instruction *CtxI) {
11398 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11399 if (KnownWithoutContext)
11400 return KnownWithoutContext;
11401
11402 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11403 return true;
11405 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11406 return false;
11407 return std::nullopt;
11408}
11409
11411 const SCEVAddRecExpr *LHS,
11412 const SCEV *RHS) {
11413 const Loop *L = LHS->getLoop();
11414 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11415 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11416}
11417
11418std::optional<ScalarEvolution::MonotonicPredicateType>
11420 ICmpInst::Predicate Pred) {
11421 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11422
11423#ifndef NDEBUG
11424 // Verify an invariant: inverting the predicate should turn a monotonically
11425 // increasing change to a monotonically decreasing one, and vice versa.
11426 if (Result) {
11427 auto ResultSwapped =
11428 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11429
11430 assert(*ResultSwapped != *Result &&
11431 "monotonicity should flip as we flip the predicate");
11432 }
11433#endif
11434
11435 return Result;
11436}
11437
11438std::optional<ScalarEvolution::MonotonicPredicateType>
11439ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11440 ICmpInst::Predicate Pred) {
11441 // A zero step value for LHS means the induction variable is essentially a
11442 // loop invariant value. We don't really depend on the predicate actually
11443 // flipping from false to true (for increasing predicates, and the other way
11444 // around for decreasing predicates), all we care about is that *if* the
11445 // predicate changes then it only changes from false to true.
11446 //
11447 // A zero step value in itself is not very useful, but there may be places
11448 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11449 // as general as possible.
11450
11451 // Only handle LE/LT/GE/GT predicates.
11452 if (!ICmpInst::isRelational(Pred))
11453 return std::nullopt;
11454
11455 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11456 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11457 "Should be greater or less!");
11458
11459 // Check that AR does not wrap.
11460 if (ICmpInst::isUnsigned(Pred)) {
11461 if (!LHS->hasNoUnsignedWrap())
11462 return std::nullopt;
11464 }
11465 assert(ICmpInst::isSigned(Pred) &&
11466 "Relational predicate is either signed or unsigned!");
11467 if (!LHS->hasNoSignedWrap())
11468 return std::nullopt;
11469
11470 const SCEV *Step = LHS->getStepRecurrence(*this);
11471
11472 if (isKnownNonNegative(Step))
11474
11475 if (isKnownNonPositive(Step))
11477
11478 return std::nullopt;
11479}
11480
11481std::optional<ScalarEvolution::LoopInvariantPredicate>
11483 const SCEV *RHS, const Loop *L,
11484 const Instruction *CtxI) {
11485 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11486 if (!isLoopInvariant(RHS, L)) {
11487 if (!isLoopInvariant(LHS, L))
11488 return std::nullopt;
11489
11490 std::swap(LHS, RHS);
11492 }
11493
11494 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11495 if (!ArLHS || ArLHS->getLoop() != L)
11496 return std::nullopt;
11497
11498 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11499 if (!MonotonicType)
11500 return std::nullopt;
11501 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11502 // true as the loop iterates, and the backedge is control dependent on
11503 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11504 //
11505 // * if the predicate was false in the first iteration then the predicate
11506 // is never evaluated again, since the loop exits without taking the
11507 // backedge.
11508 // * if the predicate was true in the first iteration then it will
11509 // continue to be true for all future iterations since it is
11510 // monotonically increasing.
11511 //
11512 // For both the above possibilities, we can replace the loop varying
11513 // predicate with its value on the first iteration of the loop (which is
11514 // loop invariant).
11515 //
11516 // A similar reasoning applies for a monotonically decreasing predicate, by
11517 // replacing true with false and false with true in the above two bullets.
11519 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11520
11521 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11523 RHS);
11524
11525 if (!CtxI)
11526 return std::nullopt;
11527 // Try to prove via context.
11528 // TODO: Support other cases.
11529 switch (Pred) {
11530 default:
11531 break;
11532 case ICmpInst::ICMP_ULE:
11533 case ICmpInst::ICMP_ULT: {
11534 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11535 // Given preconditions
11536 // (1) ArLHS does not cross the border of positive and negative parts of
11537 // range because of:
11538 // - Positive step; (TODO: lift this limitation)
11539 // - nuw - does not cross zero boundary;
11540 // - nsw - does not cross SINT_MAX boundary;
11541 // (2) ArLHS <s RHS
11542 // (3) RHS >=s 0
11543 // we can replace the loop variant ArLHS <u RHS condition with loop
11544 // invariant Start(ArLHS) <u RHS.
11545 //
11546 // Because of (1) there are two options:
11547 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11548 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11549 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11550 // Because of (2) ArLHS <u RHS is trivially true.
11551 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11552 // We can strengthen this to Start(ArLHS) <u RHS.
11553 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11554 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11555 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11556 isKnownNonNegative(RHS) &&
11557 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11559 RHS);
11560 }
11561 }
11562
11563 return std::nullopt;
11564}
11565
11566std::optional<ScalarEvolution::LoopInvariantPredicate>
11568 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11569 const Instruction *CtxI, const SCEV *MaxIter) {
11571 Pred, LHS, RHS, L, CtxI, MaxIter))
11572 return LIP;
11573 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11574 // Number of iterations expressed as UMIN isn't always great for expressing
11575 // the value on the last iteration. If the straightforward approach didn't
11576 // work, try the following trick: if the a predicate is invariant for X, it
11577 // is also invariant for umin(X, ...). So try to find something that works
11578 // among subexpressions of MaxIter expressed as umin.
11579 for (SCEVUse Op : UMin->operands())
11581 Pred, LHS, RHS, L, CtxI, Op))
11582 return LIP;
11583 return std::nullopt;
11584}
11585
11586std::optional<ScalarEvolution::LoopInvariantPredicate>
11588 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11589 const Instruction *CtxI, const SCEV *MaxIter) {
11590 // Try to prove the following set of facts:
11591 // - The predicate is monotonic in the iteration space.
11592 // - If the check does not fail on the 1st iteration:
11593 // - No overflow will happen during first MaxIter iterations;
11594 // - It will not fail on the MaxIter'th iteration.
11595 // If the check does fail on the 1st iteration, we leave the loop and no
11596 // other checks matter.
11597
11598 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11599 if (!isLoopInvariant(RHS, L)) {
11600 if (!isLoopInvariant(LHS, L))
11601 return std::nullopt;
11602
11603 std::swap(LHS, RHS);
11605 }
11606
11607 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11608 if (!AR || AR->getLoop() != L)
11609 return std::nullopt;
11610
11611 // Even if both are valid, we need to consistently chose the unsigned or the
11612 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11613 // predicate.
11614 Pred = Pred.dropSameSign();
11615
11616 // The predicate must be relational (i.e. <, <=, >=, >).
11617 if (!ICmpInst::isRelational(Pred))
11618 return std::nullopt;
11619
11620 // TODO: Support steps other than +/- 1.
11621 const SCEV *Step = AR->getStepRecurrence(*this);
11622 auto *One = getOne(Step->getType());
11623 auto *MinusOne = getNegativeSCEV(One);
11624 if (Step != One && Step != MinusOne)
11625 return std::nullopt;
11626
11627 // Type mismatch here means that MaxIter is potentially larger than max
11628 // unsigned value in start type, which mean we cannot prove no wrap for the
11629 // indvar.
11630 if (AR->getType() != MaxIter->getType())
11631 return std::nullopt;
11632
11633 // Value of IV on suggested last iteration.
11634 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11635 // Does it still meet the requirement?
11636 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11637 return std::nullopt;
11638 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11639 // not exceed max unsigned value of this type), this effectively proves
11640 // that there is no wrap during the iteration. To prove that there is no
11641 // signed/unsigned wrap, we need to check that
11642 // Start <= Last for step = 1 or Start >= Last for step = -1.
11643 ICmpInst::Predicate NoOverflowPred =
11645 if (Step == MinusOne)
11646 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11647 const SCEV *Start = AR->getStart();
11648 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11649 return std::nullopt;
11650
11651 // Everything is fine.
11652 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11653}
11654
11655bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11656 SCEVUse LHS,
11657 SCEVUse RHS) {
11658 if (HasSameValue(LHS, RHS))
11659 return ICmpInst::isTrueWhenEqual(Pred);
11660
11661 auto CheckRange = [&](bool IsSigned) {
11662 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11663 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11664 return RangeLHS.icmp(Pred, RangeRHS);
11665 };
11666
11667 // The check at the top of the function catches the case where the values are
11668 // known to be equal.
11669 if (Pred == CmpInst::ICMP_EQ)
11670 return false;
11671
11672 if (Pred == CmpInst::ICMP_NE) {
11673 if (CheckRange(true) || CheckRange(false))
11674 return true;
11675 auto *Diff = getMinusSCEV(LHS, RHS);
11676 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11677 }
11678
11679 return CheckRange(CmpInst::isSigned(Pred));
11680}
11681
11682bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11684 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11685 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11686 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11687 // OutC1 and OutC2.
11688 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11689 APInt &OutC2,
11690 SCEV::NoWrapFlags ExpectedFlags) {
11691 SCEVUse XNonConstOp, XConstOp;
11692 SCEVUse YNonConstOp, YConstOp;
11693 SCEV::NoWrapFlags XFlagsPresent;
11694 SCEV::NoWrapFlags YFlagsPresent;
11695
11696 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11697 XConstOp = getZero(X->getType());
11698 XNonConstOp = X;
11699 XFlagsPresent = ExpectedFlags;
11700 }
11701 if (!isa<SCEVConstant>(XConstOp))
11702 return false;
11703
11704 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11705 YConstOp = getZero(Y->getType());
11706 YNonConstOp = Y;
11707 YFlagsPresent = ExpectedFlags;
11708 }
11709
11710 if (YNonConstOp != XNonConstOp)
11711 return false;
11712
11713 if (!isa<SCEVConstant>(YConstOp))
11714 return false;
11715
11716 // When matching ADDs with NUW flags (and unsigned predicates), only the
11717 // second ADD (with the larger constant) requires NUW.
11718 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11719 return false;
11720 if (ExpectedFlags != SCEV::FlagNUW &&
11721 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11722 return false;
11723 }
11724
11725 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11726 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11727
11728 return true;
11729 };
11730
11731 APInt C1;
11732 APInt C2;
11733
11734 switch (Pred) {
11735 default:
11736 break;
11737
11738 case ICmpInst::ICMP_SGE:
11739 std::swap(LHS, RHS);
11740 [[fallthrough]];
11741 case ICmpInst::ICMP_SLE:
11742 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11743 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11744 return true;
11745
11746 break;
11747
11748 case ICmpInst::ICMP_SGT:
11749 std::swap(LHS, RHS);
11750 [[fallthrough]];
11751 case ICmpInst::ICMP_SLT:
11752 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11753 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11754 return true;
11755
11756 break;
11757
11758 case ICmpInst::ICMP_UGE:
11759 std::swap(LHS, RHS);
11760 [[fallthrough]];
11761 case ICmpInst::ICMP_ULE:
11762 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11763 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11764 return true;
11765
11766 break;
11767
11768 case ICmpInst::ICMP_UGT:
11769 std::swap(LHS, RHS);
11770 [[fallthrough]];
11771 case ICmpInst::ICMP_ULT:
11772 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11773 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11774 return true;
11775 break;
11776 }
11777
11778 return false;
11779}
11780
11781bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11783 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11784 return false;
11785
11786 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11787 // the stack can result in exponential time complexity.
11788 SaveAndRestore Restore(ProvingSplitPredicate, true);
11789
11790 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11791 //
11792 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11793 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11794 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11795 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11796 // use isKnownPredicate later if needed.
11797 return isKnownNonNegative(RHS) &&
11800}
11801
11802bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11803 const SCEV *LHS, const SCEV *RHS) {
11804 // No need to even try if we know the module has no guards.
11805 if (!HasGuards)
11806 return false;
11807
11808 return any_of(*BB, [&](const Instruction &I) {
11809 using namespace llvm::PatternMatch;
11810
11811 Value *Condition;
11813 m_Value(Condition))) &&
11814 isImpliedCond(Pred, LHS, RHS, Condition, false);
11815 });
11816}
11817
11818/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11819/// protected by a conditional between LHS and RHS. This is used to
11820/// to eliminate casts.
11822 CmpPredicate Pred,
11823 const SCEV *LHS,
11824 const SCEV *RHS) {
11825 // Interpret a null as meaning no loop, where there is obviously no guard
11826 // (interprocedural conditions notwithstanding). Do not bother about
11827 // unreachable loops.
11828 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11829 return true;
11830
11831 if (VerifyIR)
11832 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11833 "This cannot be done on broken IR!");
11834
11835
11836 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11837 return true;
11838
11839 BasicBlock *Latch = L->getLoopLatch();
11840 if (!Latch)
11841 return false;
11842
11843 CondBrInst *LoopContinuePredicate =
11845 if (LoopContinuePredicate &&
11846 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11847 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11848 return true;
11849
11850 // We don't want more than one activation of the following loops on the stack
11851 // -- that can lead to O(n!) time complexity.
11852 if (WalkingBEDominatingConds)
11853 return false;
11854
11855 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11856
11857 // See if we can exploit a trip count to prove the predicate.
11858 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11859 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11860 if (LatchBECount != getCouldNotCompute()) {
11861 // We know that Latch branches back to the loop header exactly
11862 // LatchBECount times. This means the backdege condition at Latch is
11863 // equivalent to "{0,+,1} u< LatchBECount".
11864 Type *Ty = LatchBECount->getType();
11865 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11866 const SCEV *LoopCounter =
11867 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11868 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11869 LatchBECount))
11870 return true;
11871 }
11872
11873 // Check conditions due to any @llvm.assume intrinsics.
11874 for (auto &AssumeVH : AC.assumptions()) {
11875 if (!AssumeVH)
11876 continue;
11877 auto *CI = cast<CallInst>(AssumeVH);
11878 if (!DT.dominates(CI, Latch->getTerminator()))
11879 continue;
11880
11881 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11882 return true;
11883 }
11884
11885 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11886 return true;
11887
11888 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11889 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11890 assert(DTN && "should reach the loop header before reaching the root!");
11891
11892 BasicBlock *BB = DTN->getBlock();
11893 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11894 return true;
11895
11896 BasicBlock *PBB = BB->getSinglePredecessor();
11897 if (!PBB)
11898 continue;
11899
11901 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11902 continue;
11903
11904 // If we have an edge `E` within the loop body that dominates the only
11905 // latch, the condition guarding `E` also guards the backedge. This
11906 // reasoning works only for loops with a single latch.
11907 // We're constructively (and conservatively) enumerating edges within the
11908 // loop body that dominate the latch. The dominator tree better agree
11909 // with us on this:
11910 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11911 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11912 BB != ContBr->getSuccessor(0)))
11913 return true;
11914 }
11915
11916 return false;
11917}
11918
11920 CmpPredicate Pred,
11921 const SCEV *LHS,
11922 const SCEV *RHS) {
11923 // Do not bother proving facts for unreachable code.
11924 if (!DT.isReachableFromEntry(BB))
11925 return true;
11926 if (VerifyIR)
11927 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11928 "This cannot be done on broken IR!");
11929
11930 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11931 // the facts (a >= b && a != b) separately. A typical situation is when the
11932 // non-strict comparison is known from ranges and non-equality is known from
11933 // dominating predicates. If we are proving strict comparison, we always try
11934 // to prove non-equality and non-strict comparison separately.
11935 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11936 const bool ProvingStrictComparison =
11937 Pred != NonStrictPredicate.dropSameSign();
11938 bool ProvedNonStrictComparison = false;
11939 bool ProvedNonEquality = false;
11940
11941 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11942 if (!ProvedNonStrictComparison)
11943 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11944 if (!ProvedNonEquality)
11945 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11946 if (ProvedNonStrictComparison && ProvedNonEquality)
11947 return true;
11948 return false;
11949 };
11950
11951 if (ProvingStrictComparison) {
11952 auto ProofFn = [&](CmpPredicate P) {
11953 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11954 };
11955 if (SplitAndProve(ProofFn))
11956 return true;
11957 }
11958
11959 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11960 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11961 const Instruction *CtxI = &BB->front();
11962 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11963 return true;
11964 if (ProvingStrictComparison) {
11965 auto ProofFn = [&](CmpPredicate P) {
11966 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11967 };
11968 if (SplitAndProve(ProofFn))
11969 return true;
11970 }
11971 return false;
11972 };
11973
11974 // Starting at the block's predecessor, climb up the predecessor chain, as long
11975 // as there are predecessors that can be found that have unique successors
11976 // leading to the original block.
11977 const Loop *ContainingLoop = LI.getLoopFor(BB);
11978 const BasicBlock *PredBB;
11979 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11980 PredBB = ContainingLoop->getLoopPredecessor();
11981 else
11982 PredBB = BB->getSinglePredecessor();
11983 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11984 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11985 const CondBrInst *BlockEntryPredicate =
11986 dyn_cast<CondBrInst>(Pair.first->getTerminator());
11987 if (!BlockEntryPredicate)
11988 continue;
11989
11990 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11991 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11992 return true;
11993 }
11994
11995 // Check conditions due to any @llvm.assume intrinsics.
11996 for (auto &AssumeVH : AC.assumptions()) {
11997 if (!AssumeVH)
11998 continue;
11999 auto *CI = cast<CallInst>(AssumeVH);
12000 if (!DT.dominates(CI, BB))
12001 continue;
12002
12003 if (ProveViaCond(CI->getArgOperand(0), false))
12004 return true;
12005 }
12006
12007 // Check conditions due to any @llvm.experimental.guard intrinsics.
12008 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12009 F.getParent(), Intrinsic::experimental_guard);
12010 if (GuardDecl)
12011 for (const auto *GU : GuardDecl->users())
12012 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12013 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12014 if (ProveViaCond(Guard->getArgOperand(0), false))
12015 return true;
12016 return false;
12017}
12018
12020 const SCEV *LHS,
12021 const SCEV *RHS) {
12022 // Interpret a null as meaning no loop, where there is obviously no guard
12023 // (interprocedural conditions notwithstanding).
12024 if (!L)
12025 return false;
12026
12027 // Both LHS and RHS must be available at loop entry.
12029 "LHS is not available at Loop Entry");
12031 "RHS is not available at Loop Entry");
12032
12033 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12034 return true;
12035
12036 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12037}
12038
12039bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12040 const SCEV *RHS,
12041 const Value *FoundCondValue, bool Inverse,
12042 const Instruction *CtxI) {
12043 // False conditions implies anything. Do not bother analyzing it further.
12044 if (FoundCondValue ==
12045 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12046 return true;
12047
12048 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12049 return false;
12050
12051 llvm::scope_exit ClearOnExit(
12052 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12053
12054 // Recursively handle And and Or conditions.
12055 const Value *Op0, *Op1;
12056 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12057 if (!Inverse)
12058 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12059 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12060 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12061 if (Inverse)
12062 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12063 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12064 }
12065
12066 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12067 if (!ICI) return false;
12068
12069 // Now that we found a conditional branch that dominates the loop or controls
12070 // the loop latch. Check to see if it is the comparison we are looking for.
12071 CmpPredicate FoundPred;
12072 if (Inverse)
12073 FoundPred = ICI->getInverseCmpPredicate();
12074 else
12075 FoundPred = ICI->getCmpPredicate();
12076
12077 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12078 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12079
12080 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12081}
12082
12083bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12084 const SCEV *RHS, CmpPredicate FoundPred,
12085 const SCEV *FoundLHS, const SCEV *FoundRHS,
12086 const Instruction *CtxI) {
12087 // Balance the types.
12088 if (getTypeSizeInBits(LHS->getType()) <
12089 getTypeSizeInBits(FoundLHS->getType())) {
12090 // For unsigned and equality predicates, try to prove that both found
12091 // operands fit into narrow unsigned range. If so, try to prove facts in
12092 // narrow types.
12093 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12094 !FoundRHS->getType()->isPointerTy()) {
12095 auto *NarrowType = LHS->getType();
12096 auto *WideType = FoundLHS->getType();
12097 auto BitWidth = getTypeSizeInBits(NarrowType);
12098 const SCEV *MaxValue = getZeroExtendExpr(
12100 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12101 MaxValue) &&
12102 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12103 MaxValue)) {
12104 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12105 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12106 // We cannot preserve samesign after truncation.
12107 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12108 TruncFoundLHS, TruncFoundRHS, CtxI))
12109 return true;
12110 }
12111 }
12112
12113 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12114 return false;
12115 if (CmpInst::isSigned(Pred)) {
12116 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12117 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12118 } else {
12119 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12120 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12121 }
12122 } else if (getTypeSizeInBits(LHS->getType()) >
12123 getTypeSizeInBits(FoundLHS->getType())) {
12124 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12125 return false;
12126 if (CmpInst::isSigned(FoundPred)) {
12127 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12128 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12129 } else {
12130 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12131 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12132 }
12133 }
12134 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12135 FoundRHS, CtxI);
12136}
12137
12138bool ScalarEvolution::isImpliedCondBalancedTypes(
12139 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12140 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12142 getTypeSizeInBits(FoundLHS->getType()) &&
12143 "Types should be balanced!");
12144 // Canonicalize the query to match the way instcombine will have
12145 // canonicalized the comparison.
12146 if (SimplifyICmpOperands(Pred, LHS, RHS))
12147 if (LHS == RHS)
12148 return CmpInst::isTrueWhenEqual(Pred);
12149 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12150 if (FoundLHS == FoundRHS)
12151 return CmpInst::isFalseWhenEqual(FoundPred);
12152
12153 // Check to see if we can make the LHS or RHS match.
12154 if (LHS == FoundRHS || RHS == FoundLHS) {
12155 if (isa<SCEVConstant>(RHS)) {
12156 std::swap(FoundLHS, FoundRHS);
12157 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12158 } else {
12159 std::swap(LHS, RHS);
12161 }
12162 }
12163
12164 // Check whether the found predicate is the same as the desired predicate.
12165 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12166 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12167
12168 // Check whether swapping the found predicate makes it the same as the
12169 // desired predicate.
12170 if (auto P = CmpPredicate::getMatching(
12171 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12172 // We can write the implication
12173 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12174 // using one of the following ways:
12175 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12176 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12177 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12178 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12179 // Forms 1. and 2. require swapping the operands of one condition. Don't
12180 // do this if it would break canonical constant/addrec ordering.
12182 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12183 LHS, FoundLHS, FoundRHS, CtxI);
12184 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12185 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12186
12187 // There's no clear preference between forms 3. and 4., try both. Avoid
12188 // forming getNotSCEV of pointer values as the resulting subtract is
12189 // not legal.
12190 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12191 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12192 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12193 FoundRHS, CtxI))
12194 return true;
12195
12196 if (!FoundLHS->getType()->isPointerTy() &&
12197 !FoundRHS->getType()->isPointerTy() &&
12198 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12199 getNotSCEV(FoundRHS), CtxI))
12200 return true;
12201
12202 return false;
12203 }
12204
12205 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12207 assert(P1 != P2 && "Handled earlier!");
12208 return CmpInst::isRelational(P2) &&
12210 };
12211 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12212 // Unsigned comparison is the same as signed comparison when both the
12213 // operands are non-negative or negative.
12214 if (haveSameSign(FoundLHS, FoundRHS))
12215 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12216 // Create local copies that we can freely swap and canonicalize our
12217 // conditions to "le/lt".
12218 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12219 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12220 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12221 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12222 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12223 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12224 std::swap(CanonicalLHS, CanonicalRHS);
12225 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12226 }
12227 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12228 "Must be!");
12229 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12230 ICmpInst::isLE(CanonicalFoundPred)) &&
12231 "Must be!");
12232 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12233 // Use implication:
12234 // x <u y && y >=s 0 --> x <s y.
12235 // If we can prove the left part, the right part is also proven.
12236 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12237 CanonicalRHS, CanonicalFoundLHS,
12238 CanonicalFoundRHS);
12239 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12240 // Use implication:
12241 // x <s y && y <s 0 --> x <u y.
12242 // If we can prove the left part, the right part is also proven.
12243 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12244 CanonicalRHS, CanonicalFoundLHS,
12245 CanonicalFoundRHS);
12246 }
12247
12248 // Check if we can make progress by sharpening ranges.
12249 if (FoundPred == ICmpInst::ICMP_NE &&
12250 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12251
12252 const SCEVConstant *C = nullptr;
12253 const SCEV *V = nullptr;
12254
12255 if (isa<SCEVConstant>(FoundLHS)) {
12256 C = cast<SCEVConstant>(FoundLHS);
12257 V = FoundRHS;
12258 } else {
12259 C = cast<SCEVConstant>(FoundRHS);
12260 V = FoundLHS;
12261 }
12262
12263 // The guarding predicate tells us that C != V. If the known range
12264 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12265 // range we consider has to correspond to same signedness as the
12266 // predicate we're interested in folding.
12267
12268 APInt Min = ICmpInst::isSigned(Pred) ?
12270
12271 if (Min == C->getAPInt()) {
12272 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12273 // This is true even if (Min + 1) wraps around -- in case of
12274 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12275
12276 APInt SharperMin = Min + 1;
12277
12278 switch (Pred) {
12279 case ICmpInst::ICMP_SGE:
12280 case ICmpInst::ICMP_UGE:
12281 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12282 // RHS, we're done.
12283 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12284 CtxI))
12285 return true;
12286 [[fallthrough]];
12287
12288 case ICmpInst::ICMP_SGT:
12289 case ICmpInst::ICMP_UGT:
12290 // We know from the range information that (V `Pred` Min ||
12291 // V == Min). We know from the guarding condition that !(V
12292 // == Min). This gives us
12293 //
12294 // V `Pred` Min || V == Min && !(V == Min)
12295 // => V `Pred` Min
12296 //
12297 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12298
12299 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12300 return true;
12301 break;
12302
12303 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12304 case ICmpInst::ICMP_SLE:
12305 case ICmpInst::ICMP_ULE:
12306 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12307 LHS, V, getConstant(SharperMin), CtxI))
12308 return true;
12309 [[fallthrough]];
12310
12311 case ICmpInst::ICMP_SLT:
12312 case ICmpInst::ICMP_ULT:
12313 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12314 LHS, V, getConstant(Min), CtxI))
12315 return true;
12316 break;
12317
12318 default:
12319 // No change
12320 break;
12321 }
12322 }
12323 }
12324
12325 // Check whether the actual condition is beyond sufficient.
12326 if (FoundPred == ICmpInst::ICMP_EQ)
12327 if (ICmpInst::isTrueWhenEqual(Pred))
12328 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12329 return true;
12330 if (Pred == ICmpInst::ICMP_NE)
12331 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12332 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12333 return true;
12334
12335 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12336 return true;
12337
12338 // Otherwise assume the worst.
12339 return false;
12340}
12341
12342bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12343 SCEV::NoWrapFlags &Flags) {
12344 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12345 return false;
12346
12347 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12348 return true;
12349}
12350
12351std::optional<APInt>
12353 // We avoid subtracting expressions here because this function is usually
12354 // fairly deep in the call stack (i.e. is called many times).
12355
12356 unsigned BW = getTypeSizeInBits(More->getType());
12357 APInt Diff(BW, 0);
12358 APInt DiffMul(BW, 1);
12359 // Try various simplifications to reduce the difference to a constant. Limit
12360 // the number of allowed simplifications to keep compile-time low.
12361 for (unsigned I = 0; I < 8; ++I) {
12362 if (More == Less)
12363 return Diff;
12364
12365 // Reduce addrecs with identical steps to their start value.
12367 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12368 const auto *MAR = cast<SCEVAddRecExpr>(More);
12369
12370 if (LAR->getLoop() != MAR->getLoop())
12371 return std::nullopt;
12372
12373 // We look at affine expressions only; not for correctness but to keep
12374 // getStepRecurrence cheap.
12375 if (!LAR->isAffine() || !MAR->isAffine())
12376 return std::nullopt;
12377
12378 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12379 return std::nullopt;
12380
12381 Less = LAR->getStart();
12382 More = MAR->getStart();
12383 continue;
12384 }
12385
12386 // Try to match a common constant multiply.
12387 auto MatchConstMul =
12388 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12389 const APInt *C;
12390 const SCEV *Op;
12391 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12392 return {{Op, *C}};
12393 return std::nullopt;
12394 };
12395 if (auto MatchedMore = MatchConstMul(More)) {
12396 if (auto MatchedLess = MatchConstMul(Less)) {
12397 if (MatchedMore->second == MatchedLess->second) {
12398 More = MatchedMore->first;
12399 Less = MatchedLess->first;
12400 DiffMul *= MatchedMore->second;
12401 continue;
12402 }
12403 }
12404 }
12405
12406 // Try to cancel out common factors in two add expressions.
12408 auto Add = [&](const SCEV *S, int Mul) {
12409 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12410 if (Mul == 1) {
12411 Diff += C->getAPInt() * DiffMul;
12412 } else {
12413 assert(Mul == -1);
12414 Diff -= C->getAPInt() * DiffMul;
12415 }
12416 } else
12417 Multiplicity[S] += Mul;
12418 };
12419 auto Decompose = [&](const SCEV *S, int Mul) {
12420 if (isa<SCEVAddExpr>(S)) {
12421 for (const SCEV *Op : S->operands())
12422 Add(Op, Mul);
12423 } else
12424 Add(S, Mul);
12425 };
12426 Decompose(More, 1);
12427 Decompose(Less, -1);
12428
12429 // Check whether all the non-constants cancel out, or reduce to new
12430 // More/Less values.
12431 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12432 for (const auto &[S, Mul] : Multiplicity) {
12433 if (Mul == 0)
12434 continue;
12435 if (Mul == 1) {
12436 if (NewMore)
12437 return std::nullopt;
12438 NewMore = S;
12439 } else if (Mul == -1) {
12440 if (NewLess)
12441 return std::nullopt;
12442 NewLess = S;
12443 } else
12444 return std::nullopt;
12445 }
12446
12447 // Values stayed the same, no point in trying further.
12448 if (NewMore == More || NewLess == Less)
12449 return std::nullopt;
12450
12451 More = NewMore;
12452 Less = NewLess;
12453
12454 // Reduced to constant.
12455 if (!More && !Less)
12456 return Diff;
12457
12458 // Left with variable on only one side, bail out.
12459 if (!More || !Less)
12460 return std::nullopt;
12461 }
12462
12463 // Did not reduce to constant.
12464 return std::nullopt;
12465}
12466
12467bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12468 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12469 const SCEV *FoundRHS, const Instruction *CtxI) {
12470 // Try to recognize the following pattern:
12471 //
12472 // FoundRHS = ...
12473 // ...
12474 // loop:
12475 // FoundLHS = {Start,+,W}
12476 // context_bb: // Basic block from the same loop
12477 // known(Pred, FoundLHS, FoundRHS)
12478 //
12479 // If some predicate is known in the context of a loop, it is also known on
12480 // each iteration of this loop, including the first iteration. Therefore, in
12481 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12482 // prove the original pred using this fact.
12483 if (!CtxI)
12484 return false;
12485 const BasicBlock *ContextBB = CtxI->getParent();
12486 // Make sure AR varies in the context block.
12487 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12488 const Loop *L = AR->getLoop();
12489 const auto *Latch = L->getLoopLatch();
12490 // Make sure that context belongs to the loop and executes on 1st iteration
12491 // (if it ever executes at all).
12492 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12493 return false;
12494 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12495 return false;
12496 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12497 }
12498
12499 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12500 const Loop *L = AR->getLoop();
12501 const auto *Latch = L->getLoopLatch();
12502 // Make sure that context belongs to the loop and executes on 1st iteration
12503 // (if it ever executes at all).
12504 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12505 return false;
12506 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12507 return false;
12508 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12509 }
12510
12511 return false;
12512}
12513
12514bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12515 const SCEV *LHS,
12516 const SCEV *RHS,
12517 const SCEV *FoundLHS,
12518 const SCEV *FoundRHS) {
12519 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12520 return false;
12521
12522 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12523 if (!AddRecLHS)
12524 return false;
12525
12526 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12527 if (!AddRecFoundLHS)
12528 return false;
12529
12530 // We'd like to let SCEV reason about control dependencies, so we constrain
12531 // both the inequalities to be about add recurrences on the same loop. This
12532 // way we can use isLoopEntryGuardedByCond later.
12533
12534 const Loop *L = AddRecFoundLHS->getLoop();
12535 if (L != AddRecLHS->getLoop())
12536 return false;
12537
12538 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12539 //
12540 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12541 // ... (2)
12542 //
12543 // Informal proof for (2), assuming (1) [*]:
12544 //
12545 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12546 //
12547 // Then
12548 //
12549 // FoundLHS s< FoundRHS s< INT_MIN - C
12550 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12551 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12552 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12553 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12554 // <=> FoundLHS + C s< FoundRHS + C
12555 //
12556 // [*]: (1) can be proved by ruling out overflow.
12557 //
12558 // [**]: This can be proved by analyzing all the four possibilities:
12559 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12560 // (A s>= 0, B s>= 0).
12561 //
12562 // Note:
12563 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12564 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12565 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12566 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12567 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12568 // C)".
12569
12570 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12571 if (!LDiff)
12572 return false;
12573 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12574 if (!RDiff || *LDiff != *RDiff)
12575 return false;
12576
12577 if (LDiff->isMinValue())
12578 return true;
12579
12580 APInt FoundRHSLimit;
12581
12582 if (Pred == CmpInst::ICMP_ULT) {
12583 FoundRHSLimit = -(*RDiff);
12584 } else {
12585 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12586 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12587 }
12588
12589 // Try to prove (1) or (2), as needed.
12590 return isAvailableAtLoopEntry(FoundRHS, L) &&
12591 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12592 getConstant(FoundRHSLimit));
12593}
12594
12595bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12596 const SCEV *RHS, const SCEV *FoundLHS,
12597 const SCEV *FoundRHS, unsigned Depth) {
12598 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12599
12600 llvm::scope_exit ClearOnExit([&]() {
12601 if (LPhi) {
12602 bool Erased = PendingMerges.erase(LPhi);
12603 assert(Erased && "Failed to erase LPhi!");
12604 (void)Erased;
12605 }
12606 if (RPhi) {
12607 bool Erased = PendingMerges.erase(RPhi);
12608 assert(Erased && "Failed to erase RPhi!");
12609 (void)Erased;
12610 }
12611 });
12612
12613 // Find respective Phis and check that they are not being pending.
12614 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12615 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12616 if (!PendingMerges.insert(Phi).second)
12617 return false;
12618 LPhi = Phi;
12619 }
12620 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12621 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12622 // If we detect a loop of Phi nodes being processed by this method, for
12623 // example:
12624 //
12625 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12626 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12627 //
12628 // we don't want to deal with a case that complex, so return conservative
12629 // answer false.
12630 if (!PendingMerges.insert(Phi).second)
12631 return false;
12632 RPhi = Phi;
12633 }
12634
12635 // If none of LHS, RHS is a Phi, nothing to do here.
12636 if (!LPhi && !RPhi)
12637 return false;
12638
12639 // If there is a SCEVUnknown Phi we are interested in, make it left.
12640 if (!LPhi) {
12641 std::swap(LHS, RHS);
12642 std::swap(FoundLHS, FoundRHS);
12643 std::swap(LPhi, RPhi);
12645 }
12646
12647 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12648 const BasicBlock *LBB = LPhi->getParent();
12649 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12650
12651 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12652 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12653 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12654 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12655 };
12656
12657 if (RPhi && RPhi->getParent() == LBB) {
12658 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12659 // If we compare two Phis from the same block, and for each entry block
12660 // the predicate is true for incoming values from this block, then the
12661 // predicate is also true for the Phis.
12662 for (const BasicBlock *IncBB : predecessors(LBB)) {
12663 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12664 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12665 if (!ProvedEasily(L, R))
12666 return false;
12667 }
12668 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12669 // Case two: RHS is also a Phi from the same basic block, and it is an
12670 // AddRec. It means that there is a loop which has both AddRec and Unknown
12671 // PHIs, for it we can compare incoming values of AddRec from above the loop
12672 // and latch with their respective incoming values of LPhi.
12673 // TODO: Generalize to handle loops with many inputs in a header.
12674 if (LPhi->getNumIncomingValues() != 2) return false;
12675
12676 auto *RLoop = RAR->getLoop();
12677 auto *Predecessor = RLoop->getLoopPredecessor();
12678 assert(Predecessor && "Loop with AddRec with no predecessor?");
12679 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12680 if (!ProvedEasily(L1, RAR->getStart()))
12681 return false;
12682 auto *Latch = RLoop->getLoopLatch();
12683 assert(Latch && "Loop with AddRec with no latch?");
12684 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12685 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12686 return false;
12687 } else {
12688 // In all other cases go over inputs of LHS and compare each of them to RHS,
12689 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12690 // At this point RHS is either a non-Phi, or it is a Phi from some block
12691 // different from LBB.
12692 for (const BasicBlock *IncBB : predecessors(LBB)) {
12693 // Check that RHS is available in this block.
12694 if (!dominates(RHS, IncBB))
12695 return false;
12696 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12697 // Make sure L does not refer to a value from a potentially previous
12698 // iteration of a loop.
12699 if (!properlyDominates(L, LBB))
12700 return false;
12701 // Addrecs are considered to properly dominate their loop, so are missed
12702 // by the previous check. Discard any values that have computable
12703 // evolution in this loop.
12704 if (auto *Loop = LI.getLoopFor(LBB))
12706 return false;
12707 if (!ProvedEasily(L, RHS))
12708 return false;
12709 }
12710 }
12711 return true;
12712}
12713
12714bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12715 const SCEV *LHS,
12716 const SCEV *RHS,
12717 const SCEV *FoundLHS,
12718 const SCEV *FoundRHS) {
12719 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12720 // sure that we are dealing with same LHS.
12721 if (RHS == FoundRHS) {
12722 std::swap(LHS, RHS);
12723 std::swap(FoundLHS, FoundRHS);
12725 }
12726 if (LHS != FoundLHS)
12727 return false;
12728
12729 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12730 if (!SUFoundRHS)
12731 return false;
12732
12733 Value *Shiftee, *ShiftValue;
12734
12735 using namespace PatternMatch;
12736 if (match(SUFoundRHS->getValue(),
12737 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12738 auto *ShifteeS = getSCEV(Shiftee);
12739 // Prove one of the following:
12740 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12741 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12742 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12743 // ---> LHS <s RHS
12744 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12745 // ---> LHS <=s RHS
12746 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12747 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12748 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12749 if (isKnownNonNegative(ShifteeS))
12750 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12751 }
12752
12753 return false;
12754}
12755
12756bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12757 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12758 const SCEV *FoundRHS) {
12759 // Only valid for equality predicates: (A == B) implies (C == D) when
12760 // the SCEV difference A - B equals C - D (they check the same
12761 // underlying relationship at every iteration).
12762 if (!ICmpInst::isEquality(Pred))
12763 return false;
12764
12765 // Restrict to cases involving loop recurrences - that's where this
12766 // pattern arises (correlated IV comparisons). This avoids calling
12767 // getMinusSCEV on arbitrary non-loop expressions.
12769 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12770 return false;
12771
12772 // AddRecs from different loops can never produce matching differences.
12773 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12774 if (!QueryAddRec)
12775 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12776 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12777 if (!FoundAddRec)
12778 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12779 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12780 return false;
12781
12782 // If the strides differ, the differences can never match.
12783 if (QueryAddRec->getStepRecurrence(*this) !=
12784 FoundAddRec->getStepRecurrence(*this))
12785 return false;
12786
12787 // Compute differences. For pointer-typed operands sharing the same base,
12788 // getMinusSCEV strips the common base and returns an integer SCEV.
12789 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12790 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12791 if (isa<SCEVCouldNotCompute>(FoundDiff))
12792 return false;
12793
12794 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12795 if (isa<SCEVCouldNotCompute>(Diff))
12796 return false;
12797
12798 return Diff == FoundDiff;
12799}
12800
12801bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12802 const SCEV *RHS,
12803 const SCEV *FoundLHS,
12804 const SCEV *FoundRHS,
12805 const Instruction *CtxI) {
12806 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12807 FoundRHS) ||
12808 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12809 FoundRHS) ||
12810 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12811 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12812 CtxI) ||
12813 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12814 FoundRHS) ||
12815 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12816}
12817
12818/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12819template <typename MinMaxExprType>
12820static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12821 const SCEV *Candidate) {
12822 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12823 if (!MinMaxExpr)
12824 return false;
12825
12826 return is_contained(MinMaxExpr->operands(), Candidate);
12827}
12828
12830 CmpPredicate Pred, const SCEV *LHS,
12831 const SCEV *RHS) {
12832 // If both sides are affine addrecs for the same loop, with equal
12833 // steps, and we know the recurrences don't wrap, then we only
12834 // need to check the predicate on the starting values.
12835
12836 if (!ICmpInst::isRelational(Pred))
12837 return false;
12838
12839 const SCEV *LStart, *RStart, *Step;
12840 const Loop *L;
12841 if (!match(LHS,
12842 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12844 m_SpecificLoop(L))))
12845 return false;
12850 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12851 return false;
12852
12853 return SE.isKnownPredicate(Pred, LStart, RStart);
12854}
12855
12856/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12857/// go below its own start value?
12859 CmpPredicate Pred,
12860 const SCEV *LHS,
12861 const SCEV *RHS) {
12862 // Normalize to (AddRec Pred Start).
12865 std::swap(LHS, RHS);
12866 }
12867
12868 // The recurrence is equal to Start in the first iteration, so only the
12869 // non-strict predicate holds.
12870 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12871 return false;
12872
12873 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12874 if (!AR || AR->getStart() != RHS)
12875 return false;
12876
12877 return SE.getMonotonicPredicateType(AR, Pred) ==
12879}
12880
12881/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12882/// expression?
12884 const SCEV *LHS, const SCEV *RHS) {
12885 switch (Pred) {
12886 default:
12887 return false;
12888
12889 case ICmpInst::ICMP_SGE:
12890 std::swap(LHS, RHS);
12891 [[fallthrough]];
12892 case ICmpInst::ICMP_SLE:
12893 return
12894 // min(A, ...) <= A
12896 // A <= max(A, ...)
12898
12899 case ICmpInst::ICMP_UGE:
12900 std::swap(LHS, RHS);
12901 [[fallthrough]];
12902 case ICmpInst::ICMP_ULE:
12903 return
12904 // min(A, ...) <= A
12905 // FIXME: what about umin_seq?
12907 // A <= max(A, ...)
12909
12910 case ICmpInst::ICMP_UGT:
12911 std::swap(LHS, RHS);
12912 [[fallthrough]];
12913 case ICmpInst::ICMP_ULT:
12914 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12915 // umin(Ops) u< RHS.
12916 //
12917 // Use computeConstantDifference instead of the more powerful
12918 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12919 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12920 // the full predicate prover would be expensive.
12921 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12922 for (SCEVUse Op : Min->operands()) {
12923 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12924 // When Op and RHS share a common base differing by a
12925 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12926 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12927 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12928 return true;
12929 }
12930 }
12931 return false;
12932 }
12933
12934 llvm_unreachable("covered switch fell through?!");
12935}
12936
12937bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12938 const SCEV *RHS,
12939 const SCEV *FoundLHS,
12940 const SCEV *FoundRHS,
12941 unsigned Depth) {
12944 "LHS and RHS have different sizes?");
12945 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12946 getTypeSizeInBits(FoundRHS->getType()) &&
12947 "FoundLHS and FoundRHS have different sizes?");
12948 // We want to avoid hurting the compile time with analysis of too big trees.
12950 return false;
12951
12952 // We only want to work with GT comparison so far.
12953 if (ICmpInst::isLT(Pred)) {
12955 std::swap(LHS, RHS);
12956 std::swap(FoundLHS, FoundRHS);
12957 }
12958
12960
12961 // For unsigned, try to reduce it to corresponding signed comparison.
12962 if (P == ICmpInst::ICMP_UGT)
12963 // We can replace unsigned predicate with its signed counterpart if all
12964 // involved values are non-negative.
12965 // TODO: We could have better support for unsigned.
12966 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12967 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12968 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12969 // use this fact to prove that LHS and RHS are non-negative.
12970 const SCEV *MinusOne = getMinusOne(LHS->getType());
12971 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12972 FoundRHS) &&
12973 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12974 FoundRHS))
12976 }
12977
12978 if (P != ICmpInst::ICMP_SGT)
12979 return false;
12980
12981 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
12982 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12983 return Ext->getOperand();
12984 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12985 // the constant in some cases.
12986 return S;
12987 };
12988
12989 // Acquire values from extensions.
12990 auto *OrigLHS = LHS;
12991 auto *OrigFoundLHS = FoundLHS;
12992 LHS = GetOpFromSExt(LHS);
12993 FoundLHS = GetOpFromSExt(FoundLHS);
12994
12995 // Is the SGT predicate can be proved trivially or using the found context.
12996 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12997 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12998 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12999 FoundRHS, Depth + 1);
13000 };
13001
13002 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13003 // We want to avoid creation of any new non-constant SCEV. Since we are
13004 // going to compare the operands to RHS, we should be certain that we don't
13005 // need any size extensions for this. So let's decline all cases when the
13006 // sizes of types of LHS and RHS do not match.
13007 // TODO: Maybe try to get RHS from sext to catch more cases?
13009 return false;
13010
13011 // Should not overflow.
13012 if (!LHSAddExpr->hasNoSignedWrap())
13013 return false;
13014
13015 SCEVUse LL = LHSAddExpr->getOperand(0);
13016 SCEVUse LR = LHSAddExpr->getOperand(1);
13017 auto *MinusOne = getMinusOne(RHS->getType());
13018
13019 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13020 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13021 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13022 };
13023 // Try to prove the following rule:
13024 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13025 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13026 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13027 return true;
13028 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13029 Value *LL, *LR;
13030 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13031
13032 using namespace llvm::PatternMatch;
13033
13034 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13035 // Rules for division.
13036 // We are going to perform some comparisons with Denominator and its
13037 // derivative expressions. In general case, creating a SCEV for it may
13038 // lead to a complex analysis of the entire graph, and in particular it
13039 // can request trip count recalculation for the same loop. This would
13040 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13041 // this, we only want to create SCEVs that are constants in this section.
13042 // So we bail if Denominator is not a constant.
13043 if (!isa<ConstantInt>(LR))
13044 return false;
13045
13046 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13047
13048 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13049 // then a SCEV for the numerator already exists and matches with FoundLHS.
13050 auto *Numerator = getExistingSCEV(LL);
13051 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13052 return false;
13053
13054 // Make sure that the numerator matches with FoundLHS and the denominator
13055 // is positive.
13056 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13057 return false;
13058
13059 auto *DTy = Denominator->getType();
13060 auto *FRHSTy = FoundRHS->getType();
13061 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13062 // One of types is a pointer and another one is not. We cannot extend
13063 // them properly to a wider type, so let us just reject this case.
13064 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13065 // to avoid this check.
13066 return false;
13067
13068 // Given that:
13069 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13070 auto *WTy = getWiderType(DTy, FRHSTy);
13071 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13072 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13073
13074 // Try to prove the following rule:
13075 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13076 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13077 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13078 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13079 if (isKnownNonPositive(RHS) &&
13080 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13081 return true;
13082
13083 // Try to prove the following rule:
13084 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13085 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13086 // If we divide it by Denominator > 2, then:
13087 // 1. If FoundLHS is negative, then the result is 0.
13088 // 2. If FoundLHS is non-negative, then the result is non-negative.
13089 // Anyways, the result is non-negative.
13090 auto *MinusOne = getMinusOne(WTy);
13091 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13092 if (isKnownNegative(RHS) &&
13093 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13094 return true;
13095 }
13096 }
13097
13098 // If our expression contained SCEVUnknown Phis, and we split it down and now
13099 // need to prove something for them, try to prove the predicate for every
13100 // possible incoming values of those Phis.
13101 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13102 return true;
13103
13104 return false;
13105}
13106
13108 const SCEV *RHS) {
13109 // zext x u<= sext x, sext x s<= zext x
13110 const SCEV *Op;
13111 switch (Pred) {
13112 case ICmpInst::ICMP_SGE:
13113 std::swap(LHS, RHS);
13114 [[fallthrough]];
13115 case ICmpInst::ICMP_SLE: {
13116 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13117 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13119 }
13120 case ICmpInst::ICMP_UGE:
13121 std::swap(LHS, RHS);
13122 [[fallthrough]];
13123 case ICmpInst::ICMP_ULE: {
13124 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13125 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13127 }
13128 default:
13129 return false;
13130 };
13131 llvm_unreachable("unhandled case");
13132}
13133
13134bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13135 SCEVUse LHS,
13136 SCEVUse RHS) {
13137 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13138 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13139 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13140 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13142 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13143}
13144
13145bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13146 const SCEV *LHS,
13147 const SCEV *RHS,
13148 const SCEV *FoundLHS,
13149 const SCEV *FoundRHS) {
13150 switch (Pred) {
13151 default:
13152 llvm_unreachable("Unexpected CmpPredicate value!");
13153 case ICmpInst::ICMP_EQ:
13154 case ICmpInst::ICMP_NE:
13155 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13156 return true;
13157 break;
13158 case ICmpInst::ICMP_SLT:
13159 case ICmpInst::ICMP_SLE:
13160 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13161 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13162 return true;
13163 break;
13164 case ICmpInst::ICMP_SGT:
13165 case ICmpInst::ICMP_SGE:
13166 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13167 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13168 return true;
13169 break;
13170 case ICmpInst::ICMP_ULT:
13171 case ICmpInst::ICMP_ULE:
13172 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13173 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13174 return true;
13175 break;
13176 case ICmpInst::ICMP_UGT:
13177 case ICmpInst::ICMP_UGE:
13178 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13179 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13180 return true;
13181 break;
13182 }
13183
13184 // Maybe it can be proved via operations?
13185 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13186 return true;
13187
13188 return false;
13189}
13190
13191bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13192 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13193 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13194 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13195 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13196 // reduce the compile time impact of this optimization.
13197 return false;
13198
13199 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13200 if (!Addend)
13201 return false;
13202
13203 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13204
13205 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13206 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13207 ConstantRange FoundLHSRange =
13208 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13209
13210 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13211 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13212
13213 // We can also compute the range of values for `LHS` that satisfy the
13214 // consequent, "`LHS` `Pred` `RHS`":
13215 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13216 // The antecedent implies the consequent if every value of `LHS` that
13217 // satisfies the antecedent also satisfies the consequent.
13218 return LHSRange.icmp(Pred, ConstRHS);
13219}
13220
13221bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13222 bool IsSigned) {
13223 assert(isKnownPositive(Stride) && "Positive stride expected!");
13224
13225 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13226 const SCEV *One = getOne(Stride->getType());
13227
13228 if (IsSigned) {
13229 APInt MaxRHS = getSignedRangeMax(RHS);
13230 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13231 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13232
13233 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13234 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13235 }
13236
13237 APInt MaxRHS = getUnsignedRangeMax(RHS);
13238 APInt MaxValue = APInt::getMaxValue(BitWidth);
13239 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13240
13241 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13242 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13243}
13244
13245bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13246 bool IsSigned) {
13247
13248 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13249 const SCEV *One = getOne(Stride->getType());
13250
13251 if (IsSigned) {
13252 APInt MinRHS = getSignedRangeMin(RHS);
13253 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13254 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13255
13256 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13257 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13258 }
13259
13260 APInt MinRHS = getUnsignedRangeMin(RHS);
13261 APInt MinValue = APInt::getMinValue(BitWidth);
13262 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13263
13264 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13265 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13266}
13267
13269 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13270 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13271 // expression fixes the case of N=0.
13272 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13273 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13274 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13275}
13276
13277const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13278 const SCEV *Stride,
13279 const SCEV *End,
13280 unsigned BitWidth,
13281 bool IsSigned) {
13282 // The logic in this function assumes we can represent a positive stride.
13283 // If we can't, the backedge-taken count must be zero.
13284 if (IsSigned && BitWidth == 1)
13285 return getZero(Stride->getType());
13286
13287 // This code below only been closely audited for negative strides in the
13288 // unsigned comparison case, it may be correct for signed comparison, but
13289 // that needs to be established.
13290 if (IsSigned && isKnownNegative(Stride))
13291 return getCouldNotCompute();
13292
13293 // Calculate the maximum backedge count based on the range of values
13294 // permitted by Start, End, and Stride.
13295 APInt MinStart =
13296 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13297
13298 APInt MinStride =
13299 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13300
13301 // We assume either the stride is positive, or the backedge-taken count
13302 // is zero. So force StrideForMaxBECount to be at least one.
13303 APInt One(BitWidth, 1);
13304 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13305 : APIntOps::umax(One, MinStride);
13306
13307 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13308 : APInt::getMaxValue(BitWidth);
13309 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13310
13311 // Although End can be a MAX expression we estimate MaxEnd considering only
13312 // the case End = RHS of the loop termination condition. This is safe because
13313 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13314 // taken count.
13315 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13316 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13317
13318 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13319 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13320 : APIntOps::umax(MaxEnd, MinStart);
13321
13322 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13323 getConstant(StrideForMaxBECount) /* Step */);
13324}
13325
13327ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13328 const Loop *L, bool IsSigned,
13329 bool ControlsOnlyExit, bool AllowPredicates) {
13331
13333 bool PredicatedIV = false;
13334 if (!IV) {
13335 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13336 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13337 if (AR && AR->getLoop() == L && AR->isAffine()) {
13338 auto canProveNUW = [&]() {
13339 // We can use the comparison to infer no-wrap flags only if it fully
13340 // controls the loop exit.
13341 if (!ControlsOnlyExit)
13342 return false;
13343
13344 if (!isLoopInvariant(RHS, L))
13345 return false;
13346
13347 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13348 // We need the sequence defined by AR to strictly increase in the
13349 // unsigned integer domain for the logic below to hold.
13350 return false;
13351
13352 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13353 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13354 // If RHS <=u Limit, then there must exist a value V in the sequence
13355 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13356 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13357 // overflow occurs. This limit also implies that a signed comparison
13358 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13359 // the high bits on both sides must be zero.
13360 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13361 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13362 Limit = Limit.zext(OuterBitWidth);
13363 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13364 };
13365 auto Flags = AR->getNoWrapFlags();
13366 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13367 Flags = setFlags(Flags, SCEV::FlagNUW);
13368
13369 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13370 if (AR->hasNoUnsignedWrap()) {
13371 // Emulate what getZeroExtendExpr would have done during construction
13372 // if we'd been able to infer the fact just above at that time.
13373 const SCEV *Step = AR->getStepRecurrence(*this);
13374 Type *Ty = ZExt->getType();
13375 auto *S = getAddRecExpr(
13377 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13379 }
13380 }
13381 }
13382 }
13383
13384
13385 if (!IV && AllowPredicates) {
13386 // Try to make this an AddRec using runtime tests, in the first X
13387 // iterations of this loop, where X is the SCEV expression found by the
13388 // algorithm below.
13389 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13390 PredicatedIV = true;
13391 }
13392
13393 // Avoid weird loops
13394 if (!IV || IV->getLoop() != L || !IV->isAffine())
13395 return getCouldNotCompute();
13396
13397 // A precondition of this method is that the condition being analyzed
13398 // reaches an exiting branch which dominates the latch. Given that, we can
13399 // assume that an increment which violates the nowrap specification and
13400 // produces poison must cause undefined behavior when the resulting poison
13401 // value is branched upon and thus we can conclude that the backedge is
13402 // taken no more often than would be required to produce that poison value.
13403 // Note that a well defined loop can exit on the iteration which violates
13404 // the nowrap specification if there is another exit (either explicit or
13405 // implicit/exceptional) which causes the loop to execute before the
13406 // exiting instruction we're analyzing would trigger UB.
13407 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13408 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13410
13411 const SCEV *Stride = IV->getStepRecurrence(*this);
13412
13413 bool PositiveStride = isKnownPositive(Stride);
13414
13415 // Whether the IV may reach the maximum value before the exit is taken.
13416 bool IVMayOverflow = true;
13417
13418 // Avoid negative or zero stride values.
13419 if (!PositiveStride) {
13420 // We can compute the correct backedge taken count for loops with unknown
13421 // strides if we can prove that the loop is not an infinite loop with side
13422 // effects. Here's the loop structure we are trying to handle -
13423 //
13424 // i = start
13425 // do {
13426 // A[i] = i;
13427 // i += s;
13428 // } while (i < end);
13429 //
13430 // The backedge taken count for such loops is evaluated as -
13431 // (max(end, start + stride) - start - 1) /u stride
13432 //
13433 // The additional preconditions that we need to check to prove correctness
13434 // of the above formula is as follows -
13435 //
13436 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13437 // NoWrap flag).
13438 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13439 // no side effects within the loop)
13440 // c) loop has a single static exit (with no abnormal exits)
13441 //
13442 // Precondition a) implies that if the stride is negative, this is a single
13443 // trip loop. The backedge taken count formula reduces to zero in this case.
13444 //
13445 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13446 // then a zero stride means the backedge can't be taken without executing
13447 // undefined behavior.
13448 //
13449 // The positive stride case is the same as isKnownPositive(Stride) returning
13450 // true (original behavior of the function).
13451 //
13452 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13454 return getCouldNotCompute();
13455
13456 if (!isKnownNonZero(Stride)) {
13457 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13458 // if it might eventually be greater than start and if so, on which
13459 // iteration. We can't even produce a useful upper bound.
13460 if (!isLoopInvariant(RHS, L))
13461 return getCouldNotCompute();
13462
13463 // We allow a potentially zero stride, but we need to divide by stride
13464 // below. Since the loop can't be infinite and this check must control
13465 // the sole exit, we can infer the exit must be taken on the first
13466 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13467 // we know the numerator in the divides below must be zero, so we can
13468 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13469 // and produce the right result.
13470 // FIXME: Handle the case where Stride is poison?
13471 auto wouldZeroStrideBeUB = [&]() {
13472 // Proof by contradiction. Suppose the stride were zero. If we can
13473 // prove that the backedge *is* taken on the first iteration, then since
13474 // we know this condition controls the sole exit, we must have an
13475 // infinite loop. We can't have a (well defined) infinite loop per
13476 // check just above.
13477 // Note: The (Start - Stride) term is used to get the start' term from
13478 // (start' + stride,+,stride). Remember that we only care about the
13479 // result of this expression when stride == 0 at runtime.
13480 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13481 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13482 };
13483 if (!wouldZeroStrideBeUB()) {
13484 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13485 }
13486 }
13487 } else {
13488 // Avoid proven overflow cases: this will ensure that the backedge taken
13489 // count will not generate any unsigned overflow.
13490 IVMayOverflow = canIVOverflowOnLT(RHS, Stride, IsSigned);
13491 if (IVMayOverflow && !NoWrap)
13492 return getCouldNotCompute();
13493 }
13494
13495 // On all paths just preceeding, we established the following invariant:
13496 // IV can be assumed not to overflow up to and including the exiting
13497 // iteration. We proved this in one of two ways:
13498 // 1) We can show overflow doesn't occur before the exiting iteration
13499 // 1a) canIVOverflowOnLT, and b) step of one
13500 // 2) We can show that if overflow occurs, the loop must execute UB
13501 // before any possible exit.
13502 // Note that we have not yet proved RHS invariant (in general).
13503
13504 const SCEV *Start = IV->getStart();
13505
13506 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13507 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13508 // Use integer-typed versions for actual computation; we can't subtract
13509 // pointers in general.
13510 const SCEV *OrigStart = Start;
13511 const SCEV *OrigRHS = RHS;
13512 if (Start->getType()->isPointerTy()) {
13513 Start = getPtrToAddrExpr(Start);
13514 if (isa<SCEVCouldNotCompute>(Start))
13515 return Start;
13516 }
13517 if (RHS->getType()->isPointerTy()) {
13520 return RHS;
13521 }
13522
13523 const SCEV *End = nullptr, *BECount = nullptr,
13524 *BECountIfBackedgeTaken = nullptr;
13525 if (!isLoopInvariant(RHS, L)) {
13526 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13527 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13528 any(RHSAddRec->getNoWrapFlags())) {
13529 // The structure of loop we are trying to calculate backedge count of:
13530 //
13531 // left = left_start
13532 // right = right_start
13533 //
13534 // while(left < right){
13535 // ... do something here ...
13536 // left += s1; // stride of left is s1 (s1 > 0)
13537 // right += s2; // stride of right is s2 (s2 < 0)
13538 // }
13539 //
13540
13541 const SCEV *RHSStart = RHSAddRec->getStart();
13542 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13543
13544 // If Stride - RHSStride is positive and does not overflow, we can write
13545 // backedge count as ->
13546 // ceil((End - Start) /u (Stride - RHSStride))
13547 // Where, End = max(RHSStart, Start)
13548
13549 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13550 if (isKnownNegative(RHSStride) &&
13551 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13552 RHSStride)) {
13553
13554 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13555 if (isKnownPositive(Denominator)) {
13556 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13557 : getUMaxExpr(RHSStart, Start);
13558
13559 // We can do this because End >= Start, as End = max(RHSStart, Start)
13560 const SCEV *Delta = getMinusSCEV(End, Start);
13561
13562 BECount = getUDivCeilSCEV(Delta, Denominator);
13563 BECountIfBackedgeTaken =
13564 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13565 }
13566 }
13567 }
13568 if (BECount == nullptr) {
13569 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13570 // given the start, stride and max value for the end bound of the
13571 // loop (RHS), and the fact that IV does not overflow (which is
13572 // checked above).
13573 const SCEV *MaxBECount = computeMaxBECountForLT(
13574 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13575 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13576 MaxBECount, false /*MaxOrZero*/, Predicates);
13577 }
13578 } else {
13579 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13580 // describe the backedge count: if the backedge is taken at least once then
13581 // End is RHS, and if not End is Start so we get a backedge count of zero.
13582 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13583 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13584 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13585 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13586 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13587 // (via !IVMayOverflow) that RHS + Stride - 1 does not overflow?
13588 if ((!IVMayOverflow ||
13589 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart)) &&
13590 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13591 // In this case, we can use a refined formula for computing backedge
13592 // taken count. The general formula remains:
13593 // "End-Start /uceiling Stride"
13594 // We want to use the alternate formula:
13595 // "((RHS - 1) - (Start - Stride)) /u Stride"
13596 // Let's do a quick case analysis to show these are equivalent under
13597 // our preconditions.
13598 // * For RHS <= Start (End is Start), the backedge-taken count must be
13599 // zero. Together with the precondition "Start - Stride < RHS", we have
13600 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13601 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13602 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13603 // So dividing that by Stride gives zero.
13604 //
13605 // * For RHS > Start (End is RHS), the backedge count must be
13606 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13607 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13608 //
13609 // If "Start - Stride < Start" holds, we have
13610 // "RHS > Start > Start - Stride". As such
13611 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13612 // reassociated numerator.
13613 //
13614 // Otherwise !IVMayOverflow guarantees "RHS + (Stride - 1) <= MaxV",
13615 // where MaxV is the maximum signed/unsigned value. Let MinV be the
13616 // matching minimum value. "Start >= MinV" gives
13617 // "RHS + (Stride - 1) - Start <= MaxV - MinV", and as "MaxV - MinV" is
13618 // the largest unsigned value, the reassociated numerator does not
13619 // overflow.
13620 const SCEV *MinusOne = getMinusOne(Stride->getType());
13621 const SCEV *Numerator =
13622 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13623 BECount = getUDivExpr(Numerator, Stride);
13624 }
13625
13626 if (!BECount) {
13627 auto canProveRHSGreaterThanEqualStart = [&]() {
13628 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13629 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13630 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13631
13632 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13633 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13634 return true;
13635
13636 // (RHS > Start - 1) implies RHS >= Start.
13637 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13638 // "Start - 1" doesn't overflow.
13639 // * For signed comparison, if Start - 1 does overflow, it's equal
13640 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13641 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13642 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13643 //
13644 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13645 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13646 auto *StartMinusOne =
13647 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13648 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13649 };
13650
13651 // If we know that RHS >= Start in the context of loop, then we know
13652 // that max(RHS, Start) = RHS at this point.
13653 if (canProveRHSGreaterThanEqualStart()) {
13654 End = RHS;
13655 } else {
13656 // If RHS < Start, the backedge will be taken zero times. So in
13657 // general, we can write the backedge-taken count as:
13658 //
13659 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13660 //
13661 // We convert it to the following to make it more convenient for SCEV:
13662 //
13663 // ceil(max(RHS, Start) - Start) / Stride
13664 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13665
13666 // See what would happen if we assume the backedge is taken. This is
13667 // used to compute MaxBECount.
13668 BECountIfBackedgeTaken =
13669 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13670 }
13671
13672 // At this point, we know:
13673 //
13674 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13675 // 2. The index variable doesn't overflow.
13676 //
13677 // Therefore, we know N exists such that
13678 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13679 // doesn't overflow.
13680 //
13681 // Using this information, try to prove whether the addition in
13682 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13683 //
13684 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13685 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13686 // the (Stride - 1) addition below cannot overflow.
13687 const SCEV *One = getOne(Stride->getType());
13688 bool MayAddOverflow = IVMayOverflow && [&] {
13689 if (isKnownToBeAPowerOfTwo(Stride)) {
13690 // Suppose Stride is a power of two, and Start/End are unsigned
13691 // integers. Let UMAX be the largest representable unsigned
13692 // integer.
13693 //
13694 // By the preconditions of this function, we know
13695 // "(Start + Stride * N) >= End", and this doesn't overflow.
13696 // As a formula:
13697 //
13698 // End <= (Start + Stride * N) <= UMAX
13699 //
13700 // Subtracting Start from all the terms:
13701 //
13702 // End - Start <= Stride * N <= UMAX - Start
13703 //
13704 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13705 //
13706 // End - Start <= Stride * N <= UMAX
13707 //
13708 // Stride * N is a multiple of Stride. Therefore,
13709 //
13710 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13711 //
13712 // Since Stride is a power of two, UMAX + 1 is divisible by
13713 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13714 // write:
13715 //
13716 // End - Start <= Stride * N <= UMAX - Stride - 1
13717 //
13718 // Dropping the middle term:
13719 //
13720 // End - Start <= UMAX - Stride - 1
13721 //
13722 // Adding Stride - 1 to both sides:
13723 //
13724 // (End - Start) + (Stride - 1) <= UMAX
13725 //
13726 // In other words, the addition doesn't have unsigned overflow.
13727 //
13728 // A similar proof works if we treat Start/End as signed values.
13729 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13730 // to use signed max instead of unsigned max. Note that we're
13731 // trying to prove a lack of unsigned overflow in either case.
13732 return false;
13733 }
13734 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13735 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13736 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13737 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13738 // 1 <s End.
13739 //
13740 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13741 // End.
13742 return false;
13743 }
13744 return true;
13745 }();
13746
13747 const SCEV *Delta = getMinusSCEV(End, Start);
13748 if (!MayAddOverflow) {
13749 // floor((D + (S - 1)) / S)
13750 // We prefer this formulation if it's legal because it's fewer
13751 // operations.
13752 BECount =
13753 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13754 } else {
13755 BECount = getUDivCeilSCEV(Delta, Stride);
13756 }
13757 }
13758 }
13759
13760 const SCEV *ConstantMaxBECount;
13761 bool MaxOrZero = false;
13762 if (isa<SCEVConstant>(BECount)) {
13763 ConstantMaxBECount = BECount;
13764 } else if (BECountIfBackedgeTaken &&
13765 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13766 // If we know exactly how many times the backedge will be taken if it's
13767 // taken at least once, then the backedge count will either be that or
13768 // zero.
13769 ConstantMaxBECount = BECountIfBackedgeTaken;
13770 MaxOrZero = true;
13771 } else {
13772 ConstantMaxBECount = computeMaxBECountForLT(
13773 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13774 }
13775
13776 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13777 !isa<SCEVCouldNotCompute>(BECount))
13778 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13779
13780 const SCEV *SymbolicMaxBECount =
13781 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13782 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13783 Predicates);
13784}
13785
13786ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13787 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13788 bool ControlsOnlyExit, bool AllowPredicates) {
13790 // We handle only IV > Invariant
13791 if (!isLoopInvariant(RHS, L))
13792 return getCouldNotCompute();
13793
13794 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13795 if (!IV && AllowPredicates)
13796 // Try to make this an AddRec using runtime tests, in the first X
13797 // iterations of this loop, where X is the SCEV expression found by the
13798 // algorithm below.
13799 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13800
13801 // Avoid weird loops
13802 if (!IV || IV->getLoop() != L || !IV->isAffine())
13803 return getCouldNotCompute();
13804
13805 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13806 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13808
13809 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13810
13811 // Avoid negative or zero stride values
13812 if (!isKnownPositive(Stride))
13813 return getCouldNotCompute();
13814
13815 // Avoid proven overflow cases: this will ensure that the backedge taken count
13816 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13817 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13818 // behaviors like the case of C language.
13819 bool MayAddOverflow = false;
13820 const SCEV *Start = IV->getStart();
13821 const SCEV *End = RHS;
13822 if (!Stride->isOne() && canIVOverflowOnGT(RHS, Stride, IsSigned)) {
13823 if (!NoWrap)
13824 return getCouldNotCompute();
13825 MayAddOverflow = true;
13826 }
13827
13828 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13829 // If we know that Start >= RHS in the context of loop, then we know that
13830 // min(RHS, Start) = RHS at this point.
13832 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13833 End = RHS;
13834 else
13835 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13836 }
13837
13838 if (Start->getType()->isPointerTy()) {
13839 Start = getPtrToAddrExpr(Start);
13840 if (isa<SCEVCouldNotCompute>(Start))
13841 return Start;
13842 }
13843 if (End->getType()->isPointerTy()) {
13844 End = getPtrToAddrExpr(End);
13845 if (isa<SCEVCouldNotCompute>(End))
13846 return End;
13847 }
13848
13849 const SCEV *Delta = getMinusSCEV(Start, End);
13850 const SCEV *BECount;
13851 if (MayAddOverflow) {
13852 // The ceiling division instead needs Start >= End, so that (Start - End) is
13853 // the exact unsigned distance between them.
13855 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13856 return getCouldNotCompute();
13857 BECount = getUDivCeilSCEV(Delta, Stride);
13858 } else {
13859 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13860 // overflow as it requires fewer operations.
13861 const SCEV *One = getOne(Stride->getType());
13862 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13863 }
13864
13865 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13867
13868 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13869 : getUnsignedRangeMin(Stride);
13870
13871 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13872 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13873 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13874
13875 // Although End can be a MIN expression we estimate MinEnd considering only
13876 // the case End = RHS. This is safe because in the other case (Start - End)
13877 // is zero, leading to a zero maximum backedge taken count.
13878 APInt MinEnd =
13879 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13880 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13881
13882 const SCEV *ConstantMaxBECount =
13883 isa<SCEVConstant>(BECount)
13884 ? BECount
13885 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13886 getConstant(MinStride));
13887
13888 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13889 ConstantMaxBECount = BECount;
13890 const SCEV *SymbolicMaxBECount =
13891 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13892
13893 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13894 Predicates);
13895}
13896
13898 ScalarEvolution &SE) const {
13899 if (Range.isFullSet()) // Infinite loop.
13900 return SE.getCouldNotCompute();
13901
13902 // If the start is a non-zero constant, shift the range to simplify things.
13903 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13904 if (!SC->getValue()->isZero()) {
13906 Operands[0] = SE.getZero(SC->getType());
13907 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13909 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13910 return ShiftedAddRec->getNumIterationsInRange(
13911 Range.subtract(SC->getAPInt()), SE);
13912 // This is strange and shouldn't happen.
13913 return SE.getCouldNotCompute();
13914 }
13915
13916 // The only time we can solve this is when we have all constant indices.
13917 // Otherwise, we cannot determine the overflow conditions.
13919 return SE.getCouldNotCompute();
13920
13921 // Okay at this point we know that all elements of the chrec are constants and
13922 // that the start element is zero.
13923
13924 // First check to see if the range contains zero. If not, the first
13925 // iteration exits.
13926 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13927 if (!Range.contains(APInt(BitWidth, 0)))
13928 return SE.getZero(getType());
13929
13930 if (isAffine()) {
13931 // If this is an affine expression then we have this situation:
13932 // Solve {0,+,A} in Range === Ax in Range
13933
13934 // We know that zero is in the range. If A is positive then we know that
13935 // the upper value of the range must be the first possible exit value.
13936 // If A is negative then the lower of the range is the last possible loop
13937 // value. Also note that we already checked for a full range.
13938 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13939 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13940
13941 // The exit value should be (End+A)/A.
13942 APInt ExitVal = (End + A).udiv(A);
13943 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13944
13945 // Evaluate at the exit value. If we really did fall out of the valid
13946 // range, then we computed our trip count, otherwise wrap around or other
13947 // things must have happened.
13948 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13949 if (Range.contains(Val->getValue()))
13950 return SE.getCouldNotCompute(); // Something strange happened
13951
13952 // Ensure that the previous value is in the range.
13953 assert(Range.contains(
13955 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13956 "Linear scev computation is off in a bad way!");
13957 return SE.getConstant(ExitValue);
13958 }
13959
13960 if (isQuadratic()) {
13961 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13962 return SE.getConstant(*S);
13963 }
13964
13965 return SE.getCouldNotCompute();
13966}
13967
13968const SCEVAddRecExpr *
13970 assert(getNumOperands() > 1 && "AddRec with zero step?");
13971 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13972 // but in this case we cannot guarantee that the value returned will be an
13973 // AddRec because SCEV does not have a fixed point where it stops
13974 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13975 // may happen if we reach arithmetic depth limit while simplifying. So we
13976 // construct the returned value explicitly.
13978 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13979 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13980 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13981 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13982 // We know that the last operand is not a constant zero (otherwise it would
13983 // have been popped out earlier). This guarantees us that if the result has
13984 // the same last operand, then it will also not be popped out, meaning that
13985 // the returned value will be an AddRec.
13986 const SCEV *Last = getOperand(getNumOperands() - 1);
13987 assert(!Last->isZero() && "Recurrency with zero step?");
13988 Ops.push_back(Last);
13991}
13992
13993// Return true when S contains at least an undef value.
13995 return SCEVExprContains(
13996 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13997}
13998
13999// Return true when S contains a value that is a nullptr.
14001 return SCEVExprContains(S, [](const SCEV *S) {
14002 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14003 return SU->getValue() == nullptr;
14004 return false;
14005 });
14006}
14007
14008/// Return the size of an element read or written by Inst.
14010 Type *Ty;
14011 Type *PtrTy;
14012 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14013 Ty = Store->getValueOperand()->getType();
14014 PtrTy = Store->getPointerOperandType();
14015 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14016 Ty = Load->getType();
14017 PtrTy = Load->getPointerOperandType();
14018 } else {
14019 return nullptr;
14020 }
14021
14022 Type *ETy = getEffectiveSCEVType(PtrTy);
14023 return getSizeOfExpr(ETy, Ty);
14024}
14025
14026//===----------------------------------------------------------------------===//
14027// SCEVCallbackVH Class Implementation
14028//===----------------------------------------------------------------------===//
14029
14031 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14032 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14033 SE->ConstantEvolutionLoopExitValue.erase(PN);
14034 SE->eraseValueFromMap(getValPtr());
14035 // this now dangles!
14036}
14037
14038void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14039 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14040
14041 // Forget all the expressions associated with users of the old value,
14042 // so that future queries will recompute the expressions using the new
14043 // value.
14044 SE->forgetValue(getValPtr());
14045 // this now dangles!
14046}
14047
14048ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14049 : CallbackVH(V), SE(se) {}
14050
14051//===----------------------------------------------------------------------===//
14052// ScalarEvolution Class Implementation
14053//===----------------------------------------------------------------------===//
14054
14057 LoopInfo &LI)
14058 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14059 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14060 LoopDispositions(64), BlockDispositions(64) {
14061 // To use guards for proving predicates, we need to scan every instruction in
14062 // relevant basic blocks, and not just terminators. Doing this is a waste of
14063 // time if the IR does not actually contain any calls to
14064 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14065 //
14066 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14067 // to _add_ guards to the module when there weren't any before, and wants
14068 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14069 // efficient in lieu of being smart in that rather obscure case.
14070
14071 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14072 F.getParent(), Intrinsic::experimental_guard);
14073 HasGuards = GuardDecl && !GuardDecl->use_empty();
14074}
14075
14077 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14078 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14079 ValueExprMap(std::move(Arg.ValueExprMap)),
14080 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14081 PendingMerges(std::move(Arg.PendingMerges)),
14082 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14083 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14084 PredicatedBackedgeTakenCounts(
14085 std::move(Arg.PredicatedBackedgeTakenCounts)),
14086 BECountUsers(std::move(Arg.BECountUsers)),
14087 ConstantEvolutionLoopExitValue(
14088 std::move(Arg.ConstantEvolutionLoopExitValue)),
14089 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14090 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14091 LoopDispositions(std::move(Arg.LoopDispositions)),
14092 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14093 BlockDispositions(std::move(Arg.BlockDispositions)),
14094 SCEVUsers(std::move(Arg.SCEVUsers)),
14095 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14096 SignedRanges(std::move(Arg.SignedRanges)),
14097 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14098 UniquePreds(std::move(Arg.UniquePreds)),
14099 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14100 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14101 LoopUsers(std::move(Arg.LoopUsers)),
14102 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14103 FirstUnknown(Arg.FirstUnknown) {
14104 Arg.FirstUnknown = nullptr;
14105}
14106
14108 // Iterate through all the SCEVUnknown instances and call their
14109 // destructors, so that they release their references to their values.
14110 for (SCEVUnknown *U = FirstUnknown; U;) {
14111 SCEVUnknown *Tmp = U;
14112 U = U->Next;
14113 Tmp->~SCEVUnknown();
14114 }
14115 FirstUnknown = nullptr;
14116
14117 ExprValueMap.clear();
14118 ValueExprMap.clear();
14119 HasRecMap.clear();
14120 BackedgeTakenCounts.clear();
14121 PredicatedBackedgeTakenCounts.clear();
14122
14123 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14124 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14125 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14126 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14127}
14128
14132
14133/// When printing a top-level SCEV for trip counts, it's helpful to include
14134/// a type for constants which are otherwise hard to disambiguate.
14135static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14136 if (isa<SCEVConstant>(S))
14137 OS << *S->getType() << " ";
14138 OS << *S;
14139}
14140
14142 const Loop *L) {
14143 // Print all inner loops first
14144 for (Loop *I : *L)
14145 PrintLoopInfo(OS, SE, I);
14146
14147 OS << "Loop ";
14148 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14149 OS << ": ";
14150
14151 SmallVector<BasicBlock *, 8> ExitingBlocks;
14152 L->getExitingBlocks(ExitingBlocks);
14153 if (ExitingBlocks.size() != 1)
14154 OS << "<multiple exits> ";
14155
14156 auto *BTC = SE->getBackedgeTakenCount(L);
14157 if (!isa<SCEVCouldNotCompute>(BTC)) {
14158 OS << "backedge-taken count is ";
14159 PrintSCEVWithTypeHint(OS, BTC);
14160 } else
14161 OS << "Unpredictable backedge-taken count.";
14162 OS << "\n";
14163
14164 if (ExitingBlocks.size() > 1)
14165 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14166 OS << " exit count for " << ExitingBlock->getName() << ": ";
14167 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14168 PrintSCEVWithTypeHint(OS, EC);
14169 if (isa<SCEVCouldNotCompute>(EC)) {
14170 // Retry with predicates.
14172 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14173 if (!isa<SCEVCouldNotCompute>(EC)) {
14174 OS << "\n predicated exit count for " << ExitingBlock->getName()
14175 << ": ";
14176 PrintSCEVWithTypeHint(OS, EC);
14177 OS << "\n Predicates:\n";
14178 for (const auto *P : Predicates)
14179 P->print(OS, 4);
14180 }
14181 }
14182 OS << "\n";
14183 }
14184
14185 OS << "Loop ";
14186 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14187 OS << ": ";
14188
14189 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14190 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14191 OS << "constant max backedge-taken count is ";
14192 PrintSCEVWithTypeHint(OS, ConstantBTC);
14194 OS << ", actual taken count either this or zero.";
14195 } else {
14196 OS << "Unpredictable constant max backedge-taken count. ";
14197 }
14198
14199 OS << "\n"
14200 "Loop ";
14201 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14202 OS << ": ";
14203
14204 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14205 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14206 OS << "symbolic max backedge-taken count is ";
14207 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14209 OS << ", actual taken count either this or zero.";
14210 } else {
14211 OS << "Unpredictable symbolic max backedge-taken count. ";
14212 }
14213 OS << "\n";
14214
14215 if (ExitingBlocks.size() > 1)
14216 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14217 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14218 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14220 PrintSCEVWithTypeHint(OS, ExitBTC);
14221 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14222 // Retry with predicates.
14224 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14226 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14227 OS << "\n predicated symbolic max exit count for "
14228 << ExitingBlock->getName() << ": ";
14229 PrintSCEVWithTypeHint(OS, ExitBTC);
14230 OS << "\n Predicates:\n";
14231 for (const auto *P : Predicates)
14232 P->print(OS, 4);
14233 }
14234 }
14235 OS << "\n";
14236 }
14237
14239 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14240 if (PBT != BTC) {
14241 OS << "Loop ";
14242 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14243 OS << ": ";
14244 if (!isa<SCEVCouldNotCompute>(PBT)) {
14245 OS << "Predicated backedge-taken count is ";
14246 PrintSCEVWithTypeHint(OS, PBT);
14247 } else
14248 OS << "Unpredictable predicated backedge-taken count.";
14249 OS << "\n";
14250 OS << " Predicates:\n";
14251 for (const auto *P : Preds)
14252 P->print(OS, 4);
14253 }
14254 Preds.clear();
14255
14256 auto *PredConstantMax =
14258 if (PredConstantMax != ConstantBTC) {
14259 OS << "Loop ";
14260 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14261 OS << ": ";
14262 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14263 OS << "Predicated constant max backedge-taken count is ";
14264 PrintSCEVWithTypeHint(OS, PredConstantMax);
14265 } else
14266 OS << "Unpredictable predicated constant max backedge-taken count.";
14267 OS << "\n";
14268 OS << " Predicates:\n";
14269 for (const auto *P : Preds)
14270 P->print(OS, 4);
14271 }
14272 Preds.clear();
14273
14274 auto *PredSymbolicMax =
14276 if (SymbolicBTC != PredSymbolicMax) {
14277 OS << "Loop ";
14278 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14279 OS << ": ";
14280 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14281 OS << "Predicated symbolic max backedge-taken count is ";
14282 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14283 } else
14284 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14285 OS << "\n";
14286 OS << " Predicates:\n";
14287 for (const auto *P : Preds)
14288 P->print(OS, 4);
14289 }
14290
14292 OS << "Loop ";
14293 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14294 OS << ": ";
14295 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14296 }
14297}
14298
14299namespace llvm {
14300// Note: these overloaded operators need to be in the llvm namespace for them
14301// to be resolved correctly. If we put them outside the llvm namespace, the
14302//
14303// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14304//
14305// code below "breaks" and start printing raw enum values as opposed to the
14306// string values.
14309 switch (LD) {
14311 OS << "Variant";
14312 break;
14314 OS << "Invariant";
14315 break;
14317 OS << "Uniform";
14318 break;
14320 OS << "Computable";
14321 break;
14322 }
14323 return OS;
14324}
14325
14328 switch (BD) {
14330 OS << "DoesNotDominate";
14331 break;
14333 OS << "Dominates";
14334 break;
14336 OS << "ProperlyDominates";
14337 break;
14338 }
14339 return OS;
14340}
14341} // namespace llvm
14342
14344 // ScalarEvolution's implementation of the print method is to print
14345 // out SCEV values of all instructions that are interesting. Doing
14346 // this potentially causes it to create new SCEV objects though,
14347 // which technically conflicts with the const qualifier. This isn't
14348 // observable from outside the class though, so casting away the
14349 // const isn't dangerous.
14350 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14351
14352 if (ClassifyExpressions) {
14353 OS << "Classifying expressions for: ";
14354 F.printAsOperand(OS, /*PrintType=*/false);
14355 OS << "\n";
14356 for (Instruction &I : instructions(F))
14357 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14358 OS << I << '\n';
14359 OS << " --> ";
14360 const SCEV *SV = SE.getSCEV(&I);
14361 SV->print(OS);
14362 if (!isa<SCEVCouldNotCompute>(SV)) {
14363 OS << " U: ";
14364 SE.getUnsignedRange(SV).print(OS);
14365 OS << " S: ";
14366 SE.getSignedRange(SV).print(OS);
14367 }
14368
14369 const Loop *L = LI.getLoopFor(I.getParent());
14370
14371 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14372 if (AtUse != SV) {
14373 OS << " --> ";
14374 OS << AtUse;
14375 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14376 OS << " U: ";
14377 SE.getUnsignedRange(AtUse).print(OS);
14378 OS << " S: ";
14379 SE.getSignedRange(AtUse).print(OS);
14380 }
14381 }
14382
14383 if (L) {
14384 OS << "\t\t" "Exits: ";
14385 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14386 if (!SE.isLoopInvariant(ExitValue, L)) {
14387 OS << "<<Unknown>>";
14388 } else {
14389 OS << ExitValue;
14390 }
14391
14392 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14393 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14394 OS << LS;
14395 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14396 OS << ": " << SE.getLoopDisposition(SV, Iter);
14397 }
14398
14399 for (const auto *InnerL : depth_first(L)) {
14400 if (InnerL == L)
14401 continue;
14402 OS << LS;
14403 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14404 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14405 }
14406
14407 OS << " }";
14408 }
14409
14410 OS << "\n";
14411 }
14412 }
14413
14414 OS << "Determining loop execution counts for: ";
14415 F.printAsOperand(OS, /*PrintType=*/false);
14416 OS << "\n";
14417 for (Loop *I : LI)
14418 PrintLoopInfo(OS, &SE, I);
14419}
14420
14423 auto &Values = LoopDispositions[S];
14424 for (auto &V : Values) {
14425 if (V.getPointer() == L)
14426 return V.getInt();
14427 }
14428 Values.emplace_back(L, LoopVariant);
14429 LoopDisposition D = computeLoopDisposition(S, L);
14430 auto &Values2 = LoopDispositions[S];
14431 for (auto &V : llvm::reverse(Values2)) {
14432 if (V.getPointer() == L) {
14433 V.setInt(D);
14434 break;
14435 }
14436 }
14437 return D;
14438}
14439
14441ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14442 switch (S->getSCEVType()) {
14443 case scConstant:
14444 case scVScale:
14445 return LoopInvariant;
14446 case scAddRecExpr: {
14447 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14448
14449 // If L is the addrec's loop, it's computable.
14450 if (AR->getLoop() == L)
14451 return LoopComputable;
14452
14453 // Add recurrences are never invariant in the function-body (null loop).
14454 if (!L)
14455 return LoopVariant;
14456
14457 // Everything that is not defined at loop entry is variant.
14458 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14459 if (L->contains(AR->getLoop()) &&
14460 llvm::all_of(AR->operands(),
14461 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14462 return LoopUniform;
14463
14464 return LoopVariant;
14465 }
14466 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14467 " dominate the contained loop's header?");
14468
14469 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14470 if (AR->getLoop()->contains(L))
14471 return LoopInvariant;
14472
14473 // This recurrence is variant w.r.t. L if any of its operands
14474 // are variant.
14475 for (SCEVUse Op : AR->operands())
14476 if (!isLoopInvariant(Op, L))
14477 return LoopVariant;
14478
14479 // Otherwise it's loop-invariant.
14480 return LoopInvariant;
14481 }
14482 case scTruncate:
14483 case scZeroExtend:
14484 case scSignExtend:
14485 case scPtrToAddr:
14486 case scAddExpr:
14487 case scMulExpr:
14488 case scUDivExpr:
14489 case scUMaxExpr:
14490 case scSMaxExpr:
14491 case scUMinExpr:
14492 case scSMinExpr:
14493 case scSequentialUMinExpr: {
14494 bool HasVarying = false;
14495 bool HasUniform = false;
14496 for (SCEVUse Op : S->operands()) {
14498 if (D == LoopVariant)
14499 return LoopVariant;
14500 if (D == LoopComputable)
14501 HasVarying = true;
14502 if (D == LoopUniform)
14503 HasUniform = true;
14504 }
14505 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14506 : (HasUniform ? LoopUniform : LoopInvariant);
14507 }
14508 case scUnknown:
14509 // All non-instruction values are loop invariant. All instructions are loop
14510 // invariant if they are not contained in the specified loop.
14511 // Instructions are never considered invariant in the function body
14512 // (null loop) because they are defined within the "loop".
14514 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14515 return LoopInvariant;
14516 case scCouldNotCompute:
14517 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14518 }
14519 llvm_unreachable("Unknown SCEV kind!");
14520}
14521
14522bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14524 return D == LoopUniform || D == LoopInvariant;
14525}
14526
14528 return getLoopDisposition(S, L) == LoopInvariant;
14529}
14530
14532 return getLoopDisposition(S, L) == LoopComputable;
14533}
14534
14537 auto &Values = BlockDispositions[S];
14538 for (auto &V : Values) {
14539 if (V.getPointer() == BB)
14540 return V.getInt();
14541 }
14542 Values.emplace_back(BB, DoesNotDominateBlock);
14543 BlockDisposition D = computeBlockDisposition(S, BB);
14544 auto &Values2 = BlockDispositions[S];
14545 for (auto &V : llvm::reverse(Values2)) {
14546 if (V.getPointer() == BB) {
14547 V.setInt(D);
14548 break;
14549 }
14550 }
14551 return D;
14552}
14553
14555ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14556 switch (S->getSCEVType()) {
14557 case scConstant:
14558 case scVScale:
14560 case scAddRecExpr: {
14561 // This uses a "dominates" query instead of "properly dominates" query
14562 // to test for proper dominance too, because the instruction which
14563 // produces the addrec's value is a PHI, and a PHI effectively properly
14564 // dominates its entire containing block.
14565 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14566 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14567 return DoesNotDominateBlock;
14568
14569 // Fall through into SCEVNAryExpr handling.
14570 [[fallthrough]];
14571 }
14572 case scTruncate:
14573 case scZeroExtend:
14574 case scSignExtend:
14575 case scPtrToAddr:
14576 case scAddExpr:
14577 case scMulExpr:
14578 case scUDivExpr:
14579 case scUMaxExpr:
14580 case scSMaxExpr:
14581 case scUMinExpr:
14582 case scSMinExpr:
14583 case scSequentialUMinExpr: {
14584 bool Proper = true;
14585 for (const SCEV *NAryOp : S->operands()) {
14587 if (D == DoesNotDominateBlock)
14588 return DoesNotDominateBlock;
14589 if (D == DominatesBlock)
14590 Proper = false;
14591 }
14592 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14593 }
14594 case scUnknown:
14595 if (Instruction *I =
14597 if (I->getParent() == BB)
14598 return DominatesBlock;
14599 if (DT.properlyDominates(I->getParent(), BB))
14601 return DoesNotDominateBlock;
14602 }
14604 case scCouldNotCompute:
14605 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14606 }
14607 llvm_unreachable("Unknown SCEV kind!");
14608}
14609
14610bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14611 return getBlockDisposition(S, BB) >= DominatesBlock;
14612}
14613
14616}
14617
14618bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14619 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14620}
14621
14622void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14623 bool Predicated) {
14624 auto &BECounts =
14625 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14626 auto It = BECounts.find(L);
14627 if (It != BECounts.end()) {
14628 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14629 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14630 if (!isa<SCEVConstant>(S)) {
14631 auto UserIt = BECountUsers.find(S);
14632 assert(UserIt != BECountUsers.end());
14633 UserIt->second.erase({L, Predicated});
14634 }
14635 }
14636 }
14637 BECounts.erase(It);
14638 }
14639}
14640
14641void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14642 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14643 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14644
14645 while (!Worklist.empty()) {
14646 const SCEV *Curr = Worklist.pop_back_val();
14647 auto Users = SCEVUsers.find(Curr);
14648 if (Users != SCEVUsers.end())
14649 for (const auto *User : Users->second)
14650 if (ToForget.insert(User).second)
14651 Worklist.push_back(User);
14652 }
14653
14654 for (const auto *S : ToForget)
14655 forgetMemoizedResultsImpl(S);
14656
14657 PredicatedSCEVRewrites.remove_if(
14658 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14659}
14660
14661void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14662 LoopDispositions.erase(S);
14663 BlockDispositions.erase(S);
14664 UnsignedRanges.erase(S);
14665 SignedRanges.erase(S);
14666 HasRecMap.erase(S);
14667 ConstantMultipleCache.erase(S);
14668
14669 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14670 UnsignedWrapViaInductionTried.erase(AR);
14671 SignedWrapViaInductionTried.erase(AR);
14672 }
14673
14674 auto ExprIt = ExprValueMap.find(S);
14675 if (ExprIt != ExprValueMap.end()) {
14676 for (Value *V : ExprIt->second) {
14677 auto ValueIt = ValueExprMap.find_as(V);
14678 if (ValueIt != ValueExprMap.end())
14679 ValueExprMap.erase(ValueIt);
14680 }
14681 ExprValueMap.erase(ExprIt);
14682 }
14683
14684 auto ScopeIt = ValuesAtScopes.find(S);
14685 if (ScopeIt != ValuesAtScopes.end()) {
14686 for (const auto &Pair : ScopeIt->second)
14687 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14688 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14689 std::make_pair(Pair.first, S));
14690 ValuesAtScopes.erase(ScopeIt);
14691 }
14692
14693 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14694 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14695 for (const auto &Pair : ScopeUserIt->second)
14696 // The recorded value at scope is a use of S, which may carry no-wrap
14697 // flags that are not part of this key.
14698 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14699 return LS.first == Pair.first && LS.second.getPointer() == S;
14700 });
14701 ValuesAtScopesUsers.erase(ScopeUserIt);
14702 }
14703
14704 auto BEUsersIt = BECountUsers.find(S);
14705 if (BEUsersIt != BECountUsers.end()) {
14706 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14707 auto Copy = BEUsersIt->second;
14708 for (const auto &Pair : Copy)
14709 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14710 BECountUsers.erase(BEUsersIt);
14711 }
14712
14713 auto FoldUser = FoldCacheUser.find(S);
14714 if (FoldUser != FoldCacheUser.end())
14715 for (auto &KV : FoldUser->second)
14716 FoldCache.erase(KV);
14717 FoldCacheUser.erase(S);
14718}
14719
14720void
14721ScalarEvolution::getUsedLoops(const SCEV *S,
14722 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14723 struct FindUsedLoops {
14724 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14725 : LoopsUsed(LoopsUsed) {}
14726 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14727 bool follow(const SCEV *S) {
14728 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14729 LoopsUsed.insert(AR->getLoop());
14730 return true;
14731 }
14732
14733 bool isDone() const { return false; }
14734 };
14735
14736 FindUsedLoops F(LoopsUsed);
14737 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14738}
14739
14740void ScalarEvolution::getReachableBlocks(
14743 Worklist.push_back(&F.getEntryBlock());
14744 while (!Worklist.empty()) {
14745 BasicBlock *BB = Worklist.pop_back_val();
14746 if (!Reachable.insert(BB).second)
14747 continue;
14748
14749 Value *Cond;
14750 BasicBlock *TrueBB, *FalseBB;
14751 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14752 m_BasicBlock(FalseBB)))) {
14753 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14754 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14755 continue;
14756 }
14757
14758 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14759 const SCEV *L = getSCEV(Cmp->getOperand(0));
14760 const SCEV *R = getSCEV(Cmp->getOperand(1));
14761 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14762 Worklist.push_back(TrueBB);
14763 continue;
14764 }
14765 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14766 R)) {
14767 Worklist.push_back(FalseBB);
14768 continue;
14769 }
14770 }
14771 }
14772
14773 append_range(Worklist, successors(BB));
14774 }
14775}
14776
14778 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14779 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14780
14781 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14782
14783 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14784 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14785 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14786
14787 const SCEV *visitConstant(const SCEVConstant *Constant) {
14788 return SE.getConstant(Constant->getAPInt());
14789 }
14790
14791 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14792 return SE.getUnknown(Expr->getValue());
14793 }
14794
14795 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14796 return SE.getCouldNotCompute();
14797 }
14798 };
14799
14800 SCEVMapper SCM(SE2);
14801 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14802 SE2.getReachableBlocks(ReachableBlocks, F);
14803
14804 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14805 if (containsUndefs(Old) || containsUndefs(New)) {
14806 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14807 // not propagate undef aggressively). This means we can (and do) fail
14808 // verification in cases where a transform makes a value go from "undef"
14809 // to "undef+1" (say). The transform is fine, since in both cases the
14810 // result is "undef", but SCEV thinks the value increased by 1.
14811 return nullptr;
14812 }
14813
14814 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14815 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14816 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14817 return nullptr;
14818
14819 return Delta;
14820 };
14821
14822 while (!LoopStack.empty()) {
14823 auto *L = LoopStack.pop_back_val();
14824 llvm::append_range(LoopStack, *L);
14825
14826 // Only verify BECounts in reachable loops. For an unreachable loop,
14827 // any BECount is legal.
14828 if (!ReachableBlocks.contains(L->getHeader()))
14829 continue;
14830
14831 // Only verify cached BECounts. Computing new BECounts may change the
14832 // results of subsequent SCEV uses.
14833 auto It = BackedgeTakenCounts.find(L);
14834 if (It == BackedgeTakenCounts.end())
14835 continue;
14836
14837 auto *CurBECount =
14838 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14839 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14840
14841 if (CurBECount == SE2.getCouldNotCompute() ||
14842 NewBECount == SE2.getCouldNotCompute()) {
14843 // NB! This situation is legal, but is very suspicious -- whatever pass
14844 // change the loop to make a trip count go from could not compute to
14845 // computable or vice-versa *should have* invalidated SCEV. However, we
14846 // choose not to assert here (for now) since we don't want false
14847 // positives.
14848 continue;
14849 }
14850
14851 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14852 SE.getTypeSizeInBits(NewBECount->getType()))
14853 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14854 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14855 SE.getTypeSizeInBits(NewBECount->getType()))
14856 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14857
14858 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14859 if (Delta && !Delta->isZero()) {
14860 dbgs() << "Trip Count for " << *L << " Changed!\n";
14861 dbgs() << "Old: " << *CurBECount << "\n";
14862 dbgs() << "New: " << *NewBECount << "\n";
14863 dbgs() << "Delta: " << *Delta << "\n";
14864 std::abort();
14865 }
14866 }
14867
14868 // Collect all valid loops currently in LoopInfo.
14869 SmallPtrSet<Loop *, 32> ValidLoops;
14870 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14871 while (!Worklist.empty()) {
14872 Loop *L = Worklist.pop_back_val();
14873 if (ValidLoops.insert(L).second)
14874 Worklist.append(L->begin(), L->end());
14875 }
14876 for (const auto &KV : ValueExprMap) {
14877#ifndef NDEBUG
14878 // Check for SCEV expressions referencing invalid/deleted loops.
14879 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14880 assert(ValidLoops.contains(AR->getLoop()) &&
14881 "AddRec references invalid loop");
14882 }
14883#endif
14884
14885 // Check that the value is also part of the reverse map.
14886 auto It = ExprValueMap.find(KV.second);
14887 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14888 dbgs() << "Value " << *KV.first
14889 << " is in ValueExprMap but not in ExprValueMap\n";
14890 std::abort();
14891 }
14892
14893 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14894 if (!ReachableBlocks.contains(I->getParent()))
14895 continue;
14896 const SCEV *OldSCEV = SCM.visit(KV.second);
14897 const SCEV *NewSCEV = SE2.getSCEV(I);
14898 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14899 if (Delta && !Delta->isZero()) {
14900 dbgs() << "SCEV for value " << *I << " changed!\n"
14901 << "Old: " << *OldSCEV << "\n"
14902 << "New: " << *NewSCEV << "\n"
14903 << "Delta: " << *Delta << "\n";
14904 std::abort();
14905 }
14906 }
14907 }
14908
14909 for (const auto &KV : ExprValueMap) {
14910 for (Value *V : KV.second) {
14911 const SCEV *S = ValueExprMap.lookup(V);
14912 if (!S) {
14913 dbgs() << "Value " << *V
14914 << " is in ExprValueMap but not in ValueExprMap\n";
14915 std::abort();
14916 }
14917 if (S != KV.first) {
14918 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14919 << *KV.first << "\n";
14920 std::abort();
14921 }
14922 }
14923 }
14924
14925 // Verify integrity of SCEV users.
14926 for (const auto &S : UniqueSCEVs) {
14927 for (SCEVUse Op : S.operands()) {
14928 // We do not store dependencies of constants.
14929 if (isa<SCEVConstant>(Op))
14930 continue;
14931 auto It = SCEVUsers.find(Op);
14932 if (It != SCEVUsers.end() && It->second.count(&S))
14933 continue;
14934 dbgs() << "Use of operand " << *Op << " by user " << S
14935 << " is not being tracked!\n";
14936 std::abort();
14937 }
14938 }
14939
14940 // Verify integrity of ValuesAtScopes users.
14941 for (const auto &ValueAndVec : ValuesAtScopes) {
14942 const SCEV *Value = ValueAndVec.first;
14943 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14944 const Loop *L = LoopAndValueAtScope.first;
14945 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14946 if (!isa<SCEVConstant>(ValueAtScope)) {
14947 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14948 if (It != ValuesAtScopesUsers.end() &&
14949 is_contained(It->second, std::make_pair(L, Value)))
14950 continue;
14951 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14952 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14953 std::abort();
14954 }
14955 }
14956 }
14957
14958 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14959 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14960 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14961 const Loop *L = LoopAndValue.first;
14962 const SCEV *Value = LoopAndValue.second;
14964 auto It = ValuesAtScopes.find(Value);
14965 // The recorded value at scope may carry no-wrap flags that are not part
14966 // of the key it is recorded under.
14967 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14968 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14969 }))
14970 continue;
14971 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14972 << *ValueAtScope << " missing in ValuesAtScopes\n";
14973 std::abort();
14974 }
14975 }
14976
14977 // Verify integrity of BECountUsers.
14978 auto VerifyBECountUsers = [&](bool Predicated) {
14979 auto &BECounts =
14980 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14981 for (const auto &LoopAndBEInfo : BECounts) {
14982 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14983 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14984 if (!isa<SCEVConstant>(S)) {
14985 auto UserIt = BECountUsers.find(S);
14986 if (UserIt != BECountUsers.end() &&
14987 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14988 continue;
14989 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14990 << " missing from BECountUsers\n";
14991 std::abort();
14992 }
14993 }
14994 }
14995 }
14996 };
14997 VerifyBECountUsers(/* Predicated */ false);
14998 VerifyBECountUsers(/* Predicated */ true);
14999
15000 // Verify intergity of loop disposition cache.
15001 for (auto &[S, Values] : LoopDispositions) {
15002 for (auto [Loop, CachedDisposition] : Values) {
15003 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15004 if (CachedDisposition != RecomputedDisposition) {
15005 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15006 << " is incorrect: cached " << CachedDisposition << ", actual "
15007 << RecomputedDisposition << "\n";
15008 std::abort();
15009 }
15010 }
15011 }
15012
15013 // Verify integrity of the block disposition cache.
15014 for (auto &[S, Values] : BlockDispositions) {
15015 for (auto [BB, CachedDisposition] : Values) {
15016 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15017 if (CachedDisposition != RecomputedDisposition) {
15018 dbgs() << "Cached disposition of " << *S << " for block %"
15019 << BB->getName() << " is incorrect: cached " << CachedDisposition
15020 << ", actual " << RecomputedDisposition << "\n";
15021 std::abort();
15022 }
15023 }
15024 }
15025
15026 // Verify FoldCache/FoldCacheUser caches.
15027 for (auto [FoldID, Expr] : FoldCache) {
15028 auto I = FoldCacheUser.find(Expr);
15029 if (I == FoldCacheUser.end()) {
15030 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15031 << "!\n";
15032 std::abort();
15033 }
15034 if (!is_contained(I->second, FoldID)) {
15035 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15036 std::abort();
15037 }
15038 }
15039 for (auto [Expr, IDs] : FoldCacheUser) {
15040 for (auto &FoldID : IDs) {
15041 const SCEV *S = FoldCache.lookup(FoldID);
15042 if (!S) {
15043 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15044 << "!\n";
15045 std::abort();
15046 }
15047 if (S != Expr) {
15048 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15049 << " != " << *Expr << "!\n";
15050 std::abort();
15051 }
15052 }
15053 }
15054
15055 // Verify that ConstantMultipleCache computations are correct. We check that
15056 // cached multiples and recomputed multiples are multiples of each other to
15057 // verify correctness. It is possible that a recomputed multiple is different
15058 // from the cached multiple due to strengthened no wrap flags or changes in
15059 // KnownBits computations.
15060 for (auto [S, Multiple] : ConstantMultipleCache) {
15061 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15062 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15063 Multiple.urem(RecomputedMultiple) != 0 &&
15064 RecomputedMultiple.urem(Multiple) != 0)) {
15065 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15066 << *S << " : Computed " << RecomputedMultiple
15067 << " but cache contains " << Multiple << "!\n";
15068 std::abort();
15069 }
15070 }
15071}
15072
15074 Function &F, const PreservedAnalyses &PA,
15075 FunctionAnalysisManager::Invalidator &Inv) {
15076 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15077 // of its dependencies is invalidated.
15078 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15079 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15080 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15081 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15082 Inv.invalidate<LoopAnalysis>(F, PA);
15083}
15084
15085AnalysisKey ScalarEvolutionAnalysis::Key;
15086
15089 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15090 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15091 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15092 auto &LI = AM.getResult<LoopAnalysis>(F);
15093 return ScalarEvolution(F, TLI, AC, DT, LI);
15094}
15095
15101
15104 // For compatibility with opt's -analyze feature under legacy pass manager
15105 // which was not ported to NPM. This keeps tests using
15106 // update_analyze_test_checks.py working.
15107 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15108 << F.getName() << "':\n";
15110 return PreservedAnalyses::all();
15111}
15112
15114 "Scalar Evolution Analysis", false, true)
15120 "Scalar Evolution Analysis", false, true)
15121
15122char ScalarEvolutionWrapperPass::ID = 0;
15123
15125
15127 SE.reset(new ScalarEvolution(
15129 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15131 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15132 return false;
15133}
15134
15136
15138 SE->print(OS);
15139}
15140
15142 if (!VerifySCEV)
15143 return;
15144
15145 SE->verify();
15146}
15147
15155
15157 const SCEV *RHS) {
15158 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15159}
15160
15161const SCEVPredicate *
15163 const SCEV *LHS, const SCEV *RHS) {
15165 assert(LHS->getType() == RHS->getType() &&
15166 "Type mismatch between LHS and RHS");
15167 // Unique this node based on the arguments
15168 ID.AddInteger(SCEVPredicate::P_Compare);
15169 ID.AddInteger(Pred);
15170 ID.AddPointer(LHS);
15171 ID.AddPointer(RHS);
15173 if (const auto *S = UniquePreds.lookup(ID, Token))
15174 return S;
15175 SCEVComparePredicate *Eq = new (SCEVAllocator)
15176 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15177 UniquePreds.insert(Eq, Token);
15178 return Eq;
15179}
15180
15182 const SCEVAddRecExpr *AR,
15185 // Unique this node based on the arguments
15187 ID.AddPointer(AR);
15188 ID.AddInteger(AddedFlags);
15190 if (const auto *S = UniquePreds.lookup(ID, Token))
15191 return S;
15192 auto *OF = new (SCEVAllocator)
15193 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15194 UniquePreds.insert(OF, Token);
15195 return OF;
15196}
15197
15198namespace {
15199
15200class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15201public:
15202
15203 /// Rewrites \p S in the context of a loop L and the SCEV predication
15204 /// infrastructure.
15205 ///
15206 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15207 /// equivalences present in \p Pred.
15208 ///
15209 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15210 /// \p NewPreds such that the result will be an AddRecExpr.
15211 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15213 const SCEVPredicate *Pred) {
15214 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15215 return Rewriter.visit(S);
15216 }
15217
15218 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15219 if (Pred) {
15220 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15221 for (const auto *Pred : U->getPredicates())
15222 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15223 if (IPred->getLHS() == Expr &&
15224 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15225 return IPred->getRHS();
15226 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15227 if (IPred->getLHS() == Expr &&
15228 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15229 return IPred->getRHS();
15230 }
15231 }
15232 return convertToAddRecWithPreds(Expr);
15233 }
15234
15235 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15236 const SCEV *Operand = visit(Expr->getOperand());
15237 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15238 if (AR && AR->getLoop() == L && AR->isAffine()) {
15239 // This couldn't be folded because the operand didn't have the nuw
15240 // flag. Add the nusw flag as an assumption that we could make.
15241 const SCEV *Step = AR->getStepRecurrence(SE);
15242 Type *Ty = Expr->getType();
15243 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15244 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15245 SE.getSignExtendExpr(Step, Ty), L,
15246 AR->getNoWrapFlags());
15247 }
15248 return SE.getZeroExtendExpr(Operand, Expr->getType());
15249 }
15250
15251 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15252 const SCEV *Operand = visit(Expr->getOperand());
15253 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15254 if (AR && AR->getLoop() == L && AR->isAffine()) {
15255 // This couldn't be folded because the operand didn't have the nsw
15256 // flag. Add the nssw flag as an assumption that we could make.
15257 const SCEV *Step = AR->getStepRecurrence(SE);
15258 Type *Ty = Expr->getType();
15259 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15260 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15261 SE.getSignExtendExpr(Step, Ty), L,
15262 AR->getNoWrapFlags());
15263 }
15264 return SE.getSignExtendExpr(Operand, Expr->getType());
15265 }
15266
15267private:
15268 explicit SCEVPredicateRewriter(
15269 const Loop *L, ScalarEvolution &SE,
15270 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15271 const SCEVPredicate *Pred)
15272 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15273
15274 bool addOverflowAssumption(const SCEVPredicate *P) {
15275 if (!NewPreds) {
15276 // Check if we've already made this assumption.
15277 return Pred && Pred->implies(P, SE);
15278 }
15279 NewPreds->push_back(P);
15280 return true;
15281 }
15282
15283 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15285 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15286 return addOverflowAssumption(A);
15287 }
15288
15289 // If \p Expr represents a PHINode, we try to see if it can be represented
15290 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15291 // to add this predicate as a runtime overflow check, we return the AddRec.
15292 // If \p Expr does not meet these conditions (is not a PHI node, or we
15293 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15294 // return \p Expr.
15295 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15296 if (!isa<PHINode>(Expr->getValue()))
15297 return Expr;
15298 std::optional<
15299 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15300 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15301 if (!PredicatedRewrite)
15302 return Expr;
15303 for (const auto *P : PredicatedRewrite->second){
15304 // Wrap predicates from outer loops are not supported.
15305 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15306 if (L != WP->getExpr()->getLoop())
15307 return Expr;
15308 }
15309 if (!addOverflowAssumption(P))
15310 return Expr;
15311 }
15312 return PredicatedRewrite->first;
15313 }
15314
15315 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15316 const SCEVPredicate *Pred;
15317 const Loop *L;
15318};
15319
15320} // end anonymous namespace
15321
15322const SCEV *
15324 const SCEVPredicate &Preds) {
15325 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15326}
15327
15329 const SCEV *S, const Loop *L,
15332 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15333 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15334
15335 if (!AddRec)
15336 return nullptr;
15337
15338 // Check if any of the transformed predicates is known to be false. In that
15339 // case, it doesn't make sense to convert to a predicated AddRec, as the
15340 // versioned loop will never execute.
15341 for (const SCEVPredicate *Pred : TransformPreds) {
15342 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15343 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15344 continue;
15345
15346 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15347 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15348 if (isa<SCEVCouldNotCompute>(ExitCount))
15349 continue;
15350
15351 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15352 if (!Step->isOne())
15353 continue;
15354
15355 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15356 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15357 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15358 return nullptr;
15359 }
15360
15361 // Since the transformation was successful, we can now transfer the SCEV
15362 // predicates.
15363 Preds.append(TransformPreds.begin(), TransformPreds.end());
15364
15365 return AddRec;
15366}
15367
15368/// SCEV predicates
15372
15374 const ICmpInst::Predicate Pred,
15375 const SCEV *LHS, const SCEV *RHS)
15376 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15377 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15378 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15379}
15380
15382 ScalarEvolution &SE) const {
15383 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15384
15385 if (!Op)
15386 return false;
15387
15388 if (Pred != ICmpInst::ICMP_EQ)
15389 return false;
15390
15391 return Op->LHS == LHS && Op->RHS == RHS;
15392}
15393
15394bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15395
15397 if (Pred == ICmpInst::ICMP_EQ)
15398 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15399 else
15400 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15401 << *RHS << "\n";
15402
15403}
15404
15406 const SCEVAddRecExpr *AR,
15407 IncrementWrapFlags Flags)
15408 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15409
15410const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15411
15413 ScalarEvolution &SE) const {
15414 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15415 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15416 return false;
15417
15418 if (Op->AR == AR)
15419 return true;
15420
15421 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15423 return false;
15424
15425 const SCEV *Start = AR->getStart();
15426 const SCEV *OpStart = Op->AR->getStart();
15427 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15428 return false;
15429
15430 // Reject pointers to different address spaces.
15431 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15432 return false;
15433
15434 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15435 // narrower-type AddRec.
15436 if (SE.getTypeSizeInBits(AR->getType()) >
15437 SE.getTypeSizeInBits(Op->AR->getType()))
15438 return false;
15439
15440 const SCEV *Step = AR->getStepRecurrence(SE);
15441 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15442 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15443 return false;
15444
15445 // If both steps are positive, this implies N, if N's start and step are
15446 // ULE/SLE (for NSUW/NSSW) than this'.
15447 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15448 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15449 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15450
15451 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15452 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15453 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15454 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15455 : SE.getNoopOrSignExtend(Start, WiderTy);
15457 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15458 SE.isKnownPredicate(Pred, OpStart, Start);
15459}
15460
15462 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15463 IncrementWrapFlags IFlags = Flags;
15464
15465 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15466 IFlags = clearFlags(IFlags, IncrementNSSW);
15467
15468 return IFlags == IncrementAnyWrap;
15469}
15470
15471void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15472 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15474 OS << "<nusw>";
15476 OS << "<nssw>";
15477 OS << "\n";
15478}
15479
15482 ScalarEvolution &SE) {
15483 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15484 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15485
15486 // We can safely transfer the NSW flag as NSSW.
15487 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15488 ImpliedFlags = IncrementNSSW;
15489
15490 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15491 // If the increment is positive, the SCEV NUW flag will also imply the
15492 // WrapPredicate NUSW flag.
15493 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15494 if (Step->getValue()->getValue().isNonNegative())
15495 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15496 }
15497
15498 return ImpliedFlags;
15499}
15500
15501/// Union predicates don't get cached so create a dummy set ID for it.
15503 ScalarEvolution &SE)
15505 for (const auto *P : Preds)
15506 add(P, SE);
15507}
15508
15510 return all_of(Preds,
15511 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15512}
15513
15515 ScalarEvolution &SE) const {
15516 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15517 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15518 return this->implies(I, SE);
15519 });
15520
15521 if (any_of(Preds,
15522 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15523 return true;
15524
15525 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15526 // equal predicates.
15527 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15528 if (!NWrap)
15529 return false;
15530 const Loop *L = NWrap->getExpr()->getLoop();
15531 return any_of(Preds, [&](const SCEVPredicate *I) {
15532 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15533 if (!IWrap)
15534 return false;
15535 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15536 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15537 return RewrittenAR &&
15538 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15539 });
15540}
15541
15543 for (const auto *Pred : Preds)
15544 Pred->print(OS, Depth);
15545}
15546
15547void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15548 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15549 for (const auto *Pred : Set->Preds)
15550 add(Pred, SE);
15551 return;
15552 }
15553
15554 // Implication checks are quadratic in the number of predicates. Stop doing
15555 // them if there are many predicates, as they should be too expensive to use
15556 // anyway at that point.
15557 bool CheckImplies = Preds.size() < 16;
15558
15559 // Only add predicate if it is not already implied by this union predicate.
15560 if (CheckImplies && implies(N, SE))
15561 return;
15562
15563 // Build a new vector containing the current predicates, except the ones that
15564 // are implied by the new predicate N.
15566 for (auto *P : Preds) {
15567 if (CheckImplies && N->implies(P, SE))
15568 continue;
15569 PrunedPreds.push_back(P);
15570 }
15571 Preds = std::move(PrunedPreds);
15572 Preds.push_back(N);
15573}
15574
15576 Loop &L)
15577 : SE(SE), L(L) {
15579 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15580}
15581
15584 for (const auto *Op : Ops)
15585 // We do not expect that forgetting cached data for SCEVConstants will ever
15586 // open any prospects for sharpening or introduce any correctness issues,
15587 // so we don't bother storing their dependencies.
15588 if (!isa<SCEVConstant>(Op))
15589 SCEVUsers[Op].insert(User);
15590}
15591
15593 for (const SCEV *Op : Ops)
15594 // We do not expect that forgetting cached data for SCEVConstants will ever
15595 // open any prospects for sharpening or introduce any correctness issues,
15596 // so we don't bother storing their dependencies.
15597 if (!isa<SCEVConstant>(Op))
15598 SCEVUsers[Op].insert(User);
15599}
15600
15602 const SCEV *Expr = SE.getSCEV(V);
15603 return getPredicatedSCEV(Expr);
15604}
15605
15607 RewriteEntry &Entry = RewriteMap[Expr];
15608
15609 // If we already have an entry and the version matches, return it.
15610 if (Entry.second && Generation == Entry.first)
15611 return Entry.second;
15612
15613 // We found an entry but it's stale. Rewrite the stale entry
15614 // according to the current predicate.
15615 if (Entry.second)
15616 Expr = Entry.second;
15617
15618 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15619 Entry = {Generation, NewSCEV};
15620
15621 return NewSCEV;
15622}
15623
15625 if (!BackedgeCount) {
15627 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15628 for (const auto *P : Preds)
15629 addPredicate(*P);
15630 }
15631 return BackedgeCount;
15632}
15633
15635 if (!SymbolicMaxBackedgeCount) {
15637 SymbolicMaxBackedgeCount =
15638 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15639 for (const auto *P : Preds)
15640 addPredicate(*P);
15641 }
15642 return SymbolicMaxBackedgeCount;
15643}
15644
15646 if (!SmallConstantMaxTripCount) {
15648 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15649 for (const auto *P : Preds)
15650 addPredicate(*P);
15651 }
15652 return *SmallConstantMaxTripCount;
15653}
15654
15656 if (Preds->implies(&Pred, SE))
15657 return;
15658
15659 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15660 NewPreds.push_back(&Pred);
15661 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15662 updateGeneration();
15663}
15664
15667 for (const SCEVPredicate *P : Preds)
15668 addPredicate(*P);
15669}
15670
15672 return *Preds;
15673}
15674
15675void PredicatedScalarEvolution::updateGeneration() {
15676 // If the generation number wrapped recompute everything.
15677 if (++Generation == 0) {
15678 for (auto &II : RewriteMap) {
15679 const SCEV *Rewritten = II.second.second;
15680 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15681 }
15682 }
15683}
15684
15687 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15688 if (!AR)
15689 return false;
15690
15692 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15693
15695}
15696
15699 const SCEV *Expr = this->getSCEV(V);
15701 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15702
15703 if (!New)
15704 return nullptr;
15705
15706 if (ExtraPreds) {
15707 ExtraPreds->append(NewPreds);
15708 return New;
15709 }
15710
15711 addPredicates(NewPreds);
15712
15713 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15714 return New;
15715}
15716
15719 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15720 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15721 SE)),
15722 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15723
15725 // For each block.
15726 for (auto *BB : L.getBlocks())
15727 for (auto &I : *BB) {
15728 if (!SE.isSCEVable(I.getType()))
15729 continue;
15730
15731 auto *Expr = SE.getSCEV(&I);
15732 auto II = RewriteMap.find(Expr);
15733
15734 if (II == RewriteMap.end())
15735 continue;
15736
15737 // Don't print things that are not interesting.
15738 if (II->second.second == Expr)
15739 continue;
15740
15741 OS.indent(Depth) << "[PSE]" << I << ":\n";
15742 OS.indent(Depth + 2) << *Expr << "\n";
15743 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15744 }
15745}
15746
15749 BasicBlock *Header = L->getHeader();
15750 BasicBlock *Pred = L->getLoopPredecessor();
15751 LoopGuards Guards(SE);
15752 if (!Pred)
15753 return Guards;
15755 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15756 return Guards;
15757}
15758
15759void ScalarEvolution::LoopGuards::collectFromPHI(
15763 unsigned Depth) {
15764 if (!SE.isSCEVable(Phi.getType()))
15765 return;
15766
15767 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15768 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15769 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15770 if (!VisitedBlocks.insert(InBlock).second)
15771 return {nullptr, scCouldNotCompute};
15772
15773 // Avoid analyzing unreachable blocks so that we don't get trapped
15774 // traversing cycles with ill-formed dominance or infinite cycles
15775 if (!SE.DT.isReachableFromEntry(InBlock))
15776 return {nullptr, scCouldNotCompute};
15777
15778 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15779 if (Inserted)
15780 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15781 Depth + 1);
15782 auto &RewriteMap = G->second.RewriteMap;
15783 if (RewriteMap.empty())
15784 return {nullptr, scCouldNotCompute};
15785 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15786 if (S == RewriteMap.end())
15787 return {nullptr, scCouldNotCompute};
15788 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15789 if (!SM)
15790 return {nullptr, scCouldNotCompute};
15791 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15792 return {C0, SM->getSCEVType()};
15793 return {nullptr, scCouldNotCompute};
15794 };
15795 auto MergeMinMaxConst = [](MinMaxPattern P1,
15796 MinMaxPattern P2) -> MinMaxPattern {
15797 auto [C1, T1] = P1;
15798 auto [C2, T2] = P2;
15799 if (!C1 || !C2 || T1 != T2)
15800 return {nullptr, scCouldNotCompute};
15801 switch (T1) {
15802 case scUMaxExpr:
15803 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15804 case scSMaxExpr:
15805 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15806 case scUMinExpr:
15807 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15808 case scSMinExpr:
15809 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15810 default:
15811 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15812 }
15813 };
15814 auto P = GetMinMaxConst(0);
15815 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15816 if (!P.first)
15817 break;
15818 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15819 }
15820 if (P.first) {
15821 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15822 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15823 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15824 Guards.RewriteMap.insert({LHS, RHS});
15825 }
15826}
15827
15828// Return a new SCEV that modifies \p Expr to the closest number divides by
15829// \p Divisor and less or equal than Expr. For now, only handle constant
15830// Expr.
15832 const APInt &DivisorVal,
15833 ScalarEvolution &SE) {
15834 const APInt *ExprVal;
15835 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15836 DivisorVal.isNonPositive())
15837 return Expr;
15838 APInt Rem = ExprVal->urem(DivisorVal);
15839 // return the SCEV: Expr - Expr % Divisor
15840 return SE.getConstant(*ExprVal - Rem);
15841}
15842
15843// Return a new SCEV that modifies \p Expr to the closest number divides by
15844// \p Divisor and greater or equal than Expr. For now, only handle constant
15845// Expr.
15846static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15847 const APInt &DivisorVal,
15848 ScalarEvolution &SE) {
15849 const APInt *ExprVal;
15850 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15851 DivisorVal.isNonPositive())
15852 return Expr;
15853 APInt Rem = ExprVal->urem(DivisorVal);
15854 if (Rem.isZero())
15855 return Expr;
15856 // return the SCEV: Expr + Divisor - Expr % Divisor
15857 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15858}
15859
15861 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15864 // If we have LHS == 0, check if LHS is computing a property of some unknown
15865 // SCEV %v which we can rewrite %v to express explicitly.
15867 return false;
15868 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15869 // explicitly express that.
15870 const SCEVUnknown *URemLHS = nullptr;
15871 const SCEV *URemRHS = nullptr;
15872 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15873 return false;
15874
15875 const SCEV *Multiple =
15876 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15877 DivInfo[URemLHS] = Multiple;
15878 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15879 Multiples[URemLHS] = C->getAPInt();
15880 return true;
15881}
15882
15883// Check if the condition is a divisibility guard (A % B == 0).
15884static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15885 ScalarEvolution &SE) {
15886 const SCEV *X, *Y;
15887 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15888}
15889
15890// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15891// recursively. This is done by aligning up/down the constant value to the
15892// Divisor.
15893static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15894 APInt Divisor,
15895 ScalarEvolution &SE) {
15896 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15897 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15898 // the non-constant operand and in \p LHS the constant operand.
15899 auto IsMinMaxSCEVWithNonNegativeConstant =
15900 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15901 const SCEV *&RHS) {
15902 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15903 if (MinMax->getNumOperands() != 2)
15904 return false;
15905 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15906 if (C->getAPInt().isNegative())
15907 return false;
15908 SCTy = MinMax->getSCEVType();
15909 LHS = MinMax->getOperand(0);
15910 RHS = MinMax->getOperand(1);
15911 return true;
15912 }
15913 }
15914 return false;
15915 };
15916
15917 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15918 SCEVTypes SCTy;
15919 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15920 MinMaxRHS))
15921 return MinMaxExpr;
15922 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15923 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15924 auto *DivisibleExpr =
15925 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15926 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15928 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15929 return SE.getMinMaxExpr(SCTy, Ops);
15930}
15931
15932void ScalarEvolution::LoopGuards::collectFromBlock(
15933 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15934 const BasicBlock *Block, const BasicBlock *Pred,
15935 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15936
15938
15939 SmallVector<SCEVUse> ExprsToRewrite;
15940 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15941 const SCEV *RHS,
15942 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15943 const LoopGuards &DivGuards) {
15944 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15945 // replacement SCEV which isn't directly implied by the structure of that
15946 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15947 // legal. See the scoping rules for flags in the header to understand why.
15948
15949 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15950 // and \p FromRewritten are the same (i.e. there has been no rewrite
15951 // registered for \p From), then puts this value in the list of rewritten
15952 // expressions.
15953 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15954 const SCEV *To) {
15955 if (From == FromRewritten)
15956 ExprsToRewrite.push_back(From);
15957 RewriteMap[From] = To;
15958 };
15959
15960 // Checks whether \p S has already been rewritten. In that case returns the
15961 // existing rewrite because we want to chain further rewrites onto the
15962 // already rewritten value. Otherwise returns \p S.
15963 auto GetMaybeRewritten = [&](const SCEV *S) {
15964 return RewriteMap.lookup_or(S, S);
15965 };
15966
15967 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15968 // create this form when combining two checks of the form (X u< C2 + C1) and
15969 // (X >=u C1).
15970 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15971 const SCEV *MatchLHS,
15972 const SCEV *MatchRHS) {
15973 const SCEVConstant *C1;
15974 const SCEVUnknown *LHSUnknown;
15975 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15976 if (!match(MatchLHS,
15977 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15978 !C2)
15979 return false;
15980
15981 auto ExactRegion =
15982 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15983 .sub(C1->getAPInt());
15984
15985 // Tighten the raw range with what we already know about LHSUnknown
15986 // from prior guards recorded in RewriteMap, or from SCEV's own range
15987 // analysis.
15988 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15989 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15991
15992 // Bail if the guard is inconsistent with prior facts, or if the range
15993 // is still not a monotonic non-wrapping interval after tightening.
15994 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15995 ExactRegion.isFullSet())
15996 return false;
15997
15998 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15999 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16000 const SCEV *ClampedLHS =
16001 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16002 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16003 return true;
16004 };
16005 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16006 return;
16007
16008 // Do not apply information for constants or if RHS contains an AddRec.
16010 return;
16011
16012 // If RHS is SCEVUnknown, make sure the information is applied to it.
16014 std::swap(LHS, RHS);
16016 }
16017
16018 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16019 // Apply divisibility information when computing the constant multiple.
16020 const APInt &DividesBy =
16021 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16022
16023 // Collect rewrites for LHS and its transitive operands based on the
16024 // condition.
16025 // For min/max expressions, also apply the guard to its operands:
16026 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16027 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16028 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16029 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16030
16031 // We cannot express strict predicates in SCEV, so instead we replace them
16032 // with non-strict ones against plus or minus one of RHS depending on the
16033 // predicate.
16034 const SCEV *One = SE.getOne(RHS->getType());
16035 switch (Predicate) {
16036 case CmpInst::ICMP_ULT:
16037 if (RHS->getType()->isPointerTy())
16038 return;
16039 RHS = SE.getUMaxExpr(RHS, One);
16040 [[fallthrough]];
16041 case CmpInst::ICMP_SLT: {
16042 RHS = SE.getMinusSCEV(RHS, One);
16043 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16044 break;
16045 }
16046 case CmpInst::ICMP_UGT:
16047 case CmpInst::ICMP_SGT:
16048 RHS = SE.getAddExpr(RHS, One);
16049 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16050 break;
16051 case CmpInst::ICMP_ULE:
16052 case CmpInst::ICMP_SLE:
16053 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16054 break;
16055 case CmpInst::ICMP_UGE:
16056 case CmpInst::ICMP_SGE:
16057 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16058 break;
16059 default:
16060 break;
16061 }
16062
16063 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16064 SmallPtrSet<const SCEV *, 16> Visited;
16065
16066 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16067 append_range(Worklist, S->operands());
16068 };
16069
16070 while (!Worklist.empty()) {
16071 const SCEV *From = Worklist.pop_back_val();
16072 if (isa<SCEVConstant>(From))
16073 continue;
16074 if (!Visited.insert(From).second)
16075 continue;
16076 const SCEV *FromRewritten = GetMaybeRewritten(From);
16077 const SCEV *To = nullptr;
16078
16079 switch (Predicate) {
16080 case CmpInst::ICMP_ULT:
16081 case CmpInst::ICMP_ULE:
16082 To = SE.getUMinExpr(FromRewritten, RHS);
16083 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16084 EnqueueOperands(UMax);
16085 break;
16086 case CmpInst::ICMP_SLT:
16087 case CmpInst::ICMP_SLE:
16088 To = SE.getSMinExpr(FromRewritten, RHS);
16089 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16090 EnqueueOperands(SMax);
16091 break;
16092 case CmpInst::ICMP_UGT:
16093 case CmpInst::ICMP_UGE:
16094 To = SE.getUMaxExpr(FromRewritten, RHS);
16095 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16096 EnqueueOperands(UMin);
16097 break;
16098 case CmpInst::ICMP_SGT:
16099 case CmpInst::ICMP_SGE:
16100 To = SE.getSMaxExpr(FromRewritten, RHS);
16101 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16102 EnqueueOperands(SMin);
16103 break;
16104 case CmpInst::ICMP_EQ:
16106 To = RHS;
16107 break;
16108 case CmpInst::ICMP_NE:
16109 if (match(RHS, m_scev_Zero())) {
16110 const SCEV *OneAlignedUp =
16111 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16112 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16113 } else {
16114 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16115 // but creating the subtraction eagerly is expensive. Track the
16116 // inequalities in a separate map, and materialize the rewrite lazily
16117 // when encountering a suitable subtraction while re-writing.
16118 if (LHS->getType()->isPointerTy()) {
16119 LHS = SE.getPtrToAddrExpr(LHS);
16120 RHS = SE.getPtrToAddrExpr(RHS);
16122 break;
16123 }
16124 const SCEVConstant *C;
16125 const SCEV *A, *B;
16128 RHS = A;
16129 LHS = B;
16130 }
16131 if (LHS > RHS)
16132 std::swap(LHS, RHS);
16133 Guards.NotEqual.insert({LHS, RHS});
16134 continue;
16135 }
16136 break;
16137 default:
16138 break;
16139 }
16140
16141 if (To)
16142 AddRewrite(From, FromRewritten, To);
16143 }
16144 };
16145
16147 // First, collect information from assumptions dominating the loop.
16148 for (auto &AssumeVH : SE.AC.assumptions()) {
16149 if (!AssumeVH)
16150 continue;
16151 auto *AssumeI = cast<CallInst>(AssumeVH);
16152 if (!SE.DT.dominates(AssumeI, Block))
16153 continue;
16154 Terms.emplace_back(AssumeI->getOperand(0), true);
16155 }
16156
16157 // Second, collect information from llvm.experimental.guards dominating the loop.
16158 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16159 SE.F.getParent(), Intrinsic::experimental_guard);
16160 if (GuardDecl)
16161 for (const auto *GU : GuardDecl->users())
16162 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16163 if (Guard->getFunction() == Block->getParent() &&
16164 SE.DT.dominates(Guard, Block))
16165 Terms.emplace_back(Guard->getArgOperand(0), true);
16166
16167 // Third, collect conditions from dominating branches. Starting at the loop
16168 // predecessor, climb up the predecessor chain, as long as there are
16169 // predecessors that can be found that have unique successors leading to the
16170 // original header.
16171 // TODO: share this logic with isLoopEntryGuardedByCond.
16172 unsigned NumCollectedConditions = 0;
16174 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16175 for (; Pair.first;
16176 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16177 VisitedBlocks.insert(Pair.second);
16178 const CondBrInst *LoopEntryPredicate =
16179 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16180 if (!LoopEntryPredicate)
16181 continue;
16182
16183 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16184 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16185 NumCollectedConditions++;
16186
16187 // If we are recursively collecting guards stop after 2
16188 // conditions to limit compile-time impact for now.
16189 if (Depth > 0 && NumCollectedConditions == 2)
16190 break;
16191 }
16192 // Finally, if we stopped climbing the predecessor chain because
16193 // there wasn't a unique one to continue, try to collect conditions
16194 // for PHINodes by recursively following all of their incoming
16195 // blocks and try to merge the found conditions to build a new one
16196 // for the Phi.
16197 if (Pair.second->hasNPredecessorsOrMore(2) &&
16199 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16200 for (auto &Phi : Pair.second->phis())
16201 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16202 }
16203
16204 // Now apply the information from the collected conditions to
16205 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16206 // earliest conditions is processed first, except guards with divisibility
16207 // information, which are moved to the back. This ensures the SCEVs with the
16208 // shortest dependency chains are constructed first.
16210 GuardsToProcess;
16211 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16212 SmallVector<Value *, 8> Worklist;
16213 SmallPtrSet<Value *, 8> Visited;
16214 Worklist.push_back(Term);
16215 while (!Worklist.empty()) {
16216 Value *Cond = Worklist.pop_back_val();
16217 if (!Visited.insert(Cond).second)
16218 continue;
16219
16220 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16221 auto Predicate =
16222 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16223 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16224 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16225 // If LHS is a constant, apply information to the other expression.
16226 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16227 // can improve results.
16228 if (isa<SCEVConstant>(LHS)) {
16229 std::swap(LHS, RHS);
16231 }
16232 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16233 continue;
16234 }
16235
16236 Value *L, *R;
16237 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16238 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16239 Worklist.push_back(L);
16240 Worklist.push_back(R);
16241 }
16242 }
16243 }
16244
16245 // Process divisibility guards in reverse order to populate DivGuards early.
16246 DenseMap<const SCEV *, APInt> Multiples;
16247 LoopGuards DivGuards(SE);
16248 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16249 if (!isDivisibilityGuard(LHS, RHS, SE))
16250 continue;
16251 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16252 Multiples, SE);
16253 }
16254
16255 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16256 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16257
16258 // Apply divisibility information last. This ensures it is applied to the
16259 // outermost expression after other rewrites for the given value.
16260 for (const auto &[K, Divisor] : Multiples) {
16261 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16262 Guards.RewriteMap[K] =
16264 Guards.rewrite(K), Divisor, SE),
16265 DivisorSCEV),
16266 DivisorSCEV);
16267 ExprsToRewrite.push_back(K);
16268 }
16269
16270 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16271 // the replacement expressions are contained in the ranges of the replaced
16272 // expressions.
16273 Guards.PreserveNUW = true;
16274 Guards.PreserveNSW = true;
16275 for (const SCEV *Expr : ExprsToRewrite) {
16276 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16277 Guards.PreserveNUW &=
16278 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16279 Guards.PreserveNSW &=
16280 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16281 }
16282
16283 // Now that all rewrite information is collect, rewrite the collected
16284 // expressions with the information in the map. This applies information to
16285 // sub-expressions.
16286 if (ExprsToRewrite.size() > 1) {
16287 for (const SCEV *Expr : ExprsToRewrite) {
16288 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16289 Guards.RewriteMap.erase(Expr);
16290 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16291 }
16292 }
16293}
16294
16296 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16297 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16298 /// replacement is loop invariant in the loop of the AddRec.
16299 class SCEVLoopGuardRewriter
16300 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16303
16305
16306 public:
16307 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16308 const ScalarEvolution::LoopGuards &Guards)
16309 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16310 NotEqual(Guards.NotEqual) {
16311 if (Guards.PreserveNUW)
16312 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16313 if (Guards.PreserveNSW)
16314 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16315 }
16316
16317 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16318
16319 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16320 return Map.lookup_or(Expr, Expr);
16321 }
16322
16323 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16324 if (const SCEV *S = Map.lookup(Expr))
16325 return S;
16326
16327 // If we didn't find the extact ZExt expr in the map, check if there's
16328 // an entry for a smaller ZExt we can use instead.
16329 Type *Ty = Expr->getType();
16330 const SCEV *Op = Expr->getOperand(0);
16331 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16332 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16333 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16334 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16335 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16336 if (const SCEV *S = Map.lookup(NarrowExt))
16337 return SE.getZeroExtendExpr(S, Ty);
16338 Bitwidth = Bitwidth / 2;
16339 }
16340
16342 Expr);
16343 }
16344
16345 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16346 if (const SCEV *S = Map.lookup(Expr))
16347 return S;
16349 Expr);
16350 }
16351
16352 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16353 if (const SCEV *S = Map.lookup(Expr))
16354 return S;
16356 }
16357
16358 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16359 if (const SCEV *S = Map.lookup(Expr))
16360 return S;
16362 }
16363
16364 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16365 if (const SCEV *S = Map.lookup(Expr))
16366 return S;
16367
16368 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16369 // return UMax(S, 1).
16370 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16371 SCEVUse LHS, RHS;
16372 if (MatchBinarySub(S, LHS, RHS)) {
16373 if (LHS > RHS)
16374 std::swap(LHS, RHS);
16375 if (NotEqual.contains({LHS, RHS})) {
16376 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16377 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16378 return SE.getUMaxExpr(OneAlignedUp, S);
16379 }
16380 }
16381 return nullptr;
16382 };
16383
16384 // Check if Expr itself is a subtraction pattern with guard info.
16385 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16386 return Rewritten;
16387
16388 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16389 // (Const + A + B). There may be guard info for A + B, and if so, apply
16390 // it.
16391 // TODO: Could more generally apply guards to Add sub-expressions.
16392 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16393 if (Expr->getNumOperands() == 3) {
16394 const SCEV *Add =
16395 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16396 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16397 return SE.getAddExpr(
16398 Expr->getOperand(0), Rewritten,
16399 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16400 if (const SCEV *S = Map.lookup(Add))
16401 return SE.getAddExpr(Expr->getOperand(0), S);
16402 }
16403
16404 // For expressions of the form (Const + A), check if we have guard info
16405 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16406 // sure we don't lose information when rewriting expressions based on
16407 // back-edge taken counts in some cases.
16408 if (Expr->getNumOperands() == 2) {
16409 const SCEV *S = nullptr;
16410 // Handle (-1 + 1 + A) without constructing SCEVs.
16411 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16412 S = Map.lookup(Expr->getOperand(1));
16413 } else {
16414 const SCEV *NewC =
16415 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16416 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16417 }
16418 if (S)
16419 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16420 }
16421 }
16423 bool Changed = false;
16424 for (SCEVUse Op : Expr->operands()) {
16425 Operands.push_back(
16427 Changed |= Op != Operands.back();
16428 }
16429 // We are only replacing operands with equivalent values, so transfer the
16430 // flags from the original expression.
16431 return !Changed ? Expr
16432 : SE.getAddExpr(Operands,
16434 Expr->getNoWrapFlags(), FlagMask));
16435 }
16436
16437 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16439 bool Changed = false;
16440 for (SCEVUse Op : Expr->operands()) {
16441 Operands.push_back(
16443 Changed |= Op != Operands.back();
16444 }
16445 // We are only replacing operands with equivalent values, so transfer the
16446 // flags from the original expression.
16447 return !Changed ? Expr
16448 : SE.getMulExpr(Operands,
16450 Expr->getNoWrapFlags(), FlagMask));
16451 }
16452 };
16453
16454 if (RewriteMap.empty() && NotEqual.empty())
16455 return Expr;
16456
16457 SCEVLoopGuardRewriter Rewriter(SE, *this);
16458 return Rewriter.visit(Expr);
16459}
16460
16461const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16462 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16463}
16464
16466 const LoopGuards &Guards) {
16467 return Guards.rewrite(Expr);
16468}
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:678
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 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:539
#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 bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
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 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 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 PHINode * getConstantEvolvingPHI(Value *V, const Loop *L)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
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 SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEV::NoWrapFlags Flags)
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< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
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 cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
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 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 SCEVUse withUseFlagsIfNotFolded(const SCEV *Res, SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags UseFlags)
Attach UseFlags to Res as use-specific flags, but only if Res really is the two-operand ExprT over LH...
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 std::optional< int > CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
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 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.
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:2007
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:463
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:358
unsigned countTrailingZeros() const
Definition APInt.h:1668
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
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:472
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1301
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1029
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:338
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:429
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
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:1497
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
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:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
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:219
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void swap(DerivedT &RHS)
Definition DenseMap.h:437
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
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:348
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:1069
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 bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
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(NoWrapFlags 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)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
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
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) 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 * 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 SCEV::NoWrapFlags, 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.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
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
SCEVNoWrapFlags NoWrapFlags
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.
static constexpr auto FlagAnyWrap
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.
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.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
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 ...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
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 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 void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
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 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 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.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
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 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 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 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.
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.
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 bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
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 const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
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...
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.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
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)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
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.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
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 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 std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
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 const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
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 forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
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.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
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 * 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 void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
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.
An instruction for storing to memory.
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:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
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:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
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:2275
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2280
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2285
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:2848
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:825
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
int getMinValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the minimum value of an extendable operand.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
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)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
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:315
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2116
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:1739
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.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
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 >
@ BinaryOp
One of the operands is a binary op.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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:2208
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 Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
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,...
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:2200
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:1746
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
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.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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...
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:383
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:2012
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:2088
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=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.
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:1917
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:2019
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:2192
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:1947
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:2146
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.
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:
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.