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);
467 void *IP = nullptr;
468 if (SCEVConstant *S =
469 static_cast<SCEVConstant *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)))
470 return Entry = S;
471 SCEVConstant *S =
472 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
473 UniqueSCEVs.InsertNode(S, IP);
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);
495 void *IP = nullptr;
496 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
497 return S;
498 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
499 UniqueSCEVs.InsertNode(S, IP);
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.RemoveNode(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.RemoveNode(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/// Return the value of this chain of recurrences at the specified iteration
974/// number. We can evaluate this recurrence by multiplying each element in the
975/// chain by the binomial coefficient corresponding to it. In other words, we
976/// can evaluate {A,+,B,+,C,+,D} as:
977///
978/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
979///
980/// where BC(It, k) stands for binomial coefficient.
982 ScalarEvolution &SE) const {
983 return evaluateAtIteration(operands(), It, SE);
984}
985
987 const SCEV *It,
988 ScalarEvolution &SE) {
989 assert(Operands.size() > 0);
990 const SCEV *Result = Operands[0].getPointer();
991 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
992 // The computation is correct in the face of overflow provided that the
993 // multiplication is performed _after_ the evaluation of the binomial
994 // coefficient.
995 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
996 if (isa<SCEVCouldNotCompute>(Coeff))
997 return Coeff;
998
999 Result =
1000 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1001 }
1002 return Result;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// SCEV Expression folder implementations
1007//===----------------------------------------------------------------------===//
1008
1009/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1010/// which computes a pointer-typed value, and rewrites the whole expression
1011/// tree so that *all* the computations are done on integers, and the only
1012/// pointer-typed operands in the expression are SCEVUnknown.
1013/// The CreatePtrCast callback is invoked to create the actual conversion
1014/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1016 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1018 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1019 Type *TargetTy;
1020 ConversionFn CreatePtrCast;
1021
1022public:
1024 ConversionFn CreatePtrCast)
1025 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1026
1027 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1028 Type *TargetTy, ConversionFn CreatePtrCast) {
1029 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1030 return Rewriter.visit(Scev);
1031 }
1032
1033 const SCEV *visit(const SCEV *S) {
1034 Type *STy = S->getType();
1035 // If the expression is not pointer-typed, just keep it as-is.
1036 if (!STy->isPointerTy())
1037 return S;
1038 // Else, recursively sink the cast down into it.
1039 return Base::visit(S);
1040 }
1041
1042 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1043 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1044 // implementation drops.
1046 bool Changed = false;
1047 for (SCEVUse Op : Expr->operands()) {
1048 Operands.push_back(visit(Op.getPointer()));
1049 Changed |= Op.getPointer() != Operands.back();
1050 }
1051 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1052 }
1053
1054 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1055 assert(Expr->getType()->isPointerTy() &&
1056 "Should only reach pointer-typed SCEVUnknown's.");
1057 // Perform some basic constant folding. If the operand of the cast is a
1058 // null pointer, don't create a cast SCEV expression (that will be left
1059 // as-is), but produce a zero constant.
1061 return SE.getZero(TargetTy);
1062 return CreatePtrCast(Expr);
1063 }
1064};
1065
1067 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1068
1069 // Treat pointers with unstable representation conservatively, since the
1070 // address bits may change.
1071 if (DL.hasUnstableRepresentation(Op->getType()))
1072 return getCouldNotCompute();
1073
1074 Type *Ty = DL.getAddressType(Op->getType());
1075
1076 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1077 // The rewriter handles null pointer constant folding.
1079 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1082 ID.AddPointer(U);
1083 ID.AddPointer(Ty);
1084 void *IP = nullptr;
1085 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1086 return S;
1087 SCEV *S = new (SCEVAllocator)
1088 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1089 UniqueSCEVs.InsertNode(S, IP);
1090 S->computeAndSetCanonical(*this);
1091 registerUser(S, U);
1092 return static_cast<const SCEV *>(S);
1093 });
1094 assert(IntOp->getType()->isIntegerTy() &&
1095 "We must have succeeded in sinking the cast, "
1096 "and ending up with an integer-typed expression!");
1097 return IntOp;
1098}
1099
1101 unsigned Depth) {
1102 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1103 "This is not a truncating conversion!");
1104 assert(isSCEVable(Ty) &&
1105 "This is not a conversion to a SCEVable type!");
1106 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1107 Ty = getEffectiveSCEVType(Ty);
1108
1111 ID.AddPointer(Op.getOpaqueValue());
1112 ID.AddPointer(Ty);
1113 void *IP = nullptr;
1114 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1115
1116 // Fold if the operand is constant.
1117 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1118 return getConstant(
1119 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1120
1121 // trunc(trunc(x)) --> trunc(x)
1123 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1124
1125 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1127 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1128
1129 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1131 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1132
1133 if (Depth > MaxCastDepth) {
1134 SCEV *S =
1135 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1136 UniqueSCEVs.InsertNode(S, IP);
1137 S->computeAndSetCanonical(*this);
1138 registerUser(S, Op);
1139 return S;
1140 }
1141
1142 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1143 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1144 // if after transforming we have at most one truncate, not counting truncates
1145 // that replace other casts.
1147 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1149 unsigned numTruncs = 0;
1150 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1151 ++i) {
1152 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1153 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1155 numTruncs++;
1156 Operands.push_back(S);
1157 }
1158 if (numTruncs < 2) {
1159 if (isa<SCEVAddExpr>(Op))
1160 return getAddExpr(Operands);
1161 if (isa<SCEVMulExpr>(Op))
1162 return getMulExpr(Operands);
1163 llvm_unreachable("Unexpected SCEV type for Op.");
1164 }
1165 // Although we checked in the beginning that ID is not in the cache, it is
1166 // possible that during recursion and different modification ID was inserted
1167 // into the cache. So if we find it, just return it.
1168 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1169 return S;
1170 }
1171
1172 // If the input value is a chrec scev, truncate the chrec's operands.
1173 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1175 for (const SCEV *Op : AddRec->operands())
1176 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1177 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1178 }
1179
1180 // Return zero if truncating to known zeros.
1181 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1182 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1183 return getZero(Ty);
1184
1185 // The cast wasn't folded; create an explicit cast node. We can reuse
1186 // the existing insert position since if we get here, we won't have
1187 // made any changes which would invalidate it.
1188 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1189 Op, Ty);
1190 UniqueSCEVs.InsertNode(S, IP);
1191 S->computeAndSetCanonical(*this);
1192 registerUser(S, Op);
1193 return S;
1194}
1195
1196// Get the limit of a recurrence such that incrementing by Step cannot cause
1197// signed overflow as long as the value of the recurrence within the
1198// loop does not exceed this limit before incrementing.
1199static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1200 ICmpInst::Predicate *Pred,
1201 ScalarEvolution *SE) {
1202 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1203 if (SE->isKnownPositive(Step)) {
1204 *Pred = ICmpInst::ICMP_SLT;
1206 SE->getSignedRangeMax(Step));
1207 }
1208 if (SE->isKnownNegative(Step)) {
1209 *Pred = ICmpInst::ICMP_SGT;
1211 SE->getSignedRangeMin(Step));
1212 }
1213 return nullptr;
1214}
1215
1216// Get the limit of a recurrence such that incrementing by Step cannot cause
1217// unsigned overflow as long as the value of the recurrence within the loop does
1218// not exceed this limit before incrementing.
1220 ICmpInst::Predicate *Pred,
1221 ScalarEvolution *SE) {
1222 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1223 *Pred = ICmpInst::ICMP_ULT;
1224
1226 SE->getUnsignedRangeMax(Step));
1227}
1228
1229namespace {
1230
1231struct ExtendOpTraitsBase {
1232 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1233 unsigned);
1234};
1235
1236// Used to make code generic over signed and unsigned overflow.
1237template <typename ExtendOp> struct ExtendOpTraits {
1238 // Members present:
1239 //
1240 // static const SCEV::NoWrapFlags WrapType;
1241 //
1242 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1243 //
1244 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1245 // ICmpInst::Predicate *Pred,
1246 // ScalarEvolution *SE);
1247};
1248
1249template <>
1250struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1251 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1252
1253 static const GetExtendExprTy GetExtendExpr;
1254
1255 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1256 ICmpInst::Predicate *Pred,
1257 ScalarEvolution *SE) {
1258 return getSignedOverflowLimitForStep(Step, Pred, SE);
1259 }
1260};
1261
1262const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1264
1265template <>
1266struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1267 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1268
1269 static const GetExtendExprTy GetExtendExpr;
1270
1271 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1272 ICmpInst::Predicate *Pred,
1273 ScalarEvolution *SE) {
1274 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1275 }
1276};
1277
1278const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1280
1281} // end anonymous namespace
1282
1283// The recurrence AR has been shown to have no signed/unsigned wrap or something
1284// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1285// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1286// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1287// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1288// expression "Step + sext/zext(PreIncAR)" is congruent with
1289// "sext/zext(PostIncAR)"
1290template <typename ExtendOpTy>
1292 ScalarEvolution *SE, unsigned Depth) {
1293 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1294 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1295
1296 const Loop *L = AR->getLoop();
1297 const SCEV *Start = AR->getStart();
1298 const SCEV *Step = AR->getStepRecurrence(*SE);
1299
1300 // Check for a simple looking step prior to loop entry.
1301 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1302 if (!SA)
1303 return nullptr;
1304
1305 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1306 // subtraction is expensive. For this purpose, perform a quick and dirty
1307 // difference, by checking for Step in the operand list. Note, that
1308 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1309 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1310 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1311 if (*It == Step) {
1312 DiffOps.erase(It);
1313 break;
1314 }
1315
1316 if (DiffOps.size() == SA->getNumOperands())
1317 return nullptr;
1318
1319 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1320 // `Step`:
1321
1322 // 1. NSW/NUW flags on the step increment.
1323 auto PreStartFlags =
1325 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1327 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1328
1329 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1330 // "S+X does not sign/unsign-overflow".
1331 //
1332
1333 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1334 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1335 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1336 return PreStart;
1337
1338 // 2. Direct overflow check on the step operation's expression.
1339 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1340 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1341 const SCEV *OperandExtendedStart =
1342 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1343 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1344 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1345 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1346 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1347 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1348 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1349 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1350 }
1351 return PreStart;
1352 }
1353
1354 // 3. Loop precondition.
1356 const SCEV *OverflowLimit =
1357 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1358
1359 if (OverflowLimit &&
1360 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1361 return PreStart;
1362
1363 return nullptr;
1364}
1365
1366// Get the normalized zero or sign extended expression for this AddRec's Start.
1367template <typename ExtendOpTy>
1368static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1369 ScalarEvolution *SE,
1370 unsigned Depth) {
1371 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1372
1373 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1374 if (!PreStart)
1375 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1376
1377 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1378 Depth),
1379 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1380}
1381
1382// Try to prove away overflow by looking at "nearby" add recurrences. A
1383// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1384// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1385//
1386// Formally:
1387//
1388// {S,+,X} == {S-T,+,X} + T
1389// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1390//
1391// If ({S-T,+,X} + T) does not overflow ... (1)
1392//
1393// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1394//
1395// If {S-T,+,X} does not overflow ... (2)
1396//
1397// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1398// == {Ext(S-T)+Ext(T),+,Ext(X)}
1399//
1400// If (S-T)+T does not overflow ... (3)
1401//
1402// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1403// == {Ext(S),+,Ext(X)} == LHS
1404//
1405// Thus, if (1), (2) and (3) are true for some T, then
1406// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1407//
1408// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1409// does not overflow" restricted to the 0th iteration. Therefore we only need
1410// to check for (1) and (2).
1411//
1412// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1413// is `Delta` (defined below).
1414template <typename ExtendOpTy>
1415bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1416 const SCEV *Step,
1417 const Loop *L) {
1418 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1419
1420 // We restrict `Start` to a constant to prevent SCEV from spending too much
1421 // time here. It is correct (but more expensive) to continue with a
1422 // non-constant `Start` and do a general SCEV subtraction to compute
1423 // `PreStart` below.
1424 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1425 if (!StartC)
1426 return false;
1427
1428 APInt StartAI = StartC->getAPInt();
1429
1430 for (unsigned Delta : {-2, -1, 1, 2}) {
1431 const SCEV *PreStart = getConstant(StartAI - Delta);
1432
1433 FoldingSetNodeID ID;
1434 ID.AddInteger(scAddRecExpr);
1435 ID.AddPointer(PreStart);
1436 ID.AddPointer(Step);
1437 ID.AddPointer(L);
1438 void *IP = nullptr;
1439 const auto *PreAR =
1440 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1441
1442 // Give up if we don't already have the add recurrence we need because
1443 // actually constructing an add recurrence is relatively expensive.
1444 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1445 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1447 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1448 DeltaS, &Pred, this);
1449 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1450 return true;
1451 }
1452 }
1453
1454 return false;
1455}
1456
1457// Finds an integer D for an expression (C + x + y + ...) such that the top
1458// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1459// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1460// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1461// the (C + x + y + ...) expression is \p WholeAddExpr.
1463 const SCEVConstant *ConstantTerm,
1464 const SCEVAddExpr *WholeAddExpr) {
1465 const APInt &C = ConstantTerm->getAPInt();
1466 const unsigned BitWidth = C.getBitWidth();
1467 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1468 uint32_t TZ = BitWidth;
1469 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1470 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1471 if (TZ) {
1472 // Set D to be as many least significant bits of C as possible while still
1473 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1474 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1475 }
1476 return APInt(BitWidth, 0);
1477}
1478
1479// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1480// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1481// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1482// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1484 const APInt &ConstantStart,
1485 const SCEV *Step) {
1486 const unsigned BitWidth = ConstantStart.getBitWidth();
1487 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1488 if (TZ)
1489 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1490 : ConstantStart;
1491 return APInt(BitWidth, 0);
1492}
1493
1495 const ScalarEvolution::FoldID &ID, const SCEV *S,
1498 &FoldCacheUser) {
1499 auto I = FoldCache.insert({ID, S});
1500 if (!I.second) {
1501 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1502 // entry.
1503 auto &UserIDs = FoldCacheUser[I.first->second];
1504 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1505 for (unsigned I = 0; I != UserIDs.size(); ++I)
1506 if (UserIDs[I] == ID) {
1507 std::swap(UserIDs[I], UserIDs.back());
1508 break;
1509 }
1510 UserIDs.pop_back();
1511 I.first->second = S;
1512 }
1513 FoldCacheUser[S].push_back(ID);
1514}
1515
1517 unsigned Depth) {
1518 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1519 "This is not an extending conversion!");
1520 assert(isSCEVable(Ty) &&
1521 "This is not a conversion to a SCEVable type!");
1522 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1523 Ty = getEffectiveSCEVType(Ty);
1524
1525 FoldID ID(scZeroExtend, Op, Ty);
1526 if (const SCEV *S = FoldCache.lookup(ID))
1527 return S;
1528
1529 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1531 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1532 return S;
1533}
1534
1536 unsigned Depth) {
1537 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1538 "This is not an extending conversion!");
1539 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1540 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1541
1542 // Fold if the operand is constant.
1543 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1544 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1545
1546 // zext(zext(x)) --> zext(x)
1548 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1549
1550 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1551 // zero-extension distributes over the recurrence.
1552 const SCEV *Start, *Step;
1553 const Loop *L;
1554 if (Depth <= MaxCastDepth &&
1555 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1556 const auto *AR = cast<SCEVAddRecExpr>(Op);
1557 if (AR->hasNoUnsignedWrap()) {
1558 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1559 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1560 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1561 }
1562 }
1563
1564 // Before doing any expensive analysis, check to see if we've already
1565 // computed a SCEV for this Op and Ty.
1568 ID.AddPointer(Op.getOpaqueValue());
1569 ID.AddPointer(Ty);
1570 void *IP = nullptr;
1571 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1572 if (Depth > MaxCastDepth) {
1573 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1574 Op, Ty);
1575 UniqueSCEVs.InsertNode(S, IP);
1576 S->computeAndSetCanonical(*this);
1577 registerUser(S, Op);
1578 return S;
1579 }
1580
1581 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1583 // It's possible the bits taken off by the truncate were all zero bits. If
1584 // so, we should be able to simplify this further.
1585 const SCEV *X = ST->getOperand();
1587 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1588 unsigned NewBits = getTypeSizeInBits(Ty);
1589 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1590 CR.zextOrTrunc(NewBits)))
1591 return getTruncateOrZeroExtend(X, Ty, Depth);
1592 }
1593
1594 // If the input value is a chrec scev, and we can prove that the value
1595 // did not overflow the old, smaller, value, we can zero extend all of the
1596 // operands (often constants). This allows analysis of something like
1597 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1598 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1599 const auto *AR = cast<SCEVAddRecExpr>(Op);
1600 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1601
1602 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1603
1604 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1605 // Note that this serves two purposes: It filters out loops that are
1606 // simply not analyzable, and it covers the case where this code is
1607 // being called from within backedge-taken count analysis, such that
1608 // attempting to ask for the backedge-taken count would likely result
1609 // in infinite recursion. In the later case, the analysis code will
1610 // cope with a conservative value, and it will take care to purge
1611 // that value once it has finished.
1612 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1613 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1614 // Manually compute the final value for AR, checking for overflow.
1615
1616 // Check whether the backedge-taken count can be losslessly casted to
1617 // the addrec's type. The count is always unsigned.
1618 const SCEV *CastedMaxBECount =
1619 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1620 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1621 CastedMaxBECount, MaxBECount->getType(), Depth);
1622 if (MaxBECount == RecastedMaxBECount) {
1623 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1624 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1625 const SCEV *ZMul =
1626 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1627 const SCEV *ZAdd = getZeroExtendExpr(
1628 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1629 Depth + 1);
1630 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1631 const SCEV *WideMaxBECount =
1632 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1633 const SCEV *OperandExtendedAdd =
1634 getAddExpr(WideStart,
1635 getMulExpr(WideMaxBECount,
1636 getZeroExtendExpr(Step, WideTy, Depth + 1),
1639 if (ZAdd == OperandExtendedAdd) {
1640 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1641 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1642 // Return the expression with the addrec on the outside.
1643 Start =
1645 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1646 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1647 }
1648 // Similar to above, only this time treat the step value as signed.
1649 // This covers loops that count down.
1650 OperandExtendedAdd =
1651 getAddExpr(WideStart,
1652 getMulExpr(WideMaxBECount,
1653 getSignExtendExpr(Step, WideTy, Depth + 1),
1656 if (ZAdd == OperandExtendedAdd) {
1657 // Cache knowledge of AR NW, which is propagated to this AddRec.
1658 // Negative step causes unsigned wrap, but it still can't self-wrap.
1659 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1660 // Return the expression with the addrec on the outside.
1661 Start =
1663 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1664 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1665 }
1666 }
1667 }
1668
1669 // Normally, in the cases we can prove no-overflow via a
1670 // backedge guarding condition, we can also compute a backedge
1671 // taken count for the loop. The exceptions are assumptions and
1672 // guards present in the loop -- SCEV is not great at exploiting
1673 // these to compute max backedge taken counts, but can still use
1674 // these to prove lack of overflow. Use this fact to avoid
1675 // doing extra work that may not pay off.
1676 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1677 !AC.assumptions().empty()) {
1678
1679 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1680 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1681 if (AR->hasNoUnsignedWrap()) {
1682 // Same as nuw case above - duplicated here to avoid a compile time
1683 // issue. It's not clear that the order of checks does matter, but
1684 // it's one of two issue possible causes for a change which was
1685 // reverted. Be conservative for the moment.
1686 Start =
1688 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1689 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1690 }
1691
1692 // For a negative step, we can extend the operands iff doing so only
1693 // traverses values in the range zext([0,UINT_MAX]).
1694 if (isKnownNegative(Step)) {
1695 const SCEV *N =
1699 // Cache knowledge of AR NW, which is propagated to this
1700 // AddRec. Negative step causes unsigned wrap, but it
1701 // still can't self-wrap.
1702 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1703 // Return the expression with the addrec on the outside.
1704 Start =
1706 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1707 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1708 }
1709 }
1710 }
1711
1712 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1713 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1714 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1715 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1716 const APInt &C = SC->getAPInt();
1717 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1718 if (D != 0) {
1719 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1720 const SCEV *SResidual =
1721 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1722 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1723 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1724 Depth + 1);
1725 }
1726 }
1727
1728 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1729 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1730 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1731 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1732 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1733 }
1734 }
1735
1736 // zext(A % B) --> zext(A) % zext(B)
1737 {
1738 const SCEV *LHS;
1739 const SCEV *RHS;
1740 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1741 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1742 getZeroExtendExpr(RHS, Ty, Depth + 1));
1743 }
1744
1745 // zext(A / B) --> zext(A) / zext(B).
1746 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1747 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1748 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1749
1750 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1751 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1752 if (SA->hasNoUnsignedWrap()) {
1753 // If the addition does not unsign overflow then we can, by definition,
1754 // commute the zero extension with the addition operation.
1756 for (SCEVUse Op : SA->operands())
1757 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1758 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1759 }
1760
1761 const APInt *C, *C2;
1762 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1763 // Currently the non-negative check is done manually, as isKnownNonNegative
1764 // is too expensive.
1765 if (SA->hasNoSignedWrap() &&
1767 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1768 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1769 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1770 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1771 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1772 SCEV::FlagNSW, Depth + 1);
1773 }
1774
1775 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1776 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1777 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1778 //
1779 // Often address arithmetics contain expressions like
1780 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1781 // This transformation is useful while proving that such expressions are
1782 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1783 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1784 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1785 if (D != 0) {
1786 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1787 const SCEV *SResidual =
1789 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1790 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1791 Depth + 1);
1792 }
1793 }
1794 }
1795
1796 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1797 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1798 if (SM->hasNoUnsignedWrap()) {
1799 // If the multiply does not unsign overflow then we can, by definition,
1800 // commute the zero extension with the multiply operation.
1802 for (SCEVUse Op : SM->operands())
1803 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1804 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1805 }
1806
1807 // zext(2^K * (trunc X to iN)) to iM ->
1808 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1809 //
1810 // Proof:
1811 //
1812 // zext(2^K * (trunc X to iN)) to iM
1813 // = zext((trunc X to iN) << K) to iM
1814 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1815 // (because shl removes the top K bits)
1816 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1817 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1818 //
1819 const APInt *C;
1820 const SCEV *TruncRHS;
1821 if (match(SM,
1822 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1823 C->isPowerOf2()) {
1824 int NewTruncBits =
1825 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1826 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1827 return getMulExpr(
1828 getZeroExtendExpr(SM->getOperand(0), Ty),
1829 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1830 SCEV::FlagNUW, Depth + 1);
1831 }
1832 }
1833
1834 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1835 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1839 for (SCEVUse Operand : MinMax->operands())
1840 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1842 return getUMinExpr(Operands);
1843 return getUMaxExpr(Operands);
1844 }
1845
1846 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1848 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1850 for (SCEVUse Operand : MinMax->operands())
1851 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1852 return getUMinExpr(Operands, /*Sequential*/ true);
1853 }
1854
1855 // The cast wasn't folded; create an explicit cast node.
1856 // Recompute the insert position, as it may have been invalidated.
1857 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1858 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1859 Op, Ty);
1860 UniqueSCEVs.InsertNode(S, IP);
1861 S->computeAndSetCanonical(*this);
1862 registerUser(S, Op);
1863 return S;
1864}
1865
1867 unsigned Depth) {
1868 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1869 "This is not an extending conversion!");
1870 assert(isSCEVable(Ty) &&
1871 "This is not a conversion to a SCEVable type!");
1872 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1873 Ty = getEffectiveSCEVType(Ty);
1874
1875 FoldID ID(scSignExtend, Op, Ty);
1876 if (const SCEV *S = FoldCache.lookup(ID))
1877 return S;
1878
1879 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1881 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1882 return S;
1883}
1884
1886 unsigned Depth) {
1887 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1888 "This is not an extending conversion!");
1889 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1890 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1891 Ty = getEffectiveSCEVType(Ty);
1892
1893 // Fold if the operand is constant.
1894 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1895 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1896
1897 // sext(sext(x)) --> sext(x)
1899 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1900
1901 // sext(zext(x)) --> zext(x)
1903 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1904
1905 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1906 // sign-extension distributes over the recurrence.
1907 const SCEV *Start, *Step;
1908 const Loop *L;
1909 if (Depth <= MaxCastDepth &&
1910 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1911 const auto *AR = cast<SCEVAddRecExpr>(Op);
1912 if (AR->hasNoSignedWrap()) {
1913 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1914 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1915 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1916 }
1917 }
1918
1919 // Before doing any expensive analysis, check to see if we've already
1920 // computed a SCEV for this Op and Ty.
1923 ID.AddPointer(Op.getOpaqueValue());
1924 ID.AddPointer(Ty);
1925 void *IP = nullptr;
1926 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1927 // Limit recursion depth.
1928 if (Depth > MaxCastDepth) {
1929 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1930 Op, Ty);
1931 UniqueSCEVs.InsertNode(S, IP);
1932 S->computeAndSetCanonical(*this);
1933 registerUser(S, Op);
1934 return S;
1935 }
1936
1937 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1939 // It's possible the bits taken off by the truncate were all sign bits. If
1940 // so, we should be able to simplify this further.
1941 const SCEV *X = ST->getOperand();
1943 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1944 unsigned NewBits = getTypeSizeInBits(Ty);
1945 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1946 CR.sextOrTrunc(NewBits)))
1947 return getTruncateOrSignExtend(X, Ty, Depth);
1948 }
1949
1950 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1951 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1952 if (SA->hasNoSignedWrap()) {
1953 // If the addition does not sign overflow then we can, by definition,
1954 // commute the sign extension with the addition operation.
1956 for (SCEVUse Op : SA->operands())
1957 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1958 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1959 }
1960
1961 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1962 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1963 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1964 //
1965 // For instance, this will bring two seemingly different expressions:
1966 // 1 + sext(5 + 20 * %x + 24 * %y) and
1967 // sext(6 + 20 * %x + 24 * %y)
1968 // to the same form:
1969 // 2 + sext(4 + 20 * %x + 24 * %y)
1970 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1971 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1972 if (D != 0) {
1973 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1974 const SCEV *SResidual =
1976 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1977 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1978 Depth + 1);
1979 }
1980 }
1981 }
1982 // If the input value is a chrec scev, and we can prove that the value
1983 // did not overflow the old, smaller, value, we can sign extend all of the
1984 // operands (often constants). This allows analysis of something like
1985 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1986 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1987 const auto *AR = cast<SCEVAddRecExpr>(Op);
1988 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1989
1990 // The no-signed-wrap case is handled before the uniquing lookup above.
1991
1992 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1993 // Note that this serves two purposes: It filters out loops that are
1994 // simply not analyzable, and it covers the case where this code is
1995 // being called from within backedge-taken count analysis, such that
1996 // attempting to ask for the backedge-taken count would likely result
1997 // in infinite recursion. In the later case, the analysis code will
1998 // cope with a conservative value, and it will take care to purge
1999 // that value once it has finished.
2000 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2001 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2002 // Manually compute the final value for AR, checking for
2003 // overflow.
2004
2005 // Check whether the backedge-taken count can be losslessly casted to
2006 // the addrec's type. The count is always unsigned.
2007 const SCEV *CastedMaxBECount =
2008 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2009 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2010 CastedMaxBECount, MaxBECount->getType(), Depth);
2011 if (MaxBECount == RecastedMaxBECount) {
2012 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2013 // Check whether Start+Step*MaxBECount has no signed overflow.
2014 const SCEV *SMul =
2015 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2016 const SCEV *SAdd = getSignExtendExpr(
2017 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2018 Depth + 1);
2019 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2020 const SCEV *WideMaxBECount =
2021 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2022 const SCEV *OperandExtendedAdd =
2023 getAddExpr(WideStart,
2024 getMulExpr(WideMaxBECount,
2025 getSignExtendExpr(Step, WideTy, Depth + 1),
2028 if (SAdd == OperandExtendedAdd) {
2029 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2030 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2031 // Return the expression with the addrec on the outside.
2032 Start =
2034 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2035 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2036 }
2037 // Similar to above, only this time treat the step value as unsigned.
2038 // This covers loops that count up with an unsigned step.
2039 OperandExtendedAdd =
2040 getAddExpr(WideStart,
2041 getMulExpr(WideMaxBECount,
2042 getZeroExtendExpr(Step, WideTy, Depth + 1),
2045 if (SAdd == OperandExtendedAdd) {
2046 // If AR wraps around then
2047 //
2048 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2049 // => SAdd != OperandExtendedAdd
2050 //
2051 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2052 // (SAdd == OperandExtendedAdd => AR is NW)
2053
2054 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2055
2056 // Return the expression with the addrec on the outside.
2057 Start =
2059 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2060 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2061 }
2062 }
2063 }
2064
2065 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2066 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2067 if (AR->hasNoSignedWrap()) {
2068 // Same as nsw case above - duplicated here to avoid a compile time
2069 // issue. It's not clear that the order of checks does matter, but
2070 // it's one of two issue possible causes for a change which was
2071 // reverted. Be conservative for the moment.
2072 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2073 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2074 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2075 }
2076
2077 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2078 // if D + (C - D + Step * n) could be proven to not signed wrap
2079 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2080 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2081 const APInt &C = SC->getAPInt();
2082 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2083 if (D != 0) {
2084 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2085 const SCEV *SResidual =
2086 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2087 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2088 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2089 Depth + 1);
2090 }
2091 }
2092
2093 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2094 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2095 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2096 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2097 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2098 }
2099 }
2100
2101 // If the input value is provably positive and we could not simplify
2102 // away the sext build a zext instead.
2104 return getZeroExtendExpr(Op, Ty, Depth + 1);
2105
2106 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2107 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2111 for (SCEVUse Operand : MinMax->operands())
2112 Operands.push_back(getSignExtendExpr(Operand, Ty));
2114 return getSMinExpr(Operands);
2115 return getSMaxExpr(Operands);
2116 }
2117
2118 // The cast wasn't folded; create an explicit cast node.
2119 // Recompute the insert position, as it may have been invalidated.
2120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2121 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2122 Op, Ty);
2123 UniqueSCEVs.InsertNode(S, IP);
2124 S->computeAndSetCanonical(*this);
2125 registerUser(S, Op);
2126 return S;
2127}
2128
2130 switch (Kind) {
2131 case scTruncate:
2132 return getTruncateExpr(Op, Ty);
2133 case scZeroExtend:
2134 return getZeroExtendExpr(Op, Ty);
2135 case scSignExtend:
2136 return getSignExtendExpr(Op, Ty);
2137 case scPtrToAddr: {
2138 const SCEV *Expr = getPtrToAddrExpr(Op);
2139 assert(Expr->getType() == Ty && "requested type must match");
2140 return Expr;
2141 }
2142 default:
2143 llvm_unreachable("Not a SCEV cast expression!");
2144 }
2145}
2146
2147/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2148/// unspecified bits out to the given type.
2150 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2151 "This is not an extending conversion!");
2152 assert(isSCEVable(Ty) &&
2153 "This is not a conversion to a SCEVable type!");
2154 Ty = getEffectiveSCEVType(Ty);
2155
2156 // Sign-extend negative constants.
2157 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2158 if (SC->getAPInt().isNegative())
2159 return getSignExtendExpr(Op, Ty);
2160
2161 // Peel off a truncate cast.
2163 const SCEV *NewOp = T->getOperand();
2164 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2165 return getAnyExtendExpr(NewOp, Ty);
2166 return getTruncateOrNoop(NewOp, Ty);
2167 }
2168
2169 // Next try a zext cast. If the cast is folded, use it.
2170 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2171 if (!isa<SCEVZeroExtendExpr>(ZExt))
2172 return ZExt;
2173
2174 // Next try a sext cast. If the cast is folded, use it.
2175 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2176 if (!isa<SCEVSignExtendExpr>(SExt))
2177 return SExt;
2178
2179 // Force the cast to be folded into the operands of an addrec.
2180 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2182 for (const SCEV *Op : AR->operands())
2183 Ops.push_back(getAnyExtendExpr(Op, Ty));
2184 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2185 }
2186
2187 // If the expression is obviously signed, use the sext cast value.
2188 if (isa<SCEVSMaxExpr>(Op))
2189 return SExt;
2190
2191 // Absent any other information, use the zext cast value.
2192 return ZExt;
2193}
2194
2195/// Process the given Ops list, which is a list of operands to be added under
2196/// the given scale, update the given map. This is a helper function for
2197/// getAddRecExpr. As an example of what it does, given a sequence of operands
2198/// that would form an add expression like this:
2199///
2200/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2201///
2202/// where A and B are constants, update the map with these values:
2203///
2204/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2205///
2206/// and add 13 + A*B*29 to AccumulatedConstant.
2207/// This will allow getAddRecExpr to produce this:
2208///
2209/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2210///
2211/// This form often exposes folding opportunities that are hidden in
2212/// the original operand list.
2213///
2214/// Return true iff it appears that any interesting folding opportunities
2215/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2216/// the common case where no interesting opportunities are present, and
2217/// is also used as a check to avoid infinite recursion.
2220 APInt &AccumulatedConstant,
2222 const APInt &Scale,
2223 ScalarEvolution &SE) {
2224 bool Interesting = false;
2225
2226 // Iterate over the add operands. They are sorted, with constants first.
2227 unsigned i = 0;
2228 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2229 ++i;
2230 // Pull a buried constant out to the outside.
2231 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2232 Interesting = true;
2233 AccumulatedConstant += Scale * C->getAPInt();
2234 }
2235
2236 // Next comes everything else. We're especially interested in multiplies
2237 // here, but they're in the middle, so just visit the rest with one loop.
2238 for (; i != Ops.size(); ++i) {
2240 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2241 APInt NewScale =
2242 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2243 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2244 // A multiplication of a constant with another add; recurse.
2245 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2246 Interesting |= CollectAddOperandsWithScales(
2247 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2248 } else {
2249 // A multiplication of a constant with some other value. Update
2250 // the map.
2251 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2252 const SCEV *Key = SE.getMulExpr(MulOps);
2253 auto Pair = M.insert({Key, NewScale});
2254 if (Pair.second) {
2255 NewOps.push_back(Pair.first->first);
2256 } else {
2257 Pair.first->second += NewScale;
2258 // The map already had an entry for this value, which may indicate
2259 // a folding opportunity.
2260 Interesting = true;
2261 }
2262 }
2263 } else {
2264 // An ordinary operand. Update the map.
2265 auto Pair = M.insert({Ops[i], Scale});
2266 if (Pair.second) {
2267 NewOps.push_back(Pair.first->first);
2268 } else {
2269 Pair.first->second += Scale;
2270 // The map already had an entry for this value, which may indicate
2271 // a folding opportunity.
2272 Interesting = true;
2273 }
2274 }
2275 }
2276
2277 return Interesting;
2278}
2279
2281 const SCEV *LHS, const SCEV *RHS,
2282 const Instruction *CtxI) {
2284 unsigned);
2285 switch (BinOp) {
2286 default:
2287 llvm_unreachable("Unsupported binary op");
2288 case Instruction::Add:
2290 break;
2291 case Instruction::Sub:
2293 break;
2294 case Instruction::Mul:
2296 break;
2297 }
2298
2299 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2302
2303 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2304 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2305 auto *WideTy =
2306 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2307
2308 const SCEV *A = (this->*Extension)(
2309 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2310 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2311 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2312 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2313 if (A == B)
2314 return true;
2315 // Can we use context to prove the fact we need?
2316 if (!CtxI)
2317 return false;
2318 // TODO: Support mul.
2319 if (BinOp == Instruction::Mul)
2320 return false;
2321 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2322 // TODO: Lift this limitation.
2323 if (!RHSC)
2324 return false;
2325 APInt C = RHSC->getAPInt();
2326 unsigned NumBits = C.getBitWidth();
2327 bool IsSub = (BinOp == Instruction::Sub);
2328 bool IsNegativeConst = (Signed && C.isNegative());
2329 // Compute the direction and magnitude by which we need to check overflow.
2330 bool OverflowDown = IsSub ^ IsNegativeConst;
2331 APInt Magnitude = C;
2332 if (IsNegativeConst) {
2333 if (C == APInt::getSignedMinValue(NumBits))
2334 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2335 // want to deal with that.
2336 return false;
2337 Magnitude = -C;
2338 }
2339
2341 if (OverflowDown) {
2342 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2343 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2344 : APInt::getMinValue(NumBits);
2345 APInt Limit = Min + Magnitude;
2346 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2347 } else {
2348 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2349 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2350 : APInt::getMaxValue(NumBits);
2351 APInt Limit = Max - Magnitude;
2352 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2353 }
2354}
2355
2356std::optional<SCEV::NoWrapFlags>
2358 const OverflowingBinaryOperator *OBO) {
2359 // It cannot be done any better.
2360 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2361 return std::nullopt;
2362
2363 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2364
2365 if (OBO->hasNoUnsignedWrap())
2367 if (OBO->hasNoSignedWrap())
2369
2370 bool Deduced = false;
2371
2373 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2374 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2375
2376 bool CanUseNSW = true;
2377 const APInt *ShiftAmt;
2378 // Treat `shl %a, C` as `mul %a, 1 << C`.
2379 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2380 unsigned BitWidth = ShiftAmt->getBitWidth();
2381 if (ShiftAmt->uge(BitWidth))
2382 return std::nullopt;
2383 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2384 // overflows.
2385 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2386 Opcode = Instruction::Mul;
2388 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2389 Opcode != Instruction::Mul) {
2390 return std::nullopt;
2391 }
2392
2393 const Instruction *CtxI =
2395 if (!OBO->hasNoUnsignedWrap() &&
2396 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2398 Deduced = true;
2399 }
2400
2401 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2402 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2404 Deduced = true;
2405 }
2406
2407 if (Deduced)
2408 return Flags;
2409 return std::nullopt;
2410}
2411
2412// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2413// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2414// can't-overflow flags for the operation if possible.
2418 SCEV::NoWrapFlags Flags) {
2419 using namespace std::placeholders;
2420
2421 using OBO = OverflowingBinaryOperator;
2422
2423 bool CanAnalyze =
2425 (void)CanAnalyze;
2426 assert(CanAnalyze && "don't call from other places!");
2427
2428 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2429 SCEV::NoWrapFlags SignOrUnsignWrap =
2430 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2431
2432 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2433 auto IsKnownNonNegative = [&](SCEVUse U) {
2434 return SE->isKnownNonNegative(U);
2435 };
2436
2437 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2438 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2439
2440 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2441
2442 if (SignOrUnsignWrap != SignOrUnsignMask &&
2443 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2444 isa<SCEVConstant>(Ops[0])) {
2445
2446 auto Opcode = [&] {
2447 switch (Type) {
2448 case scAddExpr:
2449 return Instruction::Add;
2450 case scMulExpr:
2451 return Instruction::Mul;
2452 default:
2453 llvm_unreachable("Unexpected SCEV op.");
2454 }
2455 }();
2456
2457 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2458
2459 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2460 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2462 Opcode, C, OBO::NoSignedWrap);
2463 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2465 }
2466
2467 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2468 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2470 Opcode, C, OBO::NoUnsignedWrap);
2471 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2473 }
2474 }
2475
2476 // <0,+,nonnegative><nw> is also nuw
2477 // TODO: Add corresponding nsw case
2479 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2480 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2482
2483 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2485 Ops.size() == 2) {
2486 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2487 if (UDiv->getOperand(1) == Ops[1])
2489 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2490 if (UDiv->getOperand(1) == Ops[0])
2492 }
2493
2494 return Flags;
2495}
2496
2498 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2499}
2500
2501/// Get a canonical add expression, or something simpler if possible.
2503 SCEV::NoWrapFlags OrigFlags,
2504 unsigned Depth) {
2505 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2506 "only nuw or nsw allowed");
2507 assert(!Ops.empty() && "Cannot get empty add!");
2508 if (Ops.size() == 1) return Ops[0];
2509#ifndef NDEBUG
2510 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2511 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2512 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2513 "SCEVAddExpr operand types don't match!");
2514 unsigned NumPtrs = count_if(
2515 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2516 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2517#endif
2518
2519 const SCEV *Folded = constantFoldAndGroupOps(
2520 *this, LI, DT, Ops,
2521 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2522 [](const APInt &C) { return C.isZero(); }, // identity
2523 [](const APInt &C) { return false; }); // absorber
2524 if (Folded)
2525 return Folded;
2526
2527 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2528
2529 // Delay expensive flag strengthening until necessary.
2530 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2531 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2532 };
2533
2534 // Limit recursion calls depth.
2536 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2537
2538 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2539 // Don't strengthen flags if we have no new information.
2540 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2541 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2542 Add->setNoWrapFlags(ComputeFlags(Ops));
2543 return S;
2544 }
2545
2546 // Okay, check to see if the same value occurs in the operand list more than
2547 // once. If so, merge them together into an multiply expression. Since we
2548 // sorted the list, these values are required to be adjacent.
2549 Type *Ty = Ops[0]->getType();
2550 bool FoundMatch = false;
2551 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2552 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2553 // Scan ahead to count how many equal operands there are.
2554 unsigned Count = 2;
2555 while (i+Count != e && Ops[i+Count] == Ops[i])
2556 ++Count;
2557 // Merge the values into a multiply.
2558 SCEVUse Scale = getConstant(Ty, Count);
2559 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2560 if (Ops.size() == Count)
2561 return Mul;
2562 Ops[i] = Mul;
2563 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2564 --i; e -= Count - 1;
2565 FoundMatch = true;
2566 }
2567 if (FoundMatch)
2568 return getAddExpr(Ops, OrigFlags, Depth + 1);
2569
2570 // Check for truncates. If all the operands are truncated from the same
2571 // type, see if factoring out the truncate would permit the result to be
2572 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2573 // if the contents of the resulting outer trunc fold to something simple.
2574 auto FindTruncSrcType = [&]() -> Type * {
2575 // We're ultimately looking to fold an addrec of truncs and muls of only
2576 // constants and truncs, so if we find any other types of SCEV
2577 // as operands of the addrec then we bail and return nullptr here.
2578 // Otherwise, we return the type of the operand of a trunc that we find.
2579 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2580 return T->getOperand()->getType();
2581 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2582 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2583 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2584 return T->getOperand()->getType();
2585 }
2586 return nullptr;
2587 };
2588 if (auto *SrcType = FindTruncSrcType()) {
2589 SmallVector<SCEVUse, 8> LargeOps;
2590 bool Ok = true;
2591 // Check all the operands to see if they can be represented in the
2592 // source type of the truncate.
2593 for (const SCEV *Op : Ops) {
2595 if (T->getOperand()->getType() != SrcType) {
2596 Ok = false;
2597 break;
2598 }
2599 LargeOps.push_back(T->getOperand());
2600 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2601 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2602 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2603 SmallVector<SCEVUse, 8> LargeMulOps;
2604 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2605 if (const SCEVTruncateExpr *T =
2606 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2607 if (T->getOperand()->getType() != SrcType) {
2608 Ok = false;
2609 break;
2610 }
2611 LargeMulOps.push_back(T->getOperand());
2612 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2613 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2614 } else {
2615 Ok = false;
2616 break;
2617 }
2618 }
2619 if (Ok)
2620 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2621 } else {
2622 Ok = false;
2623 break;
2624 }
2625 }
2626 if (Ok) {
2627 // Evaluate the expression in the larger type.
2628 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2629 // If it folds to something simple, use it. Otherwise, don't.
2630 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2631 return getTruncateExpr(Fold, Ty);
2632 }
2633 }
2634
2635 if (Ops.size() == 2) {
2636 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2637 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2638 // C1).
2639 const SCEV *A = Ops[0];
2640 const SCEV *B = Ops[1];
2641 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2642 auto *C = dyn_cast<SCEVConstant>(A);
2643 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2644 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2645 auto C2 = C->getAPInt();
2646 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2647
2648 APInt ConstAdd = C1 + C2;
2649 auto AddFlags = AddExpr->getNoWrapFlags();
2650 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2652 ConstAdd.ule(C1)) {
2653 PreservedFlags =
2655 }
2656
2657 // Adding a constant with the same sign and small magnitude is NSW, if the
2658 // original AddExpr was NSW.
2660 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2661 ConstAdd.abs().ule(C1.abs())) {
2662 PreservedFlags =
2664 }
2665
2666 if (PreservedFlags != SCEV::FlagAnyWrap) {
2667 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2668 NewOps[0] = getConstant(ConstAdd);
2669 return getAddExpr(NewOps, PreservedFlags);
2670 }
2671 }
2672
2673 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2674 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2675 const SCEVAddExpr *InnerAdd;
2676 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2677 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2678 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2679 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2680 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2682 SCEV::FlagNUW)) {
2683 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2684 }
2685 }
2686 }
2687
2688 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2689 const SCEV *Y;
2690 if (Ops.size() == 2 &&
2691 match(Ops[0],
2693 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2694 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2695
2696 // Skip past any other cast SCEVs.
2697 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2698 ++Idx;
2699
2700 // If there are add operands they would be next.
2701 if (Idx < Ops.size()) {
2702 bool DeletedAdd = false;
2703 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2704 // common NUW flag for expression after inlining. Other flags cannot be
2705 // preserved, because they may depend on the original order of operations.
2706 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2707 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2708 if (Ops.size() > AddOpsInlineThreshold ||
2709 Add->getNumOperands() > AddOpsInlineThreshold)
2710 break;
2711 // If we have an add, expand the add operands onto the end of the operands
2712 // list.
2713 Ops.erase(Ops.begin()+Idx);
2714 append_range(Ops, Add->operands());
2715 DeletedAdd = true;
2716 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2717 }
2718
2719 // If we deleted at least one add, we added operands to the end of the list,
2720 // and they are not necessarily sorted. Recurse to resort and resimplify
2721 // any operands we just acquired.
2722 if (DeletedAdd)
2723 return getAddExpr(Ops, CommonFlags, Depth + 1);
2724 }
2725
2726 // Skip over the add expression until we get to a multiply.
2727 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2728 ++Idx;
2729
2730 // Check to see if there are any folding opportunities present with
2731 // operands multiplied by constant values.
2732 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2733 uint64_t BitWidth = getTypeSizeInBits(Ty);
2736 APInt AccumulatedConstant(BitWidth, 0);
2737 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2738 Ops, APInt(BitWidth, 1), *this)) {
2739 struct APIntCompare {
2740 bool operator()(const APInt &LHS, const APInt &RHS) const {
2741 return LHS.ult(RHS);
2742 }
2743 };
2744
2745 // Some interesting folding opportunity is present, so its worthwhile to
2746 // re-generate the operands list. Group the operands by constant scale,
2747 // to avoid multiplying by the same constant scale multiple times.
2748 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2749 for (const SCEV *NewOp : NewOps)
2750 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2751 // Re-generate the operands list.
2752 Ops.clear();
2753 if (AccumulatedConstant != 0)
2754 Ops.push_back(getConstant(AccumulatedConstant));
2755 for (auto &MulOp : MulOpLists) {
2756 if (MulOp.first == 1) {
2757 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2758 } else if (MulOp.first != 0) {
2759 Ops.push_back(getMulExpr(
2760 getConstant(MulOp.first),
2761 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2762 SCEV::FlagAnyWrap, Depth + 1));
2763 }
2764 }
2765 if (Ops.empty())
2766 return getZero(Ty);
2767 if (Ops.size() == 1)
2768 return Ops[0];
2769 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2770 }
2771 }
2772
2773 // Given a SCEVMulExpr and an operand index, return the product of all
2774 // operands except the one at OpIdx.
2775 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2776 if (M->getNumOperands() == 2)
2777 return M->getOperand(OpIdx == 0);
2778 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2779 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2780 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2781 };
2782
2783 // If we are adding something to a multiply expression, make sure the
2784 // something is not already an operand of the multiply. If so, merge it into
2785 // the multiply.
2786 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2787 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2788 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2789 // Scan all terms to find every occurrence of common factor MulOpSCEV
2790 // and fold them in one shot:
2791 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2792 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2793 if (isa<SCEVConstant>(MulOpSCEV))
2794 continue;
2795
2796 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2797 // remaining product for multiply terms containing MulOpSCEV.
2798 SmallVector<SCEVUse, 4> Cofactors;
2799 SmallVector<unsigned, 4> DeadIndices;
2800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2801 if (MulOpSCEV == Ops[AddOp]) {
2802 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2803 Cofactors.push_back(getOne(Ty));
2804 DeadIndices.push_back(AddOp);
2805 continue;
2806 }
2807
2808 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2809 continue;
2810
2811 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2812 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2813 ++OMulOp) {
2814 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2815 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2816 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2817 DeadIndices.push_back(AddOp);
2818 break;
2819 }
2820 }
2821 }
2822
2823 // Fold all collected cofactors with the anchor multiply's cofactor:
2824 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2825 if (!Cofactors.empty()) {
2826 Cofactors.push_back(StripFactor(Mul, MulOp));
2827
2828 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2829 SCEVUse OuterMul =
2830 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2831
2832 // DeadIndices does not include Idx (the anchor), hence +1.
2833 if (Ops.size() == DeadIndices.size() + 1)
2834 return OuterMul;
2835
2836 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2837 // The -1 adjustment accounts for the shift from removing Idx;
2838 // reverse order means each erasure only shifts later positions,
2839 // which have already been processed.
2840 Ops.erase(Ops.begin() + Idx);
2841 for (unsigned Dead : reverse(DeadIndices))
2842 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2843
2844 Ops.push_back(OuterMul);
2845 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2846 }
2847 }
2848 }
2849
2850 // If there are any add recurrences in the operands list, see if any other
2851 // added values are loop invariant. If so, we can fold them into the
2852 // recurrence.
2853 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2854 ++Idx;
2855
2856 // Scan over all recurrences, trying to fold loop invariants into them.
2857 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2858 // Scan all of the other operands to this add and add them to the vector if
2859 // they are loop invariant w.r.t. the recurrence.
2861 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2862 const Loop *AddRecLoop = AddRec->getLoop();
2863 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2864 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2865 LIOps.push_back(Ops[i]);
2866 Ops.erase(Ops.begin()+i);
2867 --i; --e;
2868 }
2869
2870 // If we found some loop invariants, fold them into the recurrence.
2871 if (!LIOps.empty()) {
2872 // Compute nowrap flags for the addition of the loop-invariant ops and
2873 // the addrec. Temporarily push it as an operand for that purpose. These
2874 // flags are valid in the scope of the addrec only.
2875 LIOps.push_back(AddRec);
2876 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
2877 LIOps.pop_back();
2878
2879 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2880 LIOps.push_back(AddRec->getStart());
2881
2882 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2883
2884 // It is not in general safe to propagate flags valid on an add within
2885 // the addrec scope to one outside it. We must prove that the inner
2886 // scope is guaranteed to execute if the outer one does to be able to
2887 // safely propagate. We know the program is undefined if poison is
2888 // produced on the inner scoped addrec. We also know that *for this use*
2889 // the outer scoped add can't overflow (because of the flags we just
2890 // computed for the inner scoped add) without the program being undefined.
2891 // Proving that entry to the outer scope neccesitates entry to the inner
2892 // scope, thus proves the program undefined if the flags would be violated
2893 // in the outer scope.
2894 SCEV::NoWrapFlags AddFlags = Flags;
2895 if (AddFlags != SCEV::FlagAnyWrap) {
2896 auto *DefI = getDefiningScopeBound(LIOps);
2897 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2898 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2899 AddFlags = SCEV::FlagAnyWrap;
2900 }
2901 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2902
2903 // Build the new addrec. Propagate the NUW and NSW flags if both the
2904 // outer add and the inner addrec are guaranteed to have no overflow.
2905 // Always propagate NW.
2906 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2907 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2908
2909 // If all of the other operands were loop invariant, we are done.
2910 if (Ops.size() == 1) return NewRec;
2911
2912 // Otherwise, add the folded AddRec by the non-invariant parts.
2913 for (unsigned i = 0;; ++i)
2914 if (Ops[i] == AddRec) {
2915 Ops[i] = NewRec;
2916 break;
2917 }
2918 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2919 }
2920
2921 // Okay, if there weren't any loop invariants to be folded, check to see if
2922 // there are multiple AddRec's with the same loop induction variable being
2923 // added together. If so, we can fold them.
2924 for (unsigned OtherIdx = Idx+1;
2925 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2926 ++OtherIdx) {
2927 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2928 // so that the 1st found AddRecExpr is dominated by all others.
2929 assert(DT.dominates(
2930 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2931 AddRec->getLoop()->getHeader()) &&
2932 "AddRecExprs are not sorted in reverse dominance order?");
2933 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2934 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2935 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2936 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2937 ++OtherIdx) {
2938 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2939 if (OtherAddRec->getLoop() == AddRecLoop) {
2940 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2941 i != e; ++i) {
2942 if (i >= AddRecOps.size()) {
2943 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2944 break;
2945 }
2946 AddRecOps[i] =
2947 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2949 }
2950 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2951 }
2952 }
2953 // Step size has changed, so we cannot guarantee no self-wraparound.
2954 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2955 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2956 }
2957 }
2958
2959 // Otherwise couldn't fold anything into this recurrence. Move onto the
2960 // next one.
2961 }
2962
2963 // Okay, it looks like we really DO need an add expr. Check to see if we
2964 // already have one, otherwise create a new one.
2965 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2966}
2967
2968const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2969 SCEV::NoWrapFlags Flags) {
2972 for (SCEVUse Op : Ops)
2973 ID.AddPointer(Op.getOpaqueValue());
2974 void *IP = nullptr;
2975 SCEVAddExpr *S =
2976 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2977 if (!S) {
2978 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2980 S = new (SCEVAllocator)
2981 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2982 UniqueSCEVs.InsertNode(S, IP);
2983 S->computeAndSetCanonical(*this);
2984 registerUser(S, Ops);
2985 }
2986 S->setNoWrapFlags(Flags);
2987 return S;
2988}
2989
2990const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2991 const Loop *L,
2992 SCEV::NoWrapFlags Flags) {
2993 FoldingSetNodeID ID;
2994 ID.AddInteger(scAddRecExpr);
2995 for (SCEVUse Op : Ops)
2996 ID.AddPointer(Op.getOpaqueValue());
2997 ID.AddPointer(L);
2998 void *IP = nullptr;
2999 SCEVAddRecExpr *S =
3000 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3001 if (!S) {
3002 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3004 S = new (SCEVAllocator)
3005 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3006 UniqueSCEVs.InsertNode(S, IP);
3007 S->computeAndSetCanonical(*this);
3008 LoopUsers[L].push_back(S);
3009 registerUser(S, Ops);
3010 }
3011 setNoWrapFlags(S, Flags);
3012 return S;
3013}
3014
3015const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3016 SCEV::NoWrapFlags Flags) {
3017 FoldingSetNodeID ID;
3018 ID.AddInteger(scMulExpr);
3019 for (SCEVUse Op : Ops)
3020 ID.AddPointer(Op.getOpaqueValue());
3021 void *IP = nullptr;
3022 SCEVMulExpr *S =
3023 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3024 if (!S) {
3025 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3027 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3028 O, Ops.size());
3029 UniqueSCEVs.InsertNode(S, IP);
3030 S->computeAndSetCanonical(*this);
3031 registerUser(S, Ops);
3032 }
3033 S->setNoWrapFlags(Flags);
3034 return S;
3035}
3036
3037const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3038 FoldingSetNodeID ID;
3039 ID.AddInteger(scUDivExpr);
3040 ID.AddPointer(LHS.getOpaqueValue());
3041 ID.AddPointer(RHS.getOpaqueValue());
3042 void *IP = nullptr;
3043 SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3044 if (!S) {
3045 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3046 UniqueSCEVs.InsertNode(S, IP);
3047 S->computeAndSetCanonical(*this);
3049 }
3050 return S;
3051}
3052
3053static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3054 uint64_t k = i*j;
3055 if (j > 1 && k / j != i) Overflow = true;
3056 return k;
3057}
3058
3059/// Compute the result of "n choose k", the binomial coefficient. If an
3060/// intermediate computation overflows, Overflow will be set and the return will
3061/// be garbage. Overflow is not cleared on absence of overflow.
3062static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3063 // We use the multiplicative formula:
3064 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3065 // At each iteration, we take the n-th term of the numeral and divide by the
3066 // (k-n)th term of the denominator. This division will always produce an
3067 // integral result, and helps reduce the chance of overflow in the
3068 // intermediate computations. However, we can still overflow even when the
3069 // final result would fit.
3070
3071 if (n == 0 || n == k) return 1;
3072 if (k > n) return 0;
3073
3074 if (k > n/2)
3075 k = n-k;
3076
3077 uint64_t r = 1;
3078 for (uint64_t i = 1; i <= k; ++i) {
3079 r = umul_ov(r, n-(i-1), Overflow);
3080 r /= i;
3081 }
3082 return r;
3083}
3084
3085/// Determine if any of the operands in this SCEV are a constant or if
3086/// any of the add or multiply expressions in this SCEV contain a constant.
3087static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3088 struct FindConstantInAddMulChain {
3089 bool FoundConstant = false;
3090
3091 bool follow(const SCEV *S) {
3092 FoundConstant |= isa<SCEVConstant>(S);
3093 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3094 }
3095
3096 bool isDone() const {
3097 return FoundConstant;
3098 }
3099 };
3100
3101 FindConstantInAddMulChain F;
3103 ST.visitAll(StartExpr);
3104 return F.FoundConstant;
3105}
3106
3107/// Get a canonical multiply expression, or something simpler if possible.
3109 SCEV::NoWrapFlags OrigFlags,
3110 unsigned Depth) {
3111 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3112 "only nuw or nsw allowed");
3113 assert(!Ops.empty() && "Cannot get empty mul!");
3114 if (Ops.size() == 1) return Ops[0];
3115#ifndef NDEBUG
3116 Type *ETy = Ops[0]->getType();
3117 assert(!ETy->isPointerTy());
3118 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3119 assert(Ops[i]->getType() == ETy &&
3120 "SCEVMulExpr operand types don't match!");
3121#endif
3122
3123 const SCEV *Folded = constantFoldAndGroupOps(
3124 *this, LI, DT, Ops,
3125 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3126 [](const APInt &C) { return C.isOne(); }, // identity
3127 [](const APInt &C) { return C.isZero(); }); // absorber
3128 if (Folded)
3129 return Folded;
3130
3131 // Delay expensive flag strengthening until necessary.
3132 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3133 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3134 };
3135
3136 // Limit recursion calls depth.
3138 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3139
3140 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3141 // Don't strengthen flags if we have no new information.
3142 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3143 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3144 Mul->setNoWrapFlags(ComputeFlags(Ops));
3145 return S;
3146 }
3147
3148 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3149 if (Ops.size() == 2) {
3150 // C1*(C2+V) -> C1*C2 + C1*V
3151 // If any of Add's ops are Adds or Muls with a constant, apply this
3152 // transformation as well.
3153 //
3154 // TODO: There are some cases where this transformation is not
3155 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3156 // this transformation should be narrowed down.
3157 const SCEV *Op0, *Op1;
3158 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3160 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3161 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3162 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3163 }
3164
3165 if (Ops[0]->isAllOnesValue()) {
3166 // If we have a mul by -1 of an add, try distributing the -1 among the
3167 // add operands.
3168 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3170 bool AnyFolded = false;
3171 for (const SCEV *AddOp : Add->operands()) {
3172 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3174 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3175 NewOps.push_back(Mul);
3176 }
3177 if (AnyFolded)
3178 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3179 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3180 // Negation preserves a recurrence's no self-wrap property.
3182 for (const SCEV *AddRecOp : AddRec->operands())
3183 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3184 SCEV::FlagAnyWrap, Depth + 1));
3185 // Let M be the minimum representable signed value. AddRec with nsw
3186 // multiplied by -1 can have signed overflow if and only if it takes a
3187 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3188 // maximum signed value. In all other cases signed overflow is
3189 // impossible.
3190 auto FlagsMask = SCEV::FlagNW;
3191 if (AddRec->hasNoSignedWrap()) {
3192 auto MinInt =
3193 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3194 if (getSignedRangeMin(AddRec) != MinInt)
3195 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3196 }
3197 return getAddRecExpr(Operands, AddRec->getLoop(),
3198 AddRec->getNoWrapFlags(FlagsMask));
3199 }
3200 }
3201
3202 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3203 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3204 const SCEVAddExpr *InnerAdd;
3205 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3206 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3207 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3208 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3209 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3211 SCEV::FlagNUW)) {
3212 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3213 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3214 };
3215 }
3216
3217 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3218 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3219 // of C1, fold to (D /u (C2 /u C1)).
3220 const SCEV *D;
3221 APInt C1V = LHSC->getAPInt();
3222 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3223 // as -1 * 1, as it won't enable additional folds.
3224 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3225 C1V = C1V.abs();
3226 const SCEVConstant *C2;
3227 if (C1V.isPowerOf2() &&
3229 C2->getAPInt().isPowerOf2() &&
3230 C1V.logBase2() <= getMinTrailingZeros(D)) {
3231 const SCEV *NewMul = nullptr;
3232 if (C1V.uge(C2->getAPInt())) {
3233 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3234 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3235 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3236 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3237 }
3238 if (NewMul)
3239 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3240 }
3241 }
3242 }
3243
3244 // Skip over the add expression until we get to a multiply.
3245 unsigned Idx = 0;
3246 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3247 ++Idx;
3248
3249 // If there are mul operands inline them all into this expression.
3250 if (Idx < Ops.size()) {
3251 bool DeletedMul = false;
3252 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3253 if (Ops.size() > MulOpsInlineThreshold)
3254 break;
3255 // If we have an mul, expand the mul operands onto the end of the
3256 // operands list.
3257 Ops.erase(Ops.begin()+Idx);
3258 append_range(Ops, Mul->operands());
3259 DeletedMul = true;
3260 }
3261
3262 // If we deleted at least one mul, we added operands to the end of the
3263 // list, and they are not necessarily sorted. Recurse to resort and
3264 // resimplify any operands we just acquired.
3265 if (DeletedMul)
3266 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3267 }
3268
3269 // If there are any add recurrences in the operands list, see if any other
3270 // added values are loop invariant. If so, we can fold them into the
3271 // recurrence.
3272 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3273 ++Idx;
3274
3275 // Scan over all recurrences, trying to fold loop invariants into them.
3276 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3277 // Scan all of the other operands to this mul and add them to the vector
3278 // if they are loop invariant w.r.t. the recurrence.
3280 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3281 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3282 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3283 LIOps.push_back(Ops[i]);
3284 Ops.erase(Ops.begin()+i);
3285 --i; --e;
3286 }
3287
3288 // If we found some loop invariants, fold them into the recurrence.
3289 if (!LIOps.empty()) {
3290 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3292 NewOps.reserve(AddRec->getNumOperands());
3293 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3294
3295 // If both the mul and addrec are nuw, we can preserve nuw.
3296 // If both the mul and addrec are nsw, we can only preserve nsw if either
3297 // a) they are also nuw, or
3298 // b) all multiplications of addrec operands with scale are nsw.
3299 SCEV::NoWrapFlags Flags =
3300 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3301
3302 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3303 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3304 SCEV::FlagAnyWrap, Depth + 1));
3305
3306 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3308 Instruction::Mul, getSignedRange(Scale),
3310 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3311 Flags = clearFlags(Flags, SCEV::FlagNSW);
3312 }
3313 }
3314
3315 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3316
3317 // If all of the other operands were loop invariant, we are done.
3318 if (Ops.size() == 1) return NewRec;
3319
3320 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3321 for (unsigned i = 0;; ++i)
3322 if (Ops[i] == AddRec) {
3323 Ops[i] = NewRec;
3324 break;
3325 }
3326 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3327 }
3328
3329 // Okay, if there weren't any loop invariants to be folded, check to see
3330 // if there are multiple AddRec's with the same loop induction variable
3331 // being multiplied together. If so, we can fold them.
3332
3333 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3334 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3335 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3336 // ]]],+,...up to x=2n}.
3337 // Note that the arguments to choose() are always integers with values
3338 // known at compile time, never SCEV objects.
3339 //
3340 // The implementation avoids pointless extra computations when the two
3341 // addrec's are of different length (mathematically, it's equivalent to
3342 // an infinite stream of zeros on the right).
3343 bool OpsModified = false;
3344 for (unsigned OtherIdx = Idx+1;
3345 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3346 ++OtherIdx) {
3347 const SCEVAddRecExpr *OtherAddRec =
3348 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3349 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3350 continue;
3351
3352 // Limit max number of arguments to avoid creation of unreasonably big
3353 // SCEVAddRecs with very complex operands.
3354 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3355 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3356 continue;
3357
3358 bool Overflow = false;
3359 Type *Ty = AddRec->getType();
3360 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3361 SmallVector<SCEVUse, 7> AddRecOps;
3362 for (int x = 0, xe = AddRec->getNumOperands() +
3363 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3365 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3366 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3367 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3368 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3369 z < ze && !Overflow; ++z) {
3370 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3371 uint64_t Coeff;
3372 if (LargerThan64Bits)
3373 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3374 else
3375 Coeff = Coeff1*Coeff2;
3376 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3377 const SCEV *Term1 = AddRec->getOperand(y-z);
3378 const SCEV *Term2 = OtherAddRec->getOperand(z);
3379 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3380 SCEV::FlagAnyWrap, Depth + 1));
3381 }
3382 }
3383 if (SumOps.empty())
3384 SumOps.push_back(getZero(Ty));
3385 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3386 }
3387 if (!Overflow) {
3388 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3390 if (Ops.size() == 2) return NewAddRec;
3391 Ops[Idx] = NewAddRec;
3392 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3393 OpsModified = true;
3394 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3395 if (!AddRec)
3396 break;
3397 }
3398 }
3399 if (OpsModified)
3400 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3401
3402 // Otherwise couldn't fold anything into this recurrence. Move onto the
3403 // next one.
3404 }
3405
3406 // Okay, it looks like we really DO need an mul expr. Check to see if we
3407 // already have one, otherwise create a new one.
3408 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3409}
3410
3411/// Represents an unsigned remainder expression based on unsigned division.
3413 assert(getEffectiveSCEVType(LHS->getType()) ==
3414 getEffectiveSCEVType(RHS->getType()) &&
3415 "SCEVURemExpr operand types don't match!");
3416
3417 // Short-circuit easy cases
3418 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3419 // If constant is one, the result is trivial
3420 if (RHSC->getValue()->isOne())
3421 return getZero(LHS->getType()); // X urem 1 --> 0
3422
3423 // If constant is a power of two, fold into a zext(trunc(LHS)).
3424 if (RHSC->getAPInt().isPowerOf2()) {
3425 Type *FullTy = LHS->getType();
3426 Type *TruncTy =
3427 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3428 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3429 }
3430 }
3431
3432 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3433 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3434 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3435 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3436}
3437
3438/// Get a canonical unsigned division expression, or something simpler if
3439/// possible.
3441 assert(!LHS->getType()->isPointerTy() &&
3442 "SCEVUDivExpr operand can't be pointer!");
3443 assert(LHS->getType() == RHS->getType() &&
3444 "SCEVUDivExpr operand types don't match!");
3445
3446 if (SCEV *S =
3447 findExistingSCEVInCache(scUDivExpr, ArrayRef<SCEVUse>({LHS, RHS})))
3448 return S;
3449
3450 // 0 udiv Y == 0
3451 if (match(LHS, m_scev_Zero()))
3452 return LHS;
3453
3454 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3455 if (RHSC->getValue()->isOne())
3456 return LHS; // X udiv 1 --> x
3457 // If the denominator is zero, the result of the udiv is undefined. Don't
3458 // try to analyze it, because the resolution chosen here may differ from
3459 // the resolution chosen in other parts of the compiler.
3460 if (!RHSC->getValue()->isZero()) {
3461 // Determine if the division can be folded into the operands of
3462 // its operands.
3463 // TODO: Generalize this to non-constants by using known-bits information.
3464 Type *Ty = LHS->getType();
3465 unsigned LZ = RHSC->getAPInt().countl_zero();
3466 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3467 // For non-power-of-two values, effectively round the value up to the
3468 // nearest power of two.
3469 if (!RHSC->getAPInt().isPowerOf2())
3470 ++MaxShiftAmt;
3471 IntegerType *ExtTy =
3472 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3473 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3474 if (const SCEVConstant *Step =
3475 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3476 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3477 const APInt &StepInt = Step->getAPInt();
3478 const APInt &DivInt = RHSC->getAPInt();
3479 if (!StepInt.urem(DivInt) &&
3480 getZeroExtendExpr(AR, ExtTy) ==
3481 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3482 getZeroExtendExpr(Step, ExtTy),
3483 AR->getLoop(), SCEV::FlagAnyWrap)) {
3485 for (const SCEV *Op : AR->operands())
3486 Operands.push_back(getUDivExpr(Op, RHS));
3487 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3488 }
3489 /// Get a canonical UDivExpr for a recurrence.
3490 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3491 const APInt *StartRem;
3492 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3493 m_scev_APInt(StartRem))) {
3494 bool NoWrap =
3495 getZeroExtendExpr(AR, ExtTy) ==
3496 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3497 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3499
3500 // With N <= C and both N, C as powers-of-2, the transformation
3501 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3502 // if wrapping occurs, as the division results remain equivalent for
3503 // all offsets in [[(X - X%N), X).
3504 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3505 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3506 // Only fold if the subtraction can be folded in the start
3507 // expression.
3508 const SCEV *NewStart =
3509 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3510 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3511 !isa<SCEVAddExpr>(NewStart)) {
3512 const SCEV *NewLHS =
3513 getAddRecExpr(NewStart, Step, AR->getLoop(),
3514 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3515 if (LHS != NewLHS)
3516 return getUDivExpr(NewLHS, RHS);
3517 }
3518 }
3519 }
3520 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3521 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3522 if (M->hasNoUnsignedWrap()) {
3523 // Find an operand that's safely divisible.
3524 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3525 const SCEV *Op = M->getOperand(i);
3526 const SCEV *Div = getUDivExpr(Op, RHSC);
3527 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3528 SmallVector<SCEVUse, 4> Operands(M->operands());
3529 Operands[i] = Div;
3530 return getMulExpr(Operands);
3531 }
3532 }
3533
3534 // Even if it's not divisible, try to remove a common factor.
3535 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3536 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3537 RHSC->getAPInt());
3538 if (!Factor.isIntN(1)) {
3539 SmallVector<SCEVUse, 2> NewOperands;
3540 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3541 append_range(NewOperands, M->operands().drop_front());
3542 const SCEV *NewMul = getMulExpr(NewOperands);
3543 return getUDivExpr(NewMul,
3544 getConstant(RHSC->getAPInt().udiv(Factor)));
3545 }
3546 }
3547 }
3548 }
3549
3550 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3551 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3552 if (auto *DivisorConstant =
3553 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3554 bool Overflow = false;
3555 APInt NewRHS =
3556 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3557 if (Overflow) {
3558 return getConstant(RHSC->getType(), 0, false);
3559 }
3560 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3561 }
3562 }
3563
3564 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3565 // B/C can be folded.
3566 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3567 if (A->hasNoUnsignedWrap()) {
3569 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3570 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3571 if (isa<SCEVUDivExpr>(Op) ||
3572 getMulExpr(Op, RHS) != A->getOperand(i))
3573 break;
3574 Operands.push_back(Op);
3575 }
3576 if (Operands.size() == A->getNumOperands())
3577 return getAddExpr(Operands);
3578 }
3579 }
3580
3581 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3582 // This is an idiom for rounding A up to the next multiple of N, where A
3583 // is aready known to be a multiple of M. In this case, instcombine can
3584 // see that some low bits of the added constant are unused, so can clear
3585 // them, but we want to canonicalise to set the low bits. This makes the
3586 // pattern easier to match, without needing to check for known bits in
3587 // A*M.
3588 const APInt &N = RHSC->getAPInt();
3589 const APInt *NMinusM, *M;
3590 const SCEV *A;
3591 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3592 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3593 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3594 *NMinusM == N - *M) {
3595 return getUDivExpr(
3597 RHS);
3598 }
3599 }
3600
3601 // Fold if both operands are constant.
3602 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3603 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3604 }
3605 }
3606
3607 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3608 const APInt *NegC, *C;
3609 if (match(LHS,
3612 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3613 return getZero(LHS->getType());
3614
3615 // (%a * %b)<nuw> / %b -> %a
3616 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3617 if (Mul && Mul->hasNoUnsignedWrap()) {
3618 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3619 if (Mul->getOperand(i) == RHS) {
3621 append_range(Operands, Mul->operands().take_front(i));
3622 append_range(Operands, Mul->operands().drop_front(i + 1));
3623 return getMulExpr(Operands);
3624 }
3625 }
3626 }
3627
3628 // TODO: Generalize to handle any common factors.
3629 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3630 const SCEV *NewLHS, *NewRHS;
3631 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3632 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3633 return getUDivExpr(NewLHS, NewRHS);
3634
3635 return getOrCreateUDivExpr(LHS, RHS);
3636}
3637
3638/// Get a canonical unsigned division expression, or something simpler if
3639/// possible. There is no representation for an exact udiv in SCEV IR, but we
3640/// can attempt to optimize it prior to construction.
3642 // Currently there is no exact specific logic.
3643
3644 return getUDivExpr(LHS, RHS);
3645}
3646
3647/// Get an add recurrence expression for the specified loop. Simplify the
3648/// expression as much as possible.
3650 const Loop *L,
3651 SCEV::NoWrapFlags Flags) {
3653 Operands.push_back(Start);
3654 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3655 if (StepChrec->getLoop() == L) {
3656 append_range(Operands, StepChrec->operands());
3657 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3658 }
3659
3660 Operands.push_back(Step);
3661 return getAddRecExpr(Operands, L, Flags);
3662}
3663
3664/// Get an add recurrence expression for the specified loop. Simplify the
3665/// expression as much as possible.
3667 const Loop *L,
3668 SCEV::NoWrapFlags Flags) {
3669 if (Operands.size() == 1) return Operands[0];
3670#ifndef NDEBUG
3672 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3673 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3674 "SCEVAddRecExpr operand types don't match!");
3675 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3676 }
3677 for (const SCEV *Op : Operands)
3679 "SCEVAddRecExpr operand is not available at loop entry!");
3680#endif
3681
3682 if (Operands.back()->isZero()) {
3683 Operands.pop_back();
3684 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3685 }
3686
3687 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3688 // use that information to infer NUW and NSW flags. However, computing a
3689 // BE count requires calling getAddRecExpr, so we may not yet have a
3690 // meaningful BE count at this point (and if we don't, we'd be stuck
3691 // with a SCEVCouldNotCompute as the cached BE count).
3692
3693 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3694
3695 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3696 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3697 const Loop *NestedLoop = NestedAR->getLoop();
3698 if (L->contains(NestedLoop)
3699 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3700 : (!NestedLoop->contains(L) &&
3701 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3702 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3703 Operands[0] = NestedAR->getStart();
3704 // AddRecs require their operands be loop-invariant with respect to their
3705 // loops. Don't perform this transformation if it would break this
3706 // requirement.
3707 bool AllInvariant = all_of(
3708 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3709
3710 if (AllInvariant) {
3711 // Create a recurrence for the outer loop with the same step size.
3712 //
3713 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3714 // inner recurrence has the same property.
3715 SCEV::NoWrapFlags OuterFlags =
3716 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3717
3718 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3719 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3720 return isLoopInvariant(Op, NestedLoop);
3721 });
3722
3723 if (AllInvariant) {
3724 // Ok, both add recurrences are valid after the transformation.
3725 //
3726 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3727 // the outer recurrence has the same property.
3728 SCEV::NoWrapFlags InnerFlags =
3729 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3730 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3731 }
3732 }
3733 // Reset Operands to its original state.
3734 Operands[0] = NestedAR;
3735 }
3736 }
3737
3738 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3739 // already have one, otherwise create a new one.
3740 return getOrCreateAddRecExpr(Operands, L, Flags);
3741}
3742
3744 ArrayRef<SCEVUse> IndexExprs) {
3745 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3746 // getSCEV(Base)->getType() has the same address space as Base->getType()
3747 // because SCEV::getType() preserves the address space.
3748 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3749 if (NW != GEPNoWrapFlags::none()) {
3750 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3751 // but to do that, we have to ensure that said flag is valid in the entire
3752 // defined scope of the SCEV.
3753 // TODO: non-instructions have global scope. We might be able to prove
3754 // some global scope cases
3755 auto *GEPI = dyn_cast<Instruction>(GEP);
3756 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3757 NW = GEPNoWrapFlags::none();
3758 }
3759
3760 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3761}
3762
3764 ArrayRef<SCEVUse> IndexExprs,
3765 Type *SrcElementTy, GEPNoWrapFlags NW) {
3767 if (NW.hasNoUnsignedSignedWrap())
3768 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3769 if (NW.hasNoUnsignedWrap())
3770 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3771
3772 Type *CurTy = BaseExpr->getType();
3773 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3774 bool FirstIter = true;
3776 for (SCEVUse IndexExpr : IndexExprs) {
3777 // Compute the (potentially symbolic) offset in bytes for this index.
3778 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3779 // For a struct, add the member offset.
3780 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3781 unsigned FieldNo = Index->getZExtValue();
3782 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3783 Offsets.push_back(FieldOffset);
3784
3785 // Update CurTy to the type of the field at Index.
3786 CurTy = STy->getTypeAtIndex(Index);
3787 } else {
3788 // Update CurTy to its element type.
3789 if (FirstIter) {
3790 assert(isa<PointerType>(CurTy) &&
3791 "The first index of a GEP indexes a pointer");
3792 CurTy = SrcElementTy;
3793 FirstIter = false;
3794 } else {
3795 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3796 }
3797 // For an array, add the element offset, explicitly scaled.
3798 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3799 // Getelementptr indices are signed.
3800 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3801
3802 // Multiply the index by the element size to compute the element offset.
3803 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3804 Offsets.push_back(LocalOffset);
3805 }
3806 }
3807
3808 // Handle degenerate case of GEP without offsets.
3809 if (Offsets.empty())
3810 return BaseExpr;
3811
3812 // Add the offsets together, assuming nsw if inbounds.
3813 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3814 // Add the base address and the offset. We cannot use the nsw flag, as the
3815 // base address is unsigned. However, if we know that the offset is
3816 // non-negative, we can use nuw.
3817 bool NUW = NW.hasNoUnsignedWrap() ||
3820 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3821 assert(BaseExpr->getType() == GEPExpr->getType() &&
3822 "GEP should not change type mid-flight.");
3823 return GEPExpr;
3824}
3825
3826SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3829 ID.AddInteger(SCEVType);
3830 for (SCEVUse Op : Ops)
3831 ID.AddPointer(Op.getOpaqueValue());
3832 void *IP = nullptr;
3833 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3834}
3835
3836const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3838 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3839}
3840
3843 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3844 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3845 if (Ops.size() == 1) return Ops[0];
3846#ifndef NDEBUG
3847 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3848 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3849 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3850 "Operand types don't match!");
3851 assert(Ops[0]->getType()->isPointerTy() ==
3852 Ops[i]->getType()->isPointerTy() &&
3853 "min/max should be consistently pointerish");
3854 }
3855#endif
3856
3857 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3858 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3859
3860 const SCEV *Folded = constantFoldAndGroupOps(
3861 *this, LI, DT, Ops,
3862 [&](const APInt &C1, const APInt &C2) {
3863 switch (Kind) {
3864 case scSMaxExpr:
3865 return APIntOps::smax(C1, C2);
3866 case scSMinExpr:
3867 return APIntOps::smin(C1, C2);
3868 case scUMaxExpr:
3869 return APIntOps::umax(C1, C2);
3870 case scUMinExpr:
3871 return APIntOps::umin(C1, C2);
3872 default:
3873 llvm_unreachable("Unknown SCEV min/max opcode");
3874 }
3875 },
3876 [&](const APInt &C) {
3877 // identity
3878 if (IsMax)
3879 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3880 else
3881 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3882 },
3883 [&](const APInt &C) {
3884 // absorber
3885 if (IsMax)
3886 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3887 else
3888 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3889 });
3890 if (Folded)
3891 return Folded;
3892
3893 // Check if we have created the same expression before.
3894 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3895 return S;
3896 }
3897
3898 // Find the first operation of the same kind
3899 unsigned Idx = 0;
3900 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3901 ++Idx;
3902
3903 // Check to see if one of the operands is of the same kind. If so, expand its
3904 // operands onto our operand list, and recurse to simplify.
3905 if (Idx < Ops.size()) {
3906 bool DeletedAny = false;
3907 while (Ops[Idx]->getSCEVType() == Kind) {
3908 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3909 Ops.erase(Ops.begin()+Idx);
3910 append_range(Ops, SMME->operands());
3911 DeletedAny = true;
3912 }
3913
3914 if (DeletedAny)
3915 return getMinMaxExpr(Kind, Ops);
3916 }
3917
3918 // Okay, check to see if the same value occurs in the operand list twice. If
3919 // so, delete one. Since we sorted the list, these values are required to
3920 // be adjacent.
3925 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3926 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3927 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3928 if (Ops[i] == Ops[i + 1] ||
3929 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3930 // X op Y op Y --> X op Y
3931 // X op Y --> X, if we know X, Y are ordered appropriately
3932 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3933 --i;
3934 --e;
3935 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3936 Ops[i + 1])) {
3937 // X op Y --> Y, if we know X, Y are ordered appropriately
3938 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3939 --i;
3940 --e;
3941 }
3942 }
3943
3944 if (Ops.size() == 1) return Ops[0];
3945
3946 assert(!Ops.empty() && "Reduced smax down to nothing!");
3947
3948 // Okay, it looks like we really DO need an expr. Check to see if we
3949 // already have one, otherwise create a new one.
3951 ID.AddInteger(Kind);
3952 for (SCEVUse Op : Ops)
3953 ID.AddPointer(Op.getOpaqueValue());
3954 void *IP = nullptr;
3955 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3956 if (ExistingSCEV)
3957 return ExistingSCEV;
3958 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3960 SCEV *S = new (SCEVAllocator)
3961 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3962
3963 UniqueSCEVs.InsertNode(S, IP);
3964 S->computeAndSetCanonical(*this);
3965 registerUser(S, Ops);
3966 return S;
3967}
3968
3969namespace {
3970
3971class SCEVSequentialMinMaxDeduplicatingVisitor final
3972 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3973 std::optional<const SCEV *>> {
3974 using RetVal = std::optional<const SCEV *>;
3976
3977 ScalarEvolution &SE;
3978 const SCEVTypes RootKind; // Must be a sequential min/max expression.
3979 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
3981
3982 bool canRecurseInto(SCEVTypes Kind) const {
3983 // We can only recurse into the SCEV expression of the same effective type
3984 // as the type of our root SCEV expression.
3985 return RootKind == Kind || NonSequentialRootKind == Kind;
3986 };
3987
3988 RetVal visitAnyMinMaxExpr(const SCEV *S) {
3990 "Only for min/max expressions.");
3991 SCEVTypes Kind = S->getSCEVType();
3992
3993 if (!canRecurseInto(Kind))
3994 return S;
3995
3996 auto *NAry = cast<SCEVNAryExpr>(S);
3997 SmallVector<SCEVUse> NewOps;
3998 bool Changed = visit(Kind, NAry->operands(), NewOps);
3999
4000 if (!Changed)
4001 return S;
4002 if (NewOps.empty())
4003 return std::nullopt;
4004
4006 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4007 : SE.getMinMaxExpr(Kind, NewOps);
4008 }
4009
4010 RetVal visit(const SCEV *S) {
4011 // Has the whole operand been seen already?
4012 if (!SeenOps.insert(S).second)
4013 return std::nullopt;
4014 return Base::visit(S);
4015 }
4016
4017public:
4018 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4019 SCEVTypes RootKind)
4020 : SE(SE), RootKind(RootKind),
4021 NonSequentialRootKind(
4022 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4023 RootKind)) {}
4024
4025 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4026 SmallVectorImpl<SCEVUse> &NewOps) {
4027 bool Changed = false;
4029 Ops.reserve(OrigOps.size());
4030
4031 for (const SCEV *Op : OrigOps) {
4032 RetVal NewOp = visit(Op);
4033 if (NewOp != Op)
4034 Changed = true;
4035 if (NewOp)
4036 Ops.emplace_back(*NewOp);
4037 }
4038
4039 if (Changed)
4040 NewOps = std::move(Ops);
4041 return Changed;
4042 }
4043
4044 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4045
4046 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4047
4048 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4049
4050 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4051
4052 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4053
4054 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4055
4056 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4057
4058 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4059
4060 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4061
4062 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4063
4064 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4065 return visitAnyMinMaxExpr(Expr);
4066 }
4067
4068 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4069 return visitAnyMinMaxExpr(Expr);
4070 }
4071
4072 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4073 return visitAnyMinMaxExpr(Expr);
4074 }
4075
4076 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4077 return visitAnyMinMaxExpr(Expr);
4078 }
4079
4080 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4081 return visitAnyMinMaxExpr(Expr);
4082 }
4083
4084 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4085
4086 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4087};
4088
4089} // namespace
4090
4092 switch (Kind) {
4093 case scConstant:
4094 case scVScale:
4095 case scTruncate:
4096 case scZeroExtend:
4097 case scSignExtend:
4098 case scPtrToAddr:
4099 case scAddExpr:
4100 case scMulExpr:
4101 case scUDivExpr:
4102 case scAddRecExpr:
4103 case scUMaxExpr:
4104 case scSMaxExpr:
4105 case scUMinExpr:
4106 case scSMinExpr:
4107 case scUnknown:
4108 // If any operand is poison, the whole expression is poison.
4109 return true;
4111 // FIXME: if the *first* operand is poison, the whole expression is poison.
4112 return false; // Pessimistically, say that it does not propagate poison.
4113 case scCouldNotCompute:
4114 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4115 }
4116 llvm_unreachable("Unknown SCEV kind!");
4117}
4118
4119namespace {
4120// The only way poison may be introduced in a SCEV expression is from a
4121// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4122// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4123// introduce poison -- they encode guaranteed, non-speculated knowledge.
4124//
4125// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4126// with the notable exception of umin_seq, where only poison from the first
4127// operand is (unconditionally) propagated.
4128struct SCEVPoisonCollector {
4129 bool LookThroughMaybePoisonBlocking;
4130 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4131 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4132 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4133
4134 bool follow(const SCEV *S) {
4135 if (!LookThroughMaybePoisonBlocking &&
4137 return false;
4138
4139 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4140 if (!isGuaranteedNotToBePoison(SU->getValue()))
4141 MaybePoison.insert(SU);
4142 }
4143 return true;
4144 }
4145 bool isDone() const { return false; }
4146};
4147} // namespace
4148
4149/// Return true if V is poison given that AssumedPoison is already poison.
4150static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4151 // First collect all SCEVs that might result in AssumedPoison to be poison.
4152 // We need to look through potentially poison-blocking operations here,
4153 // because we want to find all SCEVs that *might* result in poison, not only
4154 // those that are *required* to.
4155 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4156 visitAll(AssumedPoison, PC1);
4157
4158 // AssumedPoison is never poison. As the assumption is false, the implication
4159 // is true. Don't bother walking the other SCEV in this case.
4160 if (PC1.MaybePoison.empty())
4161 return true;
4162
4163 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4164 // as well. We cannot look through potentially poison-blocking operations
4165 // here, as their arguments only *may* make the result poison.
4166 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4167 visitAll(S, PC2);
4168
4169 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4170 // it will also make S poison by being part of PC2.MaybePoison.
4171 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4172}
4173
4175 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4176 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4177 visitAll(S, PC);
4178 for (const SCEVUnknown *SU : PC.MaybePoison)
4179 Result.insert(SU->getValue());
4180}
4181
4183 const SCEV *S, Instruction *I,
4184 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4185 // If the instruction cannot be poison, it's always safe to reuse.
4187 return true;
4188
4189 // Otherwise, it is possible that I is more poisonous that S. Collect the
4190 // poison-contributors of S, and then check whether I has any additional
4191 // poison-contributors. Poison that is contributed through poison-generating
4192 // flags is handled by dropping those flags instead.
4194 getPoisonGeneratingValues(PoisonVals, S);
4195
4196 SmallVector<Value *> Worklist;
4198 Worklist.push_back(I);
4199 while (!Worklist.empty()) {
4200 Value *V = Worklist.pop_back_val();
4201 if (!Visited.insert(V).second)
4202 continue;
4203
4204 // Avoid walking large instruction graphs.
4205 if (Visited.size() > 16)
4206 return false;
4207
4208 // Either the value can't be poison, or the S would also be poison if it
4209 // is.
4210 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4211 continue;
4212
4213 auto *I = dyn_cast<Instruction>(V);
4214 if (!I)
4215 return false;
4216
4217 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4218 // can't replace an arbitrary add with disjoint or, even if we drop the
4219 // flag. We would need to convert the or into an add.
4220 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4221 if (PDI->isDisjoint())
4222 return false;
4223
4224 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4225 // because SCEV currently assumes it can't be poison. Remove this special
4226 // case once we proper model when vscale can be poison.
4227 if (auto *II = dyn_cast<IntrinsicInst>(I);
4228 II && II->getIntrinsicID() == Intrinsic::vscale)
4229 continue;
4230
4231 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4232 return false;
4233
4234 // If the instruction can't create poison, we can recurse to its operands.
4235 if (I->hasPoisonGeneratingAnnotations())
4236 DropPoisonGeneratingInsts.push_back(I);
4237
4238 llvm::append_range(Worklist, I->operands());
4239 }
4240 return true;
4241}
4242
4243const SCEV *
4246 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4247 "Not a SCEVSequentialMinMaxExpr!");
4248 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4249 if (Ops.size() == 1)
4250 return Ops[0];
4251#ifndef NDEBUG
4252 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4253 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4254 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4255 "Operand types don't match!");
4256 assert(Ops[0]->getType()->isPointerTy() ==
4257 Ops[i]->getType()->isPointerTy() &&
4258 "min/max should be consistently pointerish");
4259 }
4260#endif
4261
4262 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4263 // so we can *NOT* do any kind of sorting of the expressions!
4264
4265 // Check if we have created the same expression before.
4266 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4267 return S;
4268
4269 // FIXME: there are *some* simplifications that we can do here.
4270
4271 // Keep only the first instance of an operand.
4272 {
4273 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4274 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4275 if (Changed)
4276 return getSequentialMinMaxExpr(Kind, Ops);
4277 }
4278
4279 // Check to see if one of the operands is of the same kind. If so, expand its
4280 // operands onto our operand list, and recurse to simplify.
4281 {
4282 unsigned Idx = 0;
4283 bool DeletedAny = false;
4284 while (Idx < Ops.size()) {
4285 if (Ops[Idx]->getSCEVType() != Kind) {
4286 ++Idx;
4287 continue;
4288 }
4289 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4290 Ops.erase(Ops.begin() + Idx);
4291 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4292 SMME->operands().end());
4293 DeletedAny = true;
4294 }
4295
4296 if (DeletedAny)
4297 return getSequentialMinMaxExpr(Kind, Ops);
4298 }
4299
4300 const SCEV *SaturationPoint;
4302 switch (Kind) {
4304 SaturationPoint = getZero(Ops[0]->getType());
4305 Pred = ICmpInst::ICMP_ULE;
4306 break;
4307 default:
4308 llvm_unreachable("Not a sequential min/max type.");
4309 }
4310
4311 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4312 if (!isGuaranteedNotToCauseUB(Ops[i]))
4313 continue;
4314 // We can replace %x umin_seq %y with %x umin %y if either:
4315 // * %y being poison implies %x is also poison.
4316 // * %x cannot be the saturating value (e.g. zero for umin).
4317 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4318 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4319 SaturationPoint)) {
4320 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4321 Ops[i - 1] = getMinMaxExpr(
4323 SeqOps);
4324 Ops.erase(Ops.begin() + i);
4325 return getSequentialMinMaxExpr(Kind, Ops);
4326 }
4327 // Fold %x umin_seq %y to %x if %x ule %y.
4328 // TODO: We might be able to prove the predicate for a later operand.
4329 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4330 Ops.erase(Ops.begin() + i);
4331 return getSequentialMinMaxExpr(Kind, Ops);
4332 }
4333 }
4334
4335 // Okay, it looks like we really DO need an expr. Check to see if we
4336 // already have one, otherwise create a new one.
4338 ID.AddInteger(Kind);
4339 for (SCEVUse Op : Ops)
4340 ID.AddPointer(Op.getOpaqueValue());
4341 void *IP = nullptr;
4342 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4343 if (ExistingSCEV)
4344 return ExistingSCEV;
4345
4346 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4348 SCEV *S = new (SCEVAllocator)
4349 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4350
4351 UniqueSCEVs.InsertNode(S, IP);
4352 S->computeAndSetCanonical(*this);
4353 registerUser(S, Ops);
4354 return S;
4355}
4356
4361
4365
4370
4374
4379
4383
4385 bool Sequential) {
4386 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4387 return getUMinExpr(Ops, Sequential);
4388}
4389
4395
4396const SCEV *
4398 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4399 if (Size.isScalable())
4400 Res = getMulExpr(Res, getVScale(IntTy));
4401 return Res;
4402}
4403
4405 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4406}
4407
4409 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4410}
4411
4413 StructType *STy,
4414 unsigned FieldNo) {
4415 // We can bypass creating a target-independent constant expression and then
4416 // folding it back into a ConstantInt. This is just a compile-time
4417 // optimization.
4418 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4419 assert(!SL->getSizeInBits().isScalable() &&
4420 "Cannot get offset for structure containing scalable vector types");
4421 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4422}
4423
4425 // Don't attempt to do anything other than create a SCEVUnknown object
4426 // here. createSCEV only calls getUnknown after checking for all other
4427 // interesting possibilities, and any other code that calls getUnknown
4428 // is doing so in order to hide a value from SCEV canonicalization.
4429
4432 ID.AddPointer(V);
4433 void *IP = nullptr;
4434 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4435 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4436 "Stale SCEVUnknown in uniquing map!");
4437 return S;
4438 }
4439 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4440 FirstUnknown);
4441 FirstUnknown = cast<SCEVUnknown>(S);
4442 UniqueSCEVs.InsertNode(S, IP);
4443 S->computeAndSetCanonical(*this);
4444 return S;
4445}
4446
4447//===----------------------------------------------------------------------===//
4448// Basic SCEV Analysis and PHI Idiom Recognition Code
4449//
4450
4451/// Test if values of the given type are analyzable within the SCEV
4452/// framework. This primarily includes integer types, and it can optionally
4453/// include pointer types if the ScalarEvolution class has access to
4454/// target-specific information.
4456 // Integers and pointers are always SCEVable.
4457 return Ty->isIntOrPtrTy();
4458}
4459
4460/// Return the size in bits of the specified type, for which isSCEVable must
4461/// return true.
4463 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4464 if (Ty->isPointerTy())
4466 return getDataLayout().getTypeSizeInBits(Ty);
4467}
4468
4469/// Return a type with the same bitwidth as the given type and which represents
4470/// how SCEV will treat the given type, for which isSCEVable must return
4471/// true. For pointer types, this is the pointer index sized integer type.
4473 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4474
4475 if (Ty->isIntegerTy())
4476 return Ty;
4477
4478 // The only other support type is pointer.
4479 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4480 return getDataLayout().getIndexType(Ty);
4481}
4482
4484 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4485}
4486
4488 const SCEV *B) {
4489 /// For a valid use point to exist, the defining scope of one operand
4490 /// must dominate the other.
4491 bool PreciseA, PreciseB;
4492 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4493 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4494 if (!PreciseA || !PreciseB)
4495 // Can't tell.
4496 return false;
4497 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4498 DT.dominates(ScopeB, ScopeA);
4499}
4500
4502 return CouldNotCompute.get();
4503}
4504
4505bool ScalarEvolution::checkValidity(const SCEV *S) const {
4506 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4507 auto *SU = dyn_cast<SCEVUnknown>(S);
4508 return SU && SU->getValue() == nullptr;
4509 });
4510
4511 return !ContainsNulls;
4512}
4513
4515 HasRecMapType::iterator I = HasRecMap.find(S);
4516 if (I != HasRecMap.end())
4517 return I->second;
4518
4519 bool FoundAddRec =
4520 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4521 HasRecMap.insert({S, FoundAddRec});
4522 return FoundAddRec;
4523}
4524
4525/// Return the ValueOffsetPair set for \p S. \p S can be represented
4526/// by the value and offset from any ValueOffsetPair in the set.
4527ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4528 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4529 if (SI == ExprValueMap.end())
4530 return {};
4531 return SI->second.getArrayRef();
4532}
4533
4534/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4535/// cannot be used separately. eraseValueFromMap should be used to remove
4536/// V from ValueExprMap and ExprValueMap at the same time.
4537void ScalarEvolution::eraseValueFromMap(Value *V) {
4538 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4539 if (I != ValueExprMap.end()) {
4540 auto EVIt = ExprValueMap.find(I->second);
4541 bool Removed = EVIt->second.remove(V);
4542 (void) Removed;
4543 assert(Removed && "Value not in ExprValueMap?");
4544 ValueExprMap.erase(I);
4545 }
4546}
4547
4548void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4549 // A recursive query may have already computed the SCEV. It should be
4550 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4551 // inferred nowrap flags.
4552 auto It = ValueExprMap.find_as(V);
4553 if (It == ValueExprMap.end()) {
4554 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4555 ExprValueMap[S].insert(V);
4556 }
4557}
4558
4559/// Return an existing SCEV if it exists, otherwise analyze the expression and
4560/// create a new one.
4562 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4563
4564 if (const SCEV *S = getExistingSCEV(V))
4565 return S;
4566 return createSCEVIter(V);
4567}
4568
4570 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4571
4572 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4573 if (I != ValueExprMap.end()) {
4574 const SCEV *S = I->second;
4575 assert(checkValidity(S) &&
4576 "existing SCEV has not been properly invalidated");
4577 return S;
4578 }
4579 return nullptr;
4580}
4581
4582/// Return a SCEV corresponding to -V = -1*V
4584 SCEV::NoWrapFlags Flags) {
4585 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4586 return getConstant(
4587 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4588
4589 Type *Ty = V->getType();
4590 Ty = getEffectiveSCEVType(Ty);
4591 return getMulExpr(V, getMinusOne(Ty), Flags);
4592}
4593
4594/// If Expr computes ~A, return A else return nullptr
4595static const SCEV *MatchNotExpr(const SCEV *Expr) {
4596 const SCEV *MulOp;
4597 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4598 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4599 return MulOp;
4600 return nullptr;
4601}
4602
4603/// Return a SCEV corresponding to ~V = -1-V
4605 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4606
4607 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4608 return getConstant(
4609 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4610
4611 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4612 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4613 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4614 SmallVector<SCEVUse, 2> MatchedOperands;
4615 for (const SCEV *Operand : MME->operands()) {
4616 const SCEV *Matched = MatchNotExpr(Operand);
4617 if (!Matched)
4618 return (const SCEV *)nullptr;
4619 MatchedOperands.push_back(Matched);
4620 }
4621 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4622 MatchedOperands);
4623 };
4624 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4625 return Replaced;
4626 }
4627
4628 Type *Ty = V->getType();
4629 Ty = getEffectiveSCEVType(Ty);
4630 return getMinusSCEV(getMinusOne(Ty), V);
4631}
4632
4634 assert(P->getType()->isPointerTy());
4635
4636 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4637 // The base of an AddRec is the first operand.
4638 SmallVector<SCEVUse> Ops{AddRec->operands()};
4639 Ops[0] = removePointerBase(Ops[0]);
4640 // Don't try to transfer nowrap flags for now. We could in some cases
4641 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4642 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4643 }
4644 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4645 // The base of an Add is the pointer operand.
4646 SmallVector<SCEVUse> Ops{Add->operands()};
4647 SCEVUse *PtrOp = nullptr;
4648 for (SCEVUse &AddOp : Ops) {
4649 if (AddOp->getType()->isPointerTy()) {
4650 assert(!PtrOp && "Cannot have multiple pointer ops");
4651 PtrOp = &AddOp;
4652 }
4653 }
4654 *PtrOp = removePointerBase(*PtrOp);
4655 // Don't try to transfer nowrap flags for now. We could in some cases
4656 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4657 return getAddExpr(Ops);
4658 }
4659 // Any other expression must be a pointer base.
4660 return getZero(P->getType());
4661}
4662
4664 SCEV::NoWrapFlags Flags,
4665 unsigned Depth) {
4666 // Fast path: X - X --> 0.
4667 if (LHS == RHS)
4668 return getZero(LHS->getType());
4669
4670 // If we subtract two pointers with different pointer bases, bail.
4671 // Eventually, we're going to add an assertion to getMulExpr that we
4672 // can't multiply by a pointer.
4673 if (RHS->getType()->isPointerTy()) {
4674 if (!LHS->getType()->isPointerTy() ||
4675 getPointerBase(LHS) != getPointerBase(RHS))
4676 return getCouldNotCompute();
4677 LHS = removePointerBase(LHS);
4678 RHS = removePointerBase(RHS);
4679 }
4680
4681 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4682 // makes it so that we cannot make much use of NUW.
4683 auto AddFlags = SCEV::FlagAnyWrap;
4684 const bool RHSIsNotMinSigned =
4686 if (hasFlags(Flags, SCEV::FlagNSW)) {
4687 // Let M be the minimum representable signed value. Then (-1)*RHS
4688 // signed-wraps if and only if RHS is M. That can happen even for
4689 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4690 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4691 // (-1)*RHS, we need to prove that RHS != M.
4692 //
4693 // If LHS is non-negative and we know that LHS - RHS does not
4694 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4695 // either by proving that RHS > M or that LHS >= 0.
4696 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4697 AddFlags = SCEV::FlagNSW;
4698 }
4699 }
4700
4701 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4702 // RHS is NSW and LHS >= 0.
4703 //
4704 // The difficulty here is that the NSW flag may have been proven
4705 // relative to a loop that is to be found in a recurrence in LHS and
4706 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4707 // larger scope than intended.
4708 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4709
4710 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4711}
4712
4714 unsigned Depth) {
4715 Type *SrcTy = V->getType();
4716 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4717 "Cannot truncate or zero extend with non-integer arguments!");
4718 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4719 return V; // No conversion
4720 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4721 return getTruncateExpr(V, Ty, Depth);
4722 return getZeroExtendExpr(V, Ty, Depth);
4723}
4724
4726 unsigned Depth) {
4727 Type *SrcTy = V->getType();
4728 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4729 "Cannot truncate or zero extend with non-integer arguments!");
4730 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4731 return V; // No conversion
4732 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4733 return getTruncateExpr(V, Ty, Depth);
4734 return getSignExtendExpr(V, Ty, Depth);
4735}
4736
4738 Type *SrcTy = V->getType();
4739 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4740 "Cannot noop or zero extend with non-integer arguments!");
4742 "getNoopOrZeroExtend cannot truncate!");
4743 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4744 return V; // No conversion
4745 return getZeroExtendExpr(V, Ty);
4746}
4747
4749 Type *SrcTy = V->getType();
4750 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4751 "Cannot noop or sign extend with non-integer arguments!");
4753 "getNoopOrSignExtend cannot truncate!");
4754 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4755 return V; // No conversion
4756 return getSignExtendExpr(V, Ty);
4757}
4758
4760 Type *SrcTy = V->getType();
4761 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4762 "Cannot noop or any extend with non-integer arguments!");
4764 "getNoopOrAnyExtend cannot truncate!");
4765 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4766 return V; // No conversion
4767 return getAnyExtendExpr(V, Ty);
4768}
4769
4771 Type *SrcTy = V->getType();
4772 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4773 "Cannot truncate or noop with non-integer arguments!");
4775 "getTruncateOrNoop cannot extend!");
4776 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4777 return V; // No conversion
4778 return getTruncateExpr(V, Ty);
4779}
4780
4782 const SCEV *RHS) {
4783 const SCEV *PromotedLHS = LHS;
4784 const SCEV *PromotedRHS = RHS;
4785
4786 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4787 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4788 else
4789 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4790
4791 return getUMaxExpr(PromotedLHS, PromotedRHS);
4792}
4793
4795 const SCEV *RHS,
4796 bool Sequential) {
4797 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4798 return getUMinFromMismatchedTypes(Ops, Sequential);
4799}
4800
4801const SCEV *
4803 bool Sequential) {
4804 assert(!Ops.empty() && "At least one operand must be!");
4805 // Trivial case.
4806 if (Ops.size() == 1)
4807 return Ops[0];
4808
4809 // Find the max type first.
4810 Type *MaxType = nullptr;
4811 for (SCEVUse S : Ops)
4812 if (MaxType)
4813 MaxType = getWiderType(MaxType, S->getType());
4814 else
4815 MaxType = S->getType();
4816 assert(MaxType && "Failed to find maximum type!");
4817
4818 // Extend all ops to max type.
4819 SmallVector<SCEVUse, 2> PromotedOps;
4820 for (SCEVUse S : Ops)
4821 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4822
4823 // Generate umin.
4824 return getUMinExpr(PromotedOps, Sequential);
4825}
4826
4828 // A pointer operand may evaluate to a nonpointer expression, such as null.
4829 if (!V->getType()->isPointerTy())
4830 return V;
4831
4832 while (true) {
4833 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4834 V = AddRec->getStart();
4835 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4836 const SCEV *PtrOp = nullptr;
4837 for (const SCEV *AddOp : Add->operands()) {
4838 if (AddOp->getType()->isPointerTy()) {
4839 assert(!PtrOp && "Cannot have multiple pointer ops");
4840 PtrOp = AddOp;
4841 }
4842 }
4843 assert(PtrOp && "Must have pointer op");
4844 V = PtrOp;
4845 } else // Not something we can look further into.
4846 return V;
4847 }
4848}
4849
4850/// Push users of the given Instruction onto the given Worklist.
4854 // Push the def-use children onto the Worklist stack.
4855 for (User *U : I->users()) {
4856 auto *UserInsn = cast<Instruction>(U);
4857 if (Visited.insert(UserInsn).second)
4858 Worklist.push_back(UserInsn);
4859 }
4860}
4861
4862namespace {
4863
4864/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4865/// expression in case its Loop is L. If it is not L then
4866/// if IgnoreOtherLoops is true then use AddRec itself
4867/// otherwise rewrite cannot be done.
4868/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4869class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4870public:
4871 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4872 bool IgnoreOtherLoops = true) {
4873 SCEVInitRewriter Rewriter(L, SE);
4874 const SCEV *Result = Rewriter.visit(S);
4875 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4876 return SE.getCouldNotCompute();
4877 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4878 ? SE.getCouldNotCompute()
4879 : Result;
4880 }
4881
4882 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4883 if (!SE.isLoopInvariant(Expr, L))
4884 SeenLoopVariantSCEVUnknown = true;
4885 return Expr;
4886 }
4887
4888 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4889 // Only re-write AddRecExprs for this loop.
4890 if (Expr->getLoop() == L)
4891 return Expr->getStart();
4892 SeenOtherLoops = true;
4893 return Expr;
4894 }
4895
4896 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4897
4898 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4899
4900private:
4901 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4902 : SCEVRewriteVisitor(SE), L(L) {}
4903
4904 const Loop *L;
4905 bool SeenLoopVariantSCEVUnknown = false;
4906 bool SeenOtherLoops = false;
4907};
4908
4909/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4910/// increment expression in case its Loop is L. If it is not L then
4911/// use AddRec itself.
4912/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4913class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4914public:
4915 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4916 SCEVPostIncRewriter Rewriter(L, SE);
4917 const SCEV *Result = Rewriter.visit(S);
4918 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4919 ? SE.getCouldNotCompute()
4920 : Result;
4921 }
4922
4923 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4924 if (!SE.isLoopInvariant(Expr, L))
4925 SeenLoopVariantSCEVUnknown = true;
4926 return Expr;
4927 }
4928
4929 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4930 // Only re-write AddRecExprs for this loop.
4931 if (Expr->getLoop() == L)
4932 return Expr->getPostIncExpr(SE);
4933 SeenOtherLoops = true;
4934 return Expr;
4935 }
4936
4937 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4938
4939 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4940
4941private:
4942 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4943 : SCEVRewriteVisitor(SE), L(L) {}
4944
4945 const Loop *L;
4946 bool SeenLoopVariantSCEVUnknown = false;
4947 bool SeenOtherLoops = false;
4948};
4949
4950/// This class evaluates the compare condition by matching it against the
4951/// condition of loop latch. If there is a match we assume a true value
4952/// for the condition while building SCEV nodes.
4953class SCEVBackedgeConditionFolder
4954 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4955public:
4956 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4957 ScalarEvolution &SE) {
4958 bool IsPosBECond = false;
4959 Value *BECond = nullptr;
4960 if (BasicBlock *Latch = L->getLoopLatch()) {
4961 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4962 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4963 "Both outgoing branches should not target same header!");
4964 BECond = BI->getCondition();
4965 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4966 } else {
4967 return S;
4968 }
4969 }
4970 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4971 return Rewriter.visit(S);
4972 }
4973
4974 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4975 const SCEV *Result = Expr;
4976 bool InvariantF = SE.isLoopInvariant(Expr, L);
4977
4978 if (!InvariantF) {
4980 switch (I->getOpcode()) {
4981 case Instruction::Select: {
4982 SelectInst *SI = cast<SelectInst>(I);
4983 std::optional<const SCEV *> Res =
4984 compareWithBackedgeCondition(SI->getCondition());
4985 if (Res) {
4986 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4987 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4988 }
4989 break;
4990 }
4991 default: {
4992 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4993 if (Res)
4994 Result = *Res;
4995 break;
4996 }
4997 }
4998 }
4999 return Result;
5000 }
5001
5002private:
5003 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5004 bool IsPosBECond, ScalarEvolution &SE)
5005 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5006 IsPositiveBECond(IsPosBECond) {}
5007
5008 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5009
5010 const Loop *L;
5011 /// Loop back condition.
5012 Value *BackedgeCond = nullptr;
5013 /// Set to true if loop back is on positive branch condition.
5014 bool IsPositiveBECond;
5015};
5016
5017std::optional<const SCEV *>
5018SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5019
5020 // If value matches the backedge condition for loop latch,
5021 // then return a constant evolution node based on loopback
5022 // branch taken.
5023 if (BackedgeCond == IC)
5024 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5026 return std::nullopt;
5027}
5028
5029class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5030public:
5031 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5032 ScalarEvolution &SE) {
5033 SCEVShiftRewriter Rewriter(L, SE);
5034 const SCEV *Result = Rewriter.visit(S);
5035 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5036 }
5037
5038 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5039 // Only allow AddRecExprs for this loop.
5040 if (!SE.isLoopInvariant(Expr, L))
5041 Valid = false;
5042 return Expr;
5043 }
5044
5045 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5046 if (Expr->getLoop() == L && Expr->isAffine())
5047 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5048 Valid = false;
5049 return Expr;
5050 }
5051
5052 bool isValid() { return Valid; }
5053
5054private:
5055 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5056 : SCEVRewriteVisitor(SE), L(L) {}
5057
5058 const Loop *L;
5059 bool Valid = true;
5060};
5061
5062} // end anonymous namespace
5063
5064void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5065 if (!AR->isAffine())
5066 return;
5067
5068 // Force computation of ranges, which will also perform range-based flag
5069 // inference.
5070 if (!AR->hasNoSignedWrap())
5071 (void)getSignedRange(AR);
5072
5073 if (!AR->hasNoUnsignedWrap())
5074 (void)getUnsignedRange(AR);
5075
5076 if (!AR->hasNoSelfWrap()) {
5077 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5078 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5079 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5080 const APInt &BECountAP = BECountMax->getAPInt();
5081 unsigned NoOverflowBitWidth =
5082 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5083 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5084 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5085 }
5086 }
5087}
5088
5090ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5092
5093 if (AR->hasNoSignedWrap())
5094 return Result;
5095
5096 if (!AR->isAffine())
5097 return Result;
5098
5099 // This function can be expensive, only try to prove NSW once per AddRec.
5100 if (!SignedWrapViaInductionTried.insert(AR).second)
5101 return Result;
5102
5103 const SCEV *Step = AR->getStepRecurrence(*this);
5104 const Loop *L = AR->getLoop();
5105
5106 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5107 // Note that this serves two purposes: It filters out loops that are
5108 // simply not analyzable, and it covers the case where this code is
5109 // being called from within backedge-taken count analysis, such that
5110 // attempting to ask for the backedge-taken count would likely result
5111 // in infinite recursion. In the later case, the analysis code will
5112 // cope with a conservative value, and it will take care to purge
5113 // that value once it has finished.
5114 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5115
5116 // Normally, in the cases we can prove no-overflow via a
5117 // backedge guarding condition, we can also compute a backedge
5118 // taken count for the loop. The exceptions are assumptions and
5119 // guards present in the loop -- SCEV is not great at exploiting
5120 // these to compute max backedge taken counts, but can still use
5121 // these to prove lack of overflow. Use this fact to avoid
5122 // doing extra work that may not pay off.
5123
5124 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5125 AC.assumptions().empty())
5126 return Result;
5127
5128 // If the backedge is guarded by a comparison with the pre-inc value the
5129 // addrec is safe. Also, if the entry is guarded by a comparison with the
5130 // start value and the backedge is guarded by a comparison with the post-inc
5131 // value, the addrec is safe.
5133 const SCEV *OverflowLimit =
5134 getSignedOverflowLimitForStep(Step, &Pred, this);
5135 if (OverflowLimit &&
5136 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5137 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5138 Result = setFlags(Result, SCEV::FlagNSW);
5139 }
5140 return Result;
5141}
5143ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5145
5146 if (AR->hasNoUnsignedWrap())
5147 return Result;
5148
5149 if (!AR->isAffine())
5150 return Result;
5151
5152 // This function can be expensive, only try to prove NUW once per AddRec.
5153 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5154 return Result;
5155
5156 const SCEV *Step = AR->getStepRecurrence(*this);
5157 const Loop *L = AR->getLoop();
5158
5159 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5160 // Note that this serves two purposes: It filters out loops that are
5161 // simply not analyzable, and it covers the case where this code is
5162 // being called from within backedge-taken count analysis, such that
5163 // attempting to ask for the backedge-taken count would likely result
5164 // in infinite recursion. In the later case, the analysis code will
5165 // cope with a conservative value, and it will take care to purge
5166 // that value once it has finished.
5167 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5168
5169 // Normally, in the cases we can prove no-overflow via a
5170 // backedge guarding condition, we can also compute a backedge
5171 // taken count for the loop. The exceptions are assumptions and
5172 // guards present in the loop -- SCEV is not great at exploiting
5173 // these to compute max backedge taken counts, but can still use
5174 // these to prove lack of overflow. Use this fact to avoid
5175 // doing extra work that may not pay off.
5176
5177 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5178 AC.assumptions().empty())
5179 return Result;
5180
5181 // If the backedge is guarded by a comparison with the pre-inc value the
5182 // addrec is safe. Also, if the entry is guarded by a comparison with the
5183 // start value and the backedge is guarded by a comparison with the post-inc
5184 // value, the addrec is safe.
5185 if (isKnownPositive(Step)) {
5187 const SCEV *OverflowLimit =
5188 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5189 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5190 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5191 Result = setFlags(Result, SCEV::FlagNUW);
5192 }
5193 return Result;
5194}
5195
5196namespace {
5197
5198/// Represents an abstract binary operation. This may exist as a
5199/// normal instruction or constant expression, or may have been
5200/// derived from an expression tree.
5201struct BinaryOp {
5202 unsigned Opcode;
5203 Value *LHS;
5204 Value *RHS;
5205 bool IsNSW = false;
5206 bool IsNUW = false;
5207
5208 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5209 /// constant expression.
5210 Operator *Op = nullptr;
5211
5212 explicit BinaryOp(Operator *Op)
5213 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5214 Op(Op) {
5215 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5216 IsNSW = OBO->hasNoSignedWrap();
5217 IsNUW = OBO->hasNoUnsignedWrap();
5218 }
5219 }
5220
5221 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5222 bool IsNUW = false)
5223 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5224};
5225
5226} // end anonymous namespace
5227
5228/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5229static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5230 AssumptionCache &AC,
5231 const DominatorTree &DT,
5232 const Instruction *CxtI) {
5233 auto *Op = dyn_cast<Operator>(V);
5234 if (!Op)
5235 return std::nullopt;
5236
5237 // Implementation detail: all the cleverness here should happen without
5238 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5239 // SCEV expressions when possible, and we should not break that.
5240
5241 switch (Op->getOpcode()) {
5242 case Instruction::Add:
5243 case Instruction::Sub:
5244 case Instruction::Mul:
5245 case Instruction::UDiv:
5246 case Instruction::URem:
5247 case Instruction::And:
5248 case Instruction::AShr:
5249 case Instruction::Shl:
5250 return BinaryOp(Op);
5251
5252 case Instruction::Or: {
5253 // Convert or disjoint into add nuw nsw.
5254 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5255 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5256 /*IsNSW=*/true, /*IsNUW=*/true);
5257 // Keep the reference to the original instruction so that we can later
5258 // check whether it can produce poison value or not.
5259 BinOp.Op = Op;
5260 return BinOp;
5261 }
5262 return BinaryOp(Op);
5263 }
5264
5265 case Instruction::Xor:
5266 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5267 // If the RHS of the xor is a signmask, then this is just an add.
5268 // Instcombine turns add of signmask into xor as a strength reduction step.
5269 if (RHSC->getValue().isSignMask())
5270 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5271 // Binary `xor` is a bit-wise `add`.
5272 if (V->getType()->isIntegerTy(1))
5273 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5274 return BinaryOp(Op);
5275
5276 case Instruction::LShr:
5277 // Turn logical shift right of a constant into a unsigned divide.
5278 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5279 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5280
5281 // If the shift count is not less than the bitwidth, the result of
5282 // the shift is undefined. Don't try to analyze it, because the
5283 // resolution chosen here may differ from the resolution chosen in
5284 // other parts of the compiler.
5285 if (SA->getValue().ult(BitWidth)) {
5286 Constant *X =
5287 ConstantInt::get(SA->getContext(),
5288 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5289 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5290 }
5291 }
5292 return BinaryOp(Op);
5293
5294 case Instruction::ExtractValue: {
5295 auto *EVI = cast<ExtractValueInst>(Op);
5296 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5297 break;
5298
5299 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5300 if (!WO)
5301 break;
5302
5303 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5304 bool Signed = WO->isSigned();
5305 // TODO: Should add nuw/nsw flags for mul as well.
5306 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5307 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5308
5309 // Now that we know that all uses of the arithmetic-result component of
5310 // CI are guarded by the overflow check, we can go ahead and pretend
5311 // that the arithmetic is non-overflowing.
5312 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5313 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5314 }
5315
5316 default:
5317 break;
5318 }
5319
5320 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5321 // semantics as a Sub, return a binary sub expression.
5322 if (auto *II = dyn_cast<IntrinsicInst>(V))
5323 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5324 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5325
5326 return std::nullopt;
5327}
5328
5329/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5330/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5331/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5332/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5333/// follows one of the following patterns:
5334/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5335/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5336/// If the SCEV expression of \p Op conforms with one of the expected patterns
5337/// we return the type of the truncation operation, and indicate whether the
5338/// truncated type should be treated as signed/unsigned by setting
5339/// \p Signed to true/false, respectively.
5340static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5341 bool &Signed, ScalarEvolution &SE) {
5342 // The case where Op == SymbolicPHI (that is, with no type conversions on
5343 // the way) is handled by the regular add recurrence creating logic and
5344 // would have already been triggered in createAddRecForPHI. Reaching it here
5345 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5346 // because one of the other operands of the SCEVAddExpr updating this PHI is
5347 // not invariant).
5348 //
5349 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5350 // this case predicates that allow us to prove that Op == SymbolicPHI will
5351 // be added.
5352 if (Op == SymbolicPHI)
5353 return nullptr;
5354
5355 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5356 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5357 if (SourceBits != NewBits)
5358 return nullptr;
5359
5360 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5361 Signed = true;
5362 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5363 }
5364 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5365 Signed = false;
5366 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5367 }
5368 return nullptr;
5369}
5370
5371static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5372 if (!PN->getType()->isIntegerTy())
5373 return nullptr;
5374 const Loop *L = LI.getLoopFor(PN->getParent());
5375 if (!L || L->getHeader() != PN->getParent())
5376 return nullptr;
5377 return L;
5378}
5379
5380// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5381// computation that updates the phi follows the following pattern:
5382// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5383// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5384// If so, try to see if it can be rewritten as an AddRecExpr under some
5385// Predicates. If successful, return them as a pair. Also cache the results
5386// of the analysis.
5387//
5388// Example usage scenario:
5389// Say the Rewriter is called for the following SCEV:
5390// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5391// where:
5392// %X = phi i64 (%Start, %BEValue)
5393// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5394// and call this function with %SymbolicPHI = %X.
5395//
5396// The analysis will find that the value coming around the backedge has
5397// the following SCEV:
5398// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5399// Upon concluding that this matches the desired pattern, the function
5400// will return the pair {NewAddRec, SmallPredsVec} where:
5401// NewAddRec = {%Start,+,%Step}
5402// SmallPredsVec = {P1, P2, P3} as follows:
5403// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5404// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5405// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5406// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5407// under the predicates {P1,P2,P3}.
5408// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5409// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5410//
5411// TODO's:
5412//
5413// 1) Extend the Induction descriptor to also support inductions that involve
5414// casts: When needed (namely, when we are called in the context of the
5415// vectorizer induction analysis), a Set of cast instructions will be
5416// populated by this method, and provided back to isInductionPHI. This is
5417// needed to allow the vectorizer to properly record them to be ignored by
5418// the cost model and to avoid vectorizing them (otherwise these casts,
5419// which are redundant under the runtime overflow checks, will be
5420// vectorized, which can be costly).
5421//
5422// 2) Support additional induction/PHISCEV patterns: We also want to support
5423// inductions where the sext-trunc / zext-trunc operations (partly) occur
5424// after the induction update operation (the induction increment):
5425//
5426// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5427// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5428//
5429// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5430// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5431//
5432// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5433std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5434ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5436
5437 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5438 // return an AddRec expression under some predicate.
5439
5440 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5441 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5442 assert(L && "Expecting an integer loop header phi");
5443
5444 // The loop may have multiple entrances or multiple exits; we can analyze
5445 // this phi as an addrec if it has a unique entry value and a unique
5446 // backedge value.
5447 Value *BEValueV = nullptr, *StartValueV = nullptr;
5448 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5449 Value *V = PN->getIncomingValue(i);
5450 if (L->contains(PN->getIncomingBlock(i))) {
5451 if (!BEValueV) {
5452 BEValueV = V;
5453 } else if (BEValueV != V) {
5454 BEValueV = nullptr;
5455 break;
5456 }
5457 } else if (!StartValueV) {
5458 StartValueV = V;
5459 } else if (StartValueV != V) {
5460 StartValueV = nullptr;
5461 break;
5462 }
5463 }
5464 if (!BEValueV || !StartValueV)
5465 return std::nullopt;
5466
5467 const SCEV *BEValue = getSCEV(BEValueV);
5468
5469 // If the value coming around the backedge is an add with the symbolic
5470 // value we just inserted, possibly with casts that we can ignore under
5471 // an appropriate runtime guard, then we found a simple induction variable!
5472 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5473 if (!Add)
5474 return std::nullopt;
5475
5476 // If there is a single occurrence of the symbolic value, possibly
5477 // casted, replace it with a recurrence.
5478 unsigned FoundIndex = Add->getNumOperands();
5479 Type *TruncTy = nullptr;
5480 bool Signed;
5481 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5482 if ((TruncTy =
5483 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5484 if (FoundIndex == e) {
5485 FoundIndex = i;
5486 break;
5487 }
5488
5489 if (FoundIndex == Add->getNumOperands())
5490 return std::nullopt;
5491
5492 // Create an add with everything but the specified operand.
5494 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5495 if (i != FoundIndex)
5496 Ops.push_back(Add->getOperand(i));
5497 const SCEV *Accum = getAddExpr(Ops);
5498
5499 // The runtime checks will not be valid if the step amount is
5500 // varying inside the loop.
5501 if (!isLoopInvariant(Accum, L))
5502 return std::nullopt;
5503
5504 // *** Part2: Create the predicates
5505
5506 // Analysis was successful: we have a phi-with-cast pattern for which we
5507 // can return an AddRec expression under the following predicates:
5508 //
5509 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5510 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5511 // P2: An Equal predicate that guarantees that
5512 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5513 // P3: An Equal predicate that guarantees that
5514 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5515 //
5516 // As we next prove, the above predicates guarantee that:
5517 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5518 //
5519 //
5520 // More formally, we want to prove that:
5521 // Expr(i+1) = Start + (i+1) * Accum
5522 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5523 //
5524 // Given that:
5525 // 1) Expr(0) = Start
5526 // 2) Expr(1) = Start + Accum
5527 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5528 // 3) Induction hypothesis (step i):
5529 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5530 //
5531 // Proof:
5532 // Expr(i+1) =
5533 // = Start + (i+1)*Accum
5534 // = (Start + i*Accum) + Accum
5535 // = Expr(i) + Accum
5536 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5537 // :: from step i
5538 //
5539 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5540 //
5541 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5542 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5543 // + Accum :: from P3
5544 //
5545 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5546 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5547 //
5548 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5549 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5550 //
5551 // By induction, the same applies to all iterations 1<=i<n:
5552 //
5553
5554 // Create a truncated addrec for which we will add a no overflow check (P1).
5555 const SCEV *StartVal = getSCEV(StartValueV);
5556 const SCEV *PHISCEV =
5557 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5558 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5559
5560 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5561 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5562 // will be constant.
5563 //
5564 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5565 // add P1.
5566 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5570 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5571 Predicates.push_back(AddRecPred);
5572 }
5573
5574 // Create the Equal Predicates P2,P3:
5575
5576 // It is possible that the predicates P2 and/or P3 are computable at
5577 // compile time due to StartVal and/or Accum being constants.
5578 // If either one is, then we can check that now and escape if either P2
5579 // or P3 is false.
5580
5581 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5582 // for each of StartVal and Accum
5583 auto getExtendedExpr = [&](const SCEV *Expr,
5584 bool CreateSignExtend) -> const SCEV * {
5585 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5586 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5587 const SCEV *ExtendedExpr =
5588 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5589 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5590 return ExtendedExpr;
5591 };
5592
5593 // Given:
5594 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5595 // = getExtendedExpr(Expr)
5596 // Determine whether the predicate P: Expr == ExtendedExpr
5597 // is known to be false at compile time
5598 auto PredIsKnownFalse = [&](const SCEV *Expr,
5599 const SCEV *ExtendedExpr) -> bool {
5600 return Expr != ExtendedExpr &&
5601 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5602 };
5603
5604 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5605 if (PredIsKnownFalse(StartVal, StartExtended)) {
5606 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5607 return std::nullopt;
5608 }
5609
5610 // The Step is always Signed (because the overflow checks are either
5611 // NSSW or NUSW)
5612 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5613 if (PredIsKnownFalse(Accum, AccumExtended)) {
5614 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5615 return std::nullopt;
5616 }
5617
5618 auto AppendPredicate = [&](const SCEV *Expr,
5619 const SCEV *ExtendedExpr) -> void {
5620 if (Expr != ExtendedExpr &&
5621 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5622 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5623 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5624 Predicates.push_back(Pred);
5625 }
5626 };
5627
5628 AppendPredicate(StartVal, StartExtended);
5629 AppendPredicate(Accum, AccumExtended);
5630
5631 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5632 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5633 // into NewAR if it will also add the runtime overflow checks specified in
5634 // Predicates.
5635 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5636
5637 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5638 std::make_pair(NewAR, Predicates);
5639 // Remember the result of the analysis for this SCEV at this locayyytion.
5640 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5641 return PredRewrite;
5642}
5643
5644std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5646 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5647 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5648 if (!L)
5649 return std::nullopt;
5650
5651 // Check to see if we already analyzed this PHI.
5652 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5653 if (I != PredicatedSCEVRewrites.end()) {
5654 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5655 I->second;
5656 // Analysis was done before and failed to create an AddRec:
5657 if (Rewrite.first == SymbolicPHI)
5658 return std::nullopt;
5659 // Analysis was done before and succeeded to create an AddRec under
5660 // a predicate:
5661 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5662 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5663 return Rewrite;
5664 }
5665
5666 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5667 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5668
5669 // Record in the cache that the analysis failed
5670 if (!Rewrite) {
5672 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5673 return std::nullopt;
5674 }
5675
5676 return Rewrite;
5677}
5678
5679// FIXME: This utility is currently required because the Rewriter currently
5680// does not rewrite this expression:
5681// {0, +, (sext ix (trunc iy to ix) to iy)}
5682// into {0, +, %step},
5683// even when the following Equal predicate exists:
5684// "%step == (sext ix (trunc iy to ix) to iy)".
5686 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5687 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5688 if (AR1 == AR2)
5689 return true;
5690
5691 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5692 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5693 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5694 if (Expr1 != Expr2 &&
5695 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5696 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5697 return false;
5698 return true;
5699 };
5700
5701 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5702 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5703 return false;
5704 return true;
5705}
5706
5707/// A helper function for createAddRecFromPHI to handle simple cases.
5708///
5709/// This function tries to find an AddRec expression for the simplest (yet most
5710/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5711/// If it fails, createAddRecFromPHI will use a more general, but slow,
5712/// technique for finding the AddRec expression.
5713const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5714 Value *BEValueV,
5715 Value *StartValueV) {
5716 const Loop *L = LI.getLoopFor(PN->getParent());
5717 assert(L && L->getHeader() == PN->getParent());
5718 assert(BEValueV && StartValueV);
5719
5720 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5721 if (!BO)
5722 return nullptr;
5723
5724 if (BO->Opcode != Instruction::Add)
5725 return nullptr;
5726
5727 const SCEV *Accum = nullptr;
5728 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5729 Accum = getSCEV(BO->RHS);
5730 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5731 Accum = getSCEV(BO->LHS);
5732
5733 if (!Accum)
5734 return nullptr;
5735
5737 if (BO->IsNUW)
5738 Flags = setFlags(Flags, SCEV::FlagNUW);
5739 if (BO->IsNSW)
5740 Flags = setFlags(Flags, SCEV::FlagNSW);
5741
5742 const SCEV *StartVal = getSCEV(StartValueV);
5743 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5744 insertValueToMap(PN, PHISCEV);
5745
5746 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5747 inferNoWrapViaConstantRanges(AR);
5748
5749 // We can add Flags to the post-inc expression only if we
5750 // know that it is *undefined behavior* for BEValueV to
5751 // overflow.
5752 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5753 assert(isLoopInvariant(Accum, L) &&
5754 "Accum is defined outside L, but is not invariant?");
5755 if (isAddRecNeverPoison(BEInst, L))
5756 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5757 }
5758
5759 return PHISCEV;
5760}
5761
5762const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5763 const Loop *L = LI.getLoopFor(PN->getParent());
5764 if (!L || L->getHeader() != PN->getParent())
5765 return nullptr;
5766
5767 // The loop may have multiple entrances or multiple exits; we can analyze
5768 // this phi as an addrec if it has a unique entry value and a unique
5769 // backedge value.
5770 Value *BEValueV = nullptr, *StartValueV = nullptr;
5771 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5772 Value *V = PN->getIncomingValue(i);
5773 if (L->contains(PN->getIncomingBlock(i))) {
5774 if (!BEValueV) {
5775 BEValueV = V;
5776 } else if (BEValueV != V) {
5777 BEValueV = nullptr;
5778 break;
5779 }
5780 } else if (!StartValueV) {
5781 StartValueV = V;
5782 } else if (StartValueV != V) {
5783 StartValueV = nullptr;
5784 break;
5785 }
5786 }
5787 if (!BEValueV || !StartValueV)
5788 return nullptr;
5789
5790 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5791 "PHI node already processed?");
5792
5793 // First, try to find AddRec expression without creating a fictituos symbolic
5794 // value for PN.
5795 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5796 return S;
5797
5798 // Handle PHI node value symbolically.
5799 const SCEV *SymbolicName = getUnknown(PN);
5800 insertValueToMap(PN, SymbolicName);
5801
5802 // Using this symbolic name for the PHI, analyze the value coming around
5803 // the back-edge.
5804 const SCEV *BEValue = getSCEV(BEValueV);
5805
5806 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5807 // has a special value for the first iteration of the loop.
5808
5809 // If the value coming around the backedge is an add with the symbolic
5810 // value we just inserted, then we found a simple induction variable!
5811 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5812 // If there is a single occurrence of the symbolic value, replace it
5813 // with a recurrence.
5814 unsigned FoundIndex = Add->getNumOperands();
5815 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5816 if (Add->getOperand(i) == SymbolicName)
5817 if (FoundIndex == e) {
5818 FoundIndex = i;
5819 break;
5820 }
5821
5822 if (FoundIndex != Add->getNumOperands()) {
5823 // Create an add with everything but the specified operand.
5825 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5826 if (i != FoundIndex)
5827 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5828 L, *this));
5829 const SCEV *Accum = getAddExpr(Ops);
5830
5831 // This is not a valid addrec if the step amount is varying each
5832 // loop iteration, but is not itself an addrec in this loop.
5833 if (isLoopInvariant(Accum, L) ||
5834 (isa<SCEVAddRecExpr>(Accum) &&
5835 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5837
5838 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5839 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5840 if (BO->IsNUW)
5841 Flags = setFlags(Flags, SCEV::FlagNUW);
5842 if (BO->IsNSW)
5843 Flags = setFlags(Flags, SCEV::FlagNSW);
5844 }
5845 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5846 if (GEP->getOperand(0) == PN) {
5847 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5848 // If the increment has any nowrap flags, then we know the address
5849 // space cannot be wrapped around.
5850 if (NW != GEPNoWrapFlags::none())
5851 Flags = setFlags(Flags, SCEV::FlagNW);
5852 // If the GEP is nuw or nusw with non-negative offset, we know that
5853 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5854 // offset is treated as signed, while the base is unsigned.
5855 if (NW.hasNoUnsignedWrap() ||
5857 Flags = setFlags(Flags, SCEV::FlagNUW);
5858 }
5859
5860 // We cannot transfer nuw and nsw flags from subtraction
5861 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5862 // for instance.
5863 }
5864
5865 const SCEV *StartVal = getSCEV(StartValueV);
5866 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5867
5868 // Okay, for the entire analysis of this edge we assumed the PHI
5869 // to be symbolic. We now need to go back and purge all of the
5870 // entries for the scalars that use the symbolic expression.
5871 forgetMemoizedResults({SymbolicName});
5872 insertValueToMap(PN, PHISCEV);
5873
5874 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5875 inferNoWrapViaConstantRanges(AR);
5876
5877 // We can add Flags to the post-inc expression only if we
5878 // know that it is *undefined behavior* for BEValueV to
5879 // overflow.
5880 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5881 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5882 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5883
5884 return PHISCEV;
5885 }
5886 }
5887 } else {
5888 // Otherwise, this could be a loop like this:
5889 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5890 // In this case, j = {1,+,1} and BEValue is j.
5891 // Because the other in-value of i (0) fits the evolution of BEValue
5892 // i really is an addrec evolution.
5893 //
5894 // We can generalize this saying that i is the shifted value of BEValue
5895 // by one iteration:
5896 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5897
5898 // Do not allow refinement in rewriting of BEValue.
5899 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5900 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5901 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5902 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5903 const SCEV *StartVal = getSCEV(StartValueV);
5904 if (Start == StartVal) {
5905 // Okay, for the entire analysis of this edge we assumed the PHI
5906 // to be symbolic. We now need to go back and purge all of the
5907 // entries for the scalars that use the symbolic expression.
5908 forgetMemoizedResults({SymbolicName});
5909 insertValueToMap(PN, Shifted);
5910 return Shifted;
5911 }
5912 }
5913 }
5914
5915 // Remove the temporary PHI node SCEV that has been inserted while intending
5916 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5917 // as it will prevent later (possibly simpler) SCEV expressions to be added
5918 // to the ValueExprMap.
5919 eraseValueFromMap(PN);
5920
5921 return nullptr;
5922}
5923
5924// Try to match a control flow sequence that branches out at BI and merges back
5925// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5926// match.
5928 Value *&C, Value *&LHS, Value *&RHS) {
5929 C = BI->getCondition();
5930
5931 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5932 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5933
5934 Use &LeftUse = Merge->getOperandUse(0);
5935 Use &RightUse = Merge->getOperandUse(1);
5936
5937 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5938 LHS = LeftUse;
5939 RHS = RightUse;
5940 return true;
5941 }
5942
5943 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5944 LHS = RightUse;
5945 RHS = LeftUse;
5946 return true;
5947 }
5948
5949 return false;
5950}
5951
5953 Value *&Cond, Value *&LHS,
5954 Value *&RHS) {
5955 auto IsReachable =
5956 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5957 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5958 // Try to match
5959 //
5960 // br %cond, label %left, label %right
5961 // left:
5962 // br label %merge
5963 // right:
5964 // br label %merge
5965 // merge:
5966 // V = phi [ %x, %left ], [ %y, %right ]
5967 //
5968 // as "select %cond, %x, %y"
5969
5970 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5971 assert(IDom && "At least the entry block should dominate PN");
5972
5973 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5974 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5975 }
5976 return false;
5977}
5978
5979const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5980 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5981 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5984 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5985
5986 return nullptr;
5987}
5988
5990 BinaryOperator *CommonInst = nullptr;
5991 // Check if instructions are identical.
5992 for (Value *Incoming : PN->incoming_values()) {
5993 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5994 if (!IncomingInst)
5995 return nullptr;
5996 if (CommonInst) {
5997 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5998 return nullptr; // Not identical, give up
5999 } else {
6000 // Remember binary operator
6001 CommonInst = IncomingInst;
6002 }
6003 }
6004 return CommonInst;
6005}
6006
6007/// Returns SCEV for the first operand of a phi if all phi operands have
6008/// identical opcodes and operands
6009/// eg.
6010/// a: %add = %a + %b
6011/// br %c
6012/// b: %add1 = %a + %b
6013/// br %c
6014/// c: %phi = phi [%add, a], [%add1, b]
6015/// scev(%phi) => scev(%add)
6016const SCEV *
6017ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6018 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6019 if (!CommonInst)
6020 return nullptr;
6021
6022 // Check if SCEV exprs for instructions are identical.
6023 const SCEV *CommonSCEV = getSCEV(CommonInst);
6024 bool SCEVExprsIdentical =
6026 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6027 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6028}
6029
6030const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6031 if (const SCEV *S = createAddRecFromPHI(PN))
6032 return S;
6033
6034 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6035 // phi node for X.
6036 if (Value *V = simplifyInstruction(
6037 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6038 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6039 return getSCEV(V);
6040
6041 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6042 return S;
6043
6044 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6045 return S;
6046
6047 // If it's not a loop phi, we can't handle it yet.
6048 return getUnknown(PN);
6049}
6050
6051bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6052 SCEVTypes RootKind) {
6053 struct FindClosure {
6054 const SCEV *OperandToFind;
6055 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6056 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6057
6058 bool Found = false;
6059
6060 bool canRecurseInto(SCEVTypes Kind) const {
6061 // We can only recurse into the SCEV expression of the same effective type
6062 // as the type of our root SCEV expression, and into zero-extensions.
6063 return RootKind == Kind || NonSequentialRootKind == Kind ||
6064 scZeroExtend == Kind;
6065 };
6066
6067 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6068 : OperandToFind(OperandToFind), RootKind(RootKind),
6069 NonSequentialRootKind(
6071 RootKind)) {}
6072
6073 bool follow(const SCEV *S) {
6074 Found = S == OperandToFind;
6075
6076 return !isDone() && canRecurseInto(S->getSCEVType());
6077 }
6078
6079 bool isDone() const { return Found; }
6080 };
6081
6082 FindClosure FC(OperandToFind, RootKind);
6083 visitAll(Root, FC);
6084 return FC.Found;
6085}
6086
6087std::optional<const SCEV *>
6088ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6089 ICmpInst *Cond,
6090 Value *TrueVal,
6091 Value *FalseVal) {
6092 // Try to match some simple smax or umax patterns.
6093 auto *ICI = Cond;
6094
6095 Value *LHS = ICI->getOperand(0);
6096 Value *RHS = ICI->getOperand(1);
6097
6098 switch (ICI->getPredicate()) {
6099 case ICmpInst::ICMP_SLT:
6100 case ICmpInst::ICMP_SLE:
6101 case ICmpInst::ICMP_ULT:
6102 case ICmpInst::ICMP_ULE:
6103 std::swap(LHS, RHS);
6104 [[fallthrough]];
6105 case ICmpInst::ICMP_SGT:
6106 case ICmpInst::ICMP_SGE:
6107 case ICmpInst::ICMP_UGT:
6108 case ICmpInst::ICMP_UGE:
6109 // a > b ? a+x : b+x -> max(a, b)+x
6110 // a > b ? b+x : a+x -> min(a, b)+x
6112 bool Signed = ICI->isSigned();
6113 const SCEV *LA = getSCEV(TrueVal);
6114 const SCEV *RA = getSCEV(FalseVal);
6115 const SCEV *LS = getSCEV(LHS);
6116 const SCEV *RS = getSCEV(RHS);
6117 if (LA->getType()->isPointerTy()) {
6118 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6119 // Need to make sure we can't produce weird expressions involving
6120 // negated pointers.
6121 if (LA == LS && RA == RS)
6122 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6123 if (LA == RS && RA == LS)
6124 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6125 }
6126 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6127 if (Op->getType()->isPointerTy()) {
6130 return Op;
6131 }
6132 if (Signed)
6133 Op = getNoopOrSignExtend(Op, Ty);
6134 else
6135 Op = getNoopOrZeroExtend(Op, Ty);
6136 return Op;
6137 };
6138 LS = CoerceOperand(LS);
6139 RS = CoerceOperand(RS);
6141 break;
6142 const SCEV *LDiff = getMinusSCEV(LA, LS);
6143 const SCEV *RDiff = getMinusSCEV(RA, RS);
6144 if (LDiff == RDiff)
6145 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6146 LDiff);
6147 LDiff = getMinusSCEV(LA, RS);
6148 RDiff = getMinusSCEV(RA, LS);
6149 if (LDiff == RDiff)
6150 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6151 LDiff);
6152 }
6153 break;
6154 case ICmpInst::ICMP_NE:
6155 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6156 std::swap(TrueVal, FalseVal);
6157 [[fallthrough]];
6158 case ICmpInst::ICMP_EQ:
6159 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6162 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6163 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6164 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6165 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6166 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6167 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6168 return getAddExpr(getUMaxExpr(X, C), Y);
6169 }
6170 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6171 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6172 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6173 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6175 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6176 const SCEV *X = getSCEV(LHS);
6177 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6178 X = ZExt->getOperand();
6179 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6180 const SCEV *FalseValExpr = getSCEV(FalseVal);
6181 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6182 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6183 /*Sequential=*/true);
6184 }
6185 }
6186 break;
6187 default:
6188 break;
6189 }
6190
6191 return std::nullopt;
6192}
6193
6194static std::optional<const SCEV *>
6196 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6197 assert(CondExpr->getType()->isIntegerTy(1) &&
6198 TrueExpr->getType() == FalseExpr->getType() &&
6199 TrueExpr->getType()->isIntegerTy(1) &&
6200 "Unexpected operands of a select.");
6201
6202 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6203 // --> C + (umin_seq cond, x - C)
6204 //
6205 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6206 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6207 // --> C + (umin_seq ~cond, x - C)
6208
6209 // FIXME: while we can't legally model the case where both of the hands
6210 // are fully variable, we only require that the *difference* is constant.
6211 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6212 return std::nullopt;
6213
6214 const SCEV *X, *C;
6215 if (isa<SCEVConstant>(TrueExpr)) {
6216 CondExpr = SE->getNotSCEV(CondExpr);
6217 X = FalseExpr;
6218 C = TrueExpr;
6219 } else {
6220 X = TrueExpr;
6221 C = FalseExpr;
6222 }
6223 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6224 /*Sequential=*/true));
6225}
6226
6227static std::optional<const SCEV *>
6229 Value *FalseVal) {
6230 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6231 return std::nullopt;
6232
6233 const auto *SECond = SE->getSCEV(Cond);
6234 const auto *SETrue = SE->getSCEV(TrueVal);
6235 const auto *SEFalse = SE->getSCEV(FalseVal);
6236 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6237}
6238
6239const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6240 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6241 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6242 assert(TrueVal->getType() == FalseVal->getType() &&
6243 V->getType() == TrueVal->getType() &&
6244 "Types of select hands and of the result must match.");
6245
6246 // For now, only deal with i1-typed `select`s.
6247 if (!V->getType()->isIntegerTy(1))
6248 return getUnknown(V);
6249
6250 if (std::optional<const SCEV *> S =
6251 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6252 return *S;
6253
6254 return getUnknown(V);
6255}
6256
6257const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6258 Value *TrueVal,
6259 Value *FalseVal) {
6260 // Handle "constant" branch or select. This can occur for instance when a
6261 // loop pass transforms an inner loop and moves on to process the outer loop.
6262 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6263 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6264
6265 if (auto *I = dyn_cast<Instruction>(V)) {
6266 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6267 if (std::optional<const SCEV *> S =
6268 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6269 TrueVal, FalseVal))
6270 return *S;
6271 }
6272 }
6273
6274 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6275}
6276
6277/// Expand GEP instructions into add and multiply operations. This allows them
6278/// to be analyzed by regular SCEV code.
6279const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6280 assert(GEP->getSourceElementType()->isSized() &&
6281 "GEP source element type must be sized");
6282
6283 SmallVector<SCEVUse, 4> IndexExprs;
6284 for (Value *Index : GEP->indices())
6285 IndexExprs.push_back(getSCEV(Index));
6286 return getGEPExpr(GEP, IndexExprs);
6287}
6288
6289APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6290 const Instruction *CtxI) {
6292 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6293 return TrailingZeros >= BitWidth
6295 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6296 };
6297 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6298 // The result is GCD of all operands results.
6299 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6300 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6302 Res, getConstantMultiple(N->getOperand(I), CtxI));
6303 return Res;
6304 };
6305
6306 switch (S->getSCEVType()) {
6307 case scConstant:
6308 return cast<SCEVConstant>(S)->getAPInt();
6309 case scPtrToAddr:
6310 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6311 case scUDivExpr:
6312 case scVScale:
6313 return APInt(BitWidth, 1);
6314 case scTruncate: {
6315 // Only multiples that are a power of 2 will hold after truncation.
6316 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6317 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6318 return GetShiftedByZeros(TZ);
6319 }
6320 case scZeroExtend: {
6321 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6322 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6323 }
6324 case scSignExtend: {
6325 // Only multiples that are a power of 2 will hold after sext.
6326 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6327 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6328 return GetShiftedByZeros(TZ);
6329 }
6330 case scMulExpr: {
6331 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6332 if (M->hasNoUnsignedWrap()) {
6333 // The result is the product of all operand results.
6334 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6335 for (const SCEV *Operand : M->operands().drop_front())
6336 Res = Res * getConstantMultiple(Operand, CtxI);
6337 return Res;
6338 }
6339
6340 // If there are no wrap guarentees, find the trailing zeros, which is the
6341 // sum of trailing zeros for all its operands.
6342 uint32_t TZ = 0;
6343 for (const SCEV *Operand : M->operands())
6344 TZ += getMinTrailingZeros(Operand, CtxI);
6345 return GetShiftedByZeros(TZ);
6346 }
6347 case scAddExpr:
6348 case scAddRecExpr: {
6349 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6350 if (N->hasNoUnsignedWrap())
6351 return GetGCDMultiple(N);
6352 // Find the trailing bits, which is the minimum of its operands.
6353 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6354 for (const SCEV *Operand : N->operands().drop_front())
6355 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6356 return GetShiftedByZeros(TZ);
6357 }
6358 case scUMaxExpr:
6359 case scSMaxExpr:
6360 case scUMinExpr:
6361 case scSMinExpr:
6363 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6364 case scUnknown: {
6365 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6366 // the point their underlying IR instruction has been defined. If CtxI was
6367 // not provided, use:
6368 // * the first instruction in the entry block if it is an argument
6369 // * the instruction itself otherwise.
6370 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6371 if (!CtxI) {
6372 if (isa<Argument>(U->getValue()))
6373 CtxI = &*F.getEntryBlock().begin();
6374 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6375 CtxI = I;
6376 }
6377 unsigned Known =
6378 computeKnownBits(U->getValue(),
6379 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6380 .allowEphemerals(true))
6381 .countMinTrailingZeros();
6382 return GetShiftedByZeros(Known);
6383 }
6384 case scCouldNotCompute:
6385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6386 }
6387 llvm_unreachable("Unknown SCEV kind!");
6388}
6389
6391 const Instruction *CtxI) {
6392 // Skip looking up and updating the cache if there is a context instruction,
6393 // as the result will only be valid in the specified context.
6394 if (CtxI)
6395 return getConstantMultipleImpl(S, CtxI);
6396
6397 auto I = ConstantMultipleCache.find(S);
6398 if (I != ConstantMultipleCache.end())
6399 return I->second;
6400
6401 APInt Result = getConstantMultipleImpl(S, CtxI);
6402 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6403 assert(InsertPair.second && "Should insert a new key");
6404 return InsertPair.first->second;
6405}
6406
6408 APInt Multiple = getConstantMultiple(S);
6409 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6410}
6411
6413 const Instruction *CtxI) {
6414 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6415 (unsigned)getTypeSizeInBits(S->getType()));
6416}
6417
6418/// Helper method to assign a range to V from metadata present in the IR.
6419static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6421 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6422 return getConstantRangeFromMetadata(*MD);
6423 if (const auto *CB = dyn_cast<CallBase>(V))
6424 if (std::optional<ConstantRange> Range = CB->getRange())
6425 return Range;
6426 }
6427 if (auto *A = dyn_cast<Argument>(V))
6428 if (std::optional<ConstantRange> Range = A->getRange())
6429 return Range;
6430
6431 return std::nullopt;
6432}
6433
6435 SCEV::NoWrapFlags Flags) {
6436 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6437 AddRec->setNoWrapFlags(Flags);
6438 UnsignedRanges.erase(AddRec);
6439 SignedRanges.erase(AddRec);
6440 ConstantMultipleCache.erase(AddRec);
6441 }
6442}
6443
6444ConstantRange ScalarEvolution::
6445getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6446 const DataLayout &DL = getDataLayout();
6447
6448 unsigned BitWidth = getTypeSizeInBits(U->getType());
6449 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6450
6451 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6452 // use information about the trip count to improve our available range. Note
6453 // that the trip count independent cases are already handled by known bits.
6454 // WARNING: The definition of recurrence used here is subtly different than
6455 // the one used by AddRec (and thus most of this file). Step is allowed to
6456 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6457 // and other addrecs in the same loop (for non-affine addrecs). The code
6458 // below intentionally handles the case where step is not loop invariant.
6459 auto *P = dyn_cast<PHINode>(U->getValue());
6460 if (!P)
6461 return FullSet;
6462
6463 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6464 // even the values that are not available in these blocks may come from them,
6465 // and this leads to false-positive recurrence test.
6466 for (auto *Pred : predecessors(P->getParent()))
6467 if (!DT.isReachableFromEntry(Pred))
6468 return FullSet;
6469
6470 BinaryOperator *BO;
6471 Value *Start, *Step;
6472 if (!matchSimpleRecurrence(P, BO, Start, Step))
6473 return FullSet;
6474
6475 // If we found a recurrence in reachable code, we must be in a loop. Note
6476 // that BO might be in some subloop of L, and that's completely okay.
6477 auto *L = LI.getLoopFor(P->getParent());
6478 assert(L && L->getHeader() == P->getParent());
6479 if (!L->contains(BO->getParent()))
6480 // NOTE: This bailout should be an assert instead. However, asserting
6481 // the condition here exposes a case where LoopFusion is querying SCEV
6482 // with malformed loop information during the midst of the transform.
6483 // There doesn't appear to be an obvious fix, so for the moment bailout
6484 // until the caller issue can be fixed. PR49566 tracks the bug.
6485 return FullSet;
6486
6487 // TODO: Extend to other opcodes such as mul, and div
6488 switch (BO->getOpcode()) {
6489 default:
6490 return FullSet;
6491 case Instruction::AShr:
6492 case Instruction::LShr:
6493 case Instruction::Shl:
6494 break;
6495 };
6496
6497 if (BO->getOperand(0) != P)
6498 // TODO: Handle the power function forms some day.
6499 return FullSet;
6500
6501 unsigned TC = getSmallConstantMaxTripCount(L);
6502 if (!TC || TC >= BitWidth)
6503 return FullSet;
6504
6505 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6506 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6507 assert(KnownStart.getBitWidth() == BitWidth &&
6508 KnownStep.getBitWidth() == BitWidth);
6509
6510 // Compute total shift amount, being careful of overflow and bitwidths.
6511 auto MaxShiftAmt = KnownStep.getMaxValue();
6512 APInt TCAP(BitWidth, TC-1);
6513 bool Overflow = false;
6514 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6515 if (Overflow)
6516 return FullSet;
6517
6518 switch (BO->getOpcode()) {
6519 default:
6520 llvm_unreachable("filtered out above");
6521 case Instruction::AShr: {
6522 // For each ashr, three cases:
6523 // shift = 0 => unchanged value
6524 // saturation => 0 or -1
6525 // other => a value closer to zero (of the same sign)
6526 // Thus, the end value is closer to zero than the start.
6527 auto KnownEnd = KnownBits::ashr(KnownStart,
6528 KnownBits::makeConstant(TotalShift));
6529 if (KnownStart.isNonNegative())
6530 // Analogous to lshr (simply not yet canonicalized)
6531 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6532 KnownStart.getMaxValue() + 1);
6533 if (KnownStart.isNegative())
6534 // End >=u Start && End <=s Start
6535 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6536 KnownEnd.getMaxValue() + 1);
6537 break;
6538 }
6539 case Instruction::LShr: {
6540 // For each lshr, three cases:
6541 // shift = 0 => unchanged value
6542 // saturation => 0
6543 // other => a smaller positive number
6544 // Thus, the low end of the unsigned range is the last value produced.
6545 auto KnownEnd = KnownBits::lshr(KnownStart,
6546 KnownBits::makeConstant(TotalShift));
6547 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6548 KnownStart.getMaxValue() + 1);
6549 }
6550 case Instruction::Shl: {
6551 // Iff no bits are shifted out, value increases on every shift.
6552 auto KnownEnd = KnownBits::shl(KnownStart,
6553 KnownBits::makeConstant(TotalShift));
6554 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6555 return ConstantRange(KnownStart.getMinValue(),
6556 KnownEnd.getMaxValue() + 1);
6557 break;
6558 }
6559 };
6560 return FullSet;
6561}
6562
6563// The goal of this function is to check if recursively visiting the operands
6564// of this PHI might lead to an infinite loop. If we do see such a loop,
6565// there's no good way to break it, so we avoid analyzing such cases.
6566//
6567// getRangeRef previously used a visited set to avoid infinite loops, but this
6568// caused other issues: the result was dependent on the order of getRangeRef
6569// calls, and the interaction with createSCEVIter could cause a stack overflow
6570// in some cases (see issue #148253).
6571//
6572// FIXME: The way this is implemented is overly conservative; this checks
6573// for a few obviously safe patterns, but anything that doesn't lead to
6574// recursion is fine.
6576 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6578 return true;
6579
6580 if (all_of(PHI->operands(),
6581 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6582 return true;
6583
6584 return false;
6585}
6586
6587const ConstantRange &
6588ScalarEvolution::getRangeRefIter(const SCEV *S,
6589 ScalarEvolution::RangeSignHint SignHint) {
6590 DenseMap<const SCEV *, ConstantRange> &Cache =
6591 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6592 : SignedRanges;
6593 SmallVector<SCEVUse> WorkList;
6594 SmallPtrSet<const SCEV *, 8> Seen;
6595
6596 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6597 // SCEVUnknown PHI node.
6598 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6599 if (!Seen.insert(Expr).second)
6600 return;
6601 if (Cache.contains(Expr))
6602 return;
6603 switch (Expr->getSCEVType()) {
6604 case scUnknown:
6606 break;
6607 [[fallthrough]];
6608 case scConstant:
6609 case scVScale:
6610 case scTruncate:
6611 case scZeroExtend:
6612 case scSignExtend:
6613 case scPtrToAddr:
6614 case scAddExpr:
6615 case scMulExpr:
6616 case scUDivExpr:
6617 case scAddRecExpr:
6618 case scUMaxExpr:
6619 case scSMaxExpr:
6620 case scUMinExpr:
6621 case scSMinExpr:
6623 WorkList.push_back(Expr);
6624 break;
6625 case scCouldNotCompute:
6626 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6627 }
6628 };
6629 AddToWorklist(S);
6630
6631 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6632 for (unsigned I = 0; I != WorkList.size(); ++I) {
6633 const SCEV *P = WorkList[I];
6634 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6635 // If it is not a `SCEVUnknown`, just recurse into operands.
6636 if (!UnknownS) {
6637 for (const SCEV *Op : P->operands())
6638 AddToWorklist(Op);
6639 continue;
6640 }
6641 // `SCEVUnknown`'s require special treatment.
6642 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6643 if (!RangeRefPHIAllowedOperands(DT, P))
6644 continue;
6645 for (auto &Op : reverse(P->operands()))
6646 AddToWorklist(getSCEV(Op));
6647 }
6648 }
6649
6650 if (!WorkList.empty()) {
6651 // Use getRangeRef to compute ranges for items in the worklist in reverse
6652 // order. This will force ranges for earlier operands to be computed before
6653 // their users in most cases.
6654 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6655 getRangeRef(P, SignHint);
6656 }
6657 }
6658
6659 return getRangeRef(S, SignHint, 0);
6660}
6661
6662const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6663 if (const auto *C = dyn_cast<SCEVConstant>(S))
6664 return &C->getAPInt();
6665 return nullptr;
6666}
6667
6668/// Determine the range for a particular SCEV. If SignHint is
6669/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6670/// with a "cleaner" unsigned (resp. signed) representation.
6671const ConstantRange &ScalarEvolution::getRangeRef(
6672 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6673 DenseMap<const SCEV *, ConstantRange> &Cache =
6674 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6675 : SignedRanges;
6677 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6679
6680 // See if we've computed this range already.
6681 auto I = Cache.find(S);
6682 if (I != Cache.end())
6683 return I->second;
6684
6685 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6686 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6687
6688 // Switch to iteratively computing the range for S, if it is part of a deeply
6689 // nested expression.
6691 return getRangeRefIter(S, SignHint);
6692
6693 unsigned BitWidth = getTypeSizeInBits(S->getType());
6694 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6695 using OBO = OverflowingBinaryOperator;
6696
6697 // If the value has known zeros, the maximum value will have those known zeros
6698 // as well.
6699 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6700 APInt Multiple = getNonZeroConstantMultiple(S);
6701 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6702 if (!Remainder.isZero())
6703 ConservativeResult =
6704 ConstantRange(APInt::getMinValue(BitWidth),
6705 APInt::getMaxValue(BitWidth) - Remainder + 1);
6706 }
6707 else {
6708 uint32_t TZ = getMinTrailingZeros(S);
6709 if (TZ != 0) {
6710 ConservativeResult = ConstantRange(
6712 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6713 }
6714 }
6715
6716 switch (S->getSCEVType()) {
6717 case scConstant:
6718 llvm_unreachable("Already handled above.");
6719 case scVScale:
6720 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6721 case scTruncate: {
6722 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6723 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6724 return setRange(
6725 Trunc, SignHint,
6726 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6727 }
6728 case scZeroExtend: {
6729 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6730 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6731 return setRange(
6732 ZExt, SignHint,
6733 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6734 }
6735 case scSignExtend: {
6736 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6737 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6738 return setRange(
6739 SExt, SignHint,
6740 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6741 }
6742 case scPtrToAddr: {
6743 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6744 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6745 return setRange(Cast, SignHint, X);
6746 }
6747 case scAddExpr: {
6748 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6749 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6750 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6751 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6752 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6753 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6754 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6755 ConservativeResult =
6756 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6757 }
6758 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6759 unsigned WrapType = OBO::AnyWrap;
6760 if (Add->hasNoSignedWrap())
6761 WrapType |= OBO::NoSignedWrap;
6762 if (Add->hasNoUnsignedWrap())
6763 WrapType |= OBO::NoUnsignedWrap;
6764 for (const SCEV *Op : drop_begin(Add->operands()))
6765 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6766 RangeType);
6767 return setRange(Add, SignHint,
6768 ConservativeResult.intersectWith(X, RangeType));
6769 }
6770 case scMulExpr: {
6771 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6772 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6773 for (const SCEV *Op : drop_begin(Mul->operands()))
6774 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6775 return setRange(Mul, SignHint,
6776 ConservativeResult.intersectWith(X, RangeType));
6777 }
6778 case scUDivExpr: {
6779 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6780 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6781 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6782 return setRange(UDiv, SignHint,
6783 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6784 }
6785 case scAddRecExpr: {
6786 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6787 // If there's no unsigned wrap, the value will never be less than its
6788 // initial value.
6789 if (AddRec->hasNoUnsignedWrap()) {
6790 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6791 if (!UnsignedMinValue.isZero())
6792 ConservativeResult = ConservativeResult.intersectWith(
6793 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6794 }
6795
6796 // If there's no signed wrap, and all the operands except initial value have
6797 // the same sign or zero, the value won't ever be:
6798 // 1: smaller than initial value if operands are non negative,
6799 // 2: bigger than initial value if operands are non positive.
6800 // For both cases, value can not cross signed min/max boundary.
6801 if (AddRec->hasNoSignedWrap()) {
6802 bool AllNonNeg = true;
6803 bool AllNonPos = true;
6804 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6805 if (!isKnownNonNegative(AddRec->getOperand(i)))
6806 AllNonNeg = false;
6807 if (!isKnownNonPositive(AddRec->getOperand(i)))
6808 AllNonPos = false;
6809 }
6810 if (AllNonNeg)
6811 ConservativeResult = ConservativeResult.intersectWith(
6814 RangeType);
6815 else if (AllNonPos)
6816 ConservativeResult = ConservativeResult.intersectWith(
6818 getSignedRangeMax(AddRec->getStart()) +
6819 1),
6820 RangeType);
6821 }
6822
6823 // TODO: non-affine addrec
6824 if (AddRec->isAffine()) {
6825 const SCEV *MaxBEScev =
6827 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6828 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6829
6830 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6831 // MaxBECount's active bits are all <= AddRec's bit width.
6832 if (MaxBECount.getBitWidth() > BitWidth &&
6833 MaxBECount.getActiveBits() <= BitWidth)
6834 MaxBECount = MaxBECount.trunc(BitWidth);
6835 else if (MaxBECount.getBitWidth() < BitWidth)
6836 MaxBECount = MaxBECount.zext(BitWidth);
6837
6838 if (MaxBECount.getBitWidth() == BitWidth) {
6839 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6840 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6841 ConservativeResult =
6842 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6843 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6844
6845 auto RangeFromFactoring = getRangeViaFactoring(
6846 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6847 ConservativeResult =
6848 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6849 }
6850 }
6851
6852 // Now try symbolic BE count and more powerful methods.
6854 const SCEV *SymbolicMaxBECount =
6856 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6857 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6858 AddRec->hasNoSelfWrap()) {
6859 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6860 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6861 ConservativeResult =
6862 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6863 }
6864 }
6865 }
6866
6867 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6868 }
6869 case scUMaxExpr:
6870 case scSMaxExpr:
6871 case scUMinExpr:
6872 case scSMinExpr:
6873 case scSequentialUMinExpr: {
6875 switch (S->getSCEVType()) {
6876 case scUMaxExpr:
6877 ID = Intrinsic::umax;
6878 break;
6879 case scSMaxExpr:
6880 ID = Intrinsic::smax;
6881 break;
6882 case scUMinExpr:
6884 ID = Intrinsic::umin;
6885 break;
6886 case scSMinExpr:
6887 ID = Intrinsic::smin;
6888 break;
6889 default:
6890 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6891 }
6892
6893 const auto *NAry = cast<SCEVNAryExpr>(S);
6894 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6895 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6896 X = X.intrinsic(
6897 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6898 return setRange(S, SignHint,
6899 ConservativeResult.intersectWith(X, RangeType));
6900 }
6901 case scUnknown: {
6902 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6903 Value *V = U->getValue();
6904
6905 // Check if the IR explicitly contains !range metadata.
6906 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6907 if (MDRange)
6908 ConservativeResult =
6909 ConservativeResult.intersectWith(*MDRange, RangeType);
6910
6911 // Use facts about recurrences in the underlying IR. Note that add
6912 // recurrences are AddRecExprs and thus don't hit this path. This
6913 // primarily handles shift recurrences.
6914 auto CR = getRangeForUnknownRecurrence(U);
6915 ConservativeResult = ConservativeResult.intersectWith(CR);
6916
6917 // See if ValueTracking can give us a useful range.
6918 const DataLayout &DL = getDataLayout();
6919 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6920 if (Known.getBitWidth() != BitWidth)
6921 Known = Known.zextOrTrunc(BitWidth);
6922
6923 // ValueTracking may be able to compute a tighter result for the number of
6924 // sign bits than for the value of those sign bits.
6925 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6926 if (U->getType()->isPointerTy()) {
6927 // If the pointer size is larger than the index size type, this can cause
6928 // NS to be larger than BitWidth. So compensate for this.
6929 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
6930 int ptrIdxDiff = ptrSize - BitWidth;
6931 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
6932 NS -= ptrIdxDiff;
6933 }
6934
6935 if (NS > 1) {
6936 // If we know any of the sign bits, we know all of the sign bits.
6937 if (!Known.Zero.getHiBits(NS).isZero())
6938 Known.Zero.setHighBits(NS);
6939 if (!Known.One.getHiBits(NS).isZero())
6940 Known.One.setHighBits(NS);
6941 }
6942
6943 if (Known.getMinValue() != Known.getMaxValue() + 1)
6944 ConservativeResult = ConservativeResult.intersectWith(
6945 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6946 RangeType);
6947 if (NS > 1)
6948 ConservativeResult = ConservativeResult.intersectWith(
6949 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6950 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6951 RangeType);
6952
6953 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6954 // Strengthen the range if the underlying IR value is a
6955 // global/alloca/heap allocation using the size of the object.
6956 bool CanBeNull;
6957 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6958 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6959 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6960 // The highest address the object can start is DerefBytes bytes before
6961 // the end (unsigned max value). If this value is not a multiple of the
6962 // alignment, the last possible start value is the next lowest multiple
6963 // of the alignment. Note: The computations below cannot overflow,
6964 // because if they would there's no possible start address for the
6965 // object.
6966 APInt MaxVal =
6967 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6968 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6969 uint64_t Rem = MaxVal.urem(Align);
6970 MaxVal -= APInt(BitWidth, Rem);
6971 APInt MinVal = APInt::getZero(BitWidth);
6972 if (llvm::isKnownNonZero(V, DL))
6973 MinVal = Align;
6974 ConservativeResult = ConservativeResult.intersectWith(
6975 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6976 }
6977 }
6978
6979 // A range of Phi is a subset of union of all ranges of its input.
6980 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6981 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6982 // AddRecs; return the range for the corresponding AddRec.
6983 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6984 return getRangeRef(AR, SignHint, Depth + 1);
6985
6986 // Make sure that we do not run over cycled Phis.
6987 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6988 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6989
6990 for (const auto &Op : Phi->operands()) {
6991 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6992 RangeFromOps = RangeFromOps.unionWith(OpRange);
6993 // No point to continue if we already have a full set.
6994 if (RangeFromOps.isFullSet())
6995 break;
6996 }
6997 ConservativeResult =
6998 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6999 }
7000 }
7001
7002 // vscale can't be equal to zero
7003 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7004 if (II->getIntrinsicID() == Intrinsic::vscale) {
7005 ConstantRange Disallowed = APInt::getZero(BitWidth);
7006 ConservativeResult = ConservativeResult.difference(Disallowed);
7007 }
7008
7009 return setRange(U, SignHint, std::move(ConservativeResult));
7010 }
7011 case scCouldNotCompute:
7012 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7013 }
7014
7015 return setRange(S, SignHint, std::move(ConservativeResult));
7016}
7017
7018// Given a StartRange, Step and MaxBECount for an expression compute a range of
7019// values that the expression can take. Initially, the expression has a value
7020// from StartRange and then is changed by Step up to MaxBECount times. Signed
7021// argument defines if we treat Step as signed or unsigned. The second return
7022// value indicates that no wrapping occurred.
7023static std::pair<ConstantRange, bool>
7025 const APInt &MaxBECount, bool Signed) {
7026 unsigned BitWidth = Step.getBitWidth();
7027 assert(BitWidth == StartRange.getBitWidth() &&
7028 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7029 // If either Step or MaxBECount is 0, then the expression won't change, and we
7030 // just need to return the initial range.
7031 if (Step == 0 || MaxBECount == 0)
7032 return {StartRange, true};
7033
7034 // If we don't know anything about the initial value (i.e. StartRange is
7035 // FullRange), then we don't know anything about the final range either.
7036 // Return FullRange.
7037 if (StartRange.isFullSet())
7038 return {ConstantRange::getFull(BitWidth), false};
7039
7040 // If Step is signed and negative, then we use its absolute value, but we also
7041 // note that we're moving in the opposite direction.
7042 bool Descending = Signed && Step.isNegative();
7043
7044 if (Signed)
7045 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7046 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7047 // This equations hold true due to the well-defined wrap-around behavior of
7048 // APInt.
7049 Step = Step.abs();
7050
7051 // Check if Offset is more than full span of BitWidth. If it is, the
7052 // expression is guaranteed to overflow.
7053 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7054 return {ConstantRange::getFull(BitWidth), false};
7055
7056 // Offset is by how much the expression can change. Checks above guarantee no
7057 // overflow here.
7058 APInt Offset = Step * MaxBECount;
7059
7060 // Minimum value of the final range will match the minimal value of StartRange
7061 // if the expression is increasing and will be decreased by Offset otherwise.
7062 // Maximum value of the final range will match the maximal value of StartRange
7063 // if the expression is decreasing and will be increased by Offset otherwise.
7064 APInt StartLower = StartRange.getLower();
7065 APInt StartUpper = StartRange.getUpper() - 1;
7066 bool Overflow;
7067 APInt MovedBoundary;
7068 if (Signed) {
7069 // This does not use sadd_ov, as we want to check overflow for a signed
7070 // start with an unsigned offset.
7071 if (Descending) {
7072 MovedBoundary = StartLower - std::move(Offset);
7073 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7074 } else {
7075 MovedBoundary = StartUpper + std::move(Offset);
7076 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7077 }
7078 } else {
7079 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7080 Overflow |= StartRange.isWrappedSet();
7081 }
7082
7083 // It's possible that the new minimum/maximum value will fall into the initial
7084 // range (due to wrap around). This means that the expression can take any
7085 // value in this bitwidth, and we have to return full range.
7086 if (StartRange.contains(MovedBoundary))
7087 return {ConstantRange::getFull(BitWidth), false};
7088
7089 APInt NewLower =
7090 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7091 APInt NewUpper =
7092 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7093 NewUpper += 1;
7094
7095 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7096 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7097 !Overflow};
7098}
7099
7100std::pair<ConstantRange, SCEV::NoWrapFlags>
7101ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7102 const APInt &MaxBECount) {
7103 assert(getTypeSizeInBits(Start->getType()) ==
7104 getTypeSizeInBits(Step->getType()) &&
7105 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7106 "mismatched bit widths");
7107
7108 // First, consider step signed.
7109 ConstantRange StartSRange = getSignedRange(Start);
7110 ConstantRange StepSRange = getSignedRange(Step);
7111
7112 // If Step can be both positive and negative, we need to find ranges for the
7113 // maximum absolute step values in both directions and union them.
7114 auto [SR1, NSW1] = getRangeForAffineARHelper(
7115 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7116 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7117 StartSRange, MaxBECount,
7118 /*Signed=*/true);
7119 ConstantRange SR = SR1.unionWith(SR2);
7120
7121 // Next, consider step unsigned.
7122 auto [UR, NUW] = getRangeForAffineARHelper(
7123 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7124 /*Signed=*/false);
7125
7127 if (NUW)
7129 if (NSW1 && NSW2)
7131
7132 // Finally, intersect signed and unsigned ranges.
7134}
7135
7136ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7137 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7138 ScalarEvolution::RangeSignHint SignHint) {
7139 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7140 assert(AddRec->hasNoSelfWrap() &&
7141 "This only works for non-self-wrapping AddRecs!");
7142 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7143 const SCEV *Step = AddRec->getStepRecurrence(*this);
7144 // Only deal with constant step to save compile time.
7145 if (!isa<SCEVConstant>(Step))
7146 return ConstantRange::getFull(BitWidth);
7147 // Let's make sure that we can prove that we do not self-wrap during
7148 // MaxBECount iterations. We need this because MaxBECount is a maximum
7149 // iteration count estimate, and we might infer nw from some exit for which we
7150 // do not know max exit count (or any other side reasoning).
7151 // TODO: Turn into assert at some point.
7152 if (getTypeSizeInBits(MaxBECount->getType()) >
7153 getTypeSizeInBits(AddRec->getType()))
7154 return ConstantRange::getFull(BitWidth);
7155 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7156 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7157 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7158 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7159 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7160 MaxItersWithoutWrap))
7161 return ConstantRange::getFull(BitWidth);
7162
7163 ICmpInst::Predicate LEPred =
7165 ICmpInst::Predicate GEPred =
7167 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7168
7169 // We know that there is no self-wrap. Let's take Start and End values and
7170 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7171 // the iteration. They either lie inside the range [Min(Start, End),
7172 // Max(Start, End)] or outside it:
7173 //
7174 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7175 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7176 //
7177 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7178 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7179 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7180 // Start <= End and step is positive, or Start >= End and step is negative.
7181 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7182 ConstantRange StartRange = getRangeRef(Start, SignHint);
7183 ConstantRange EndRange = getRangeRef(End, SignHint);
7184 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7185 // If they already cover full iteration space, we will know nothing useful
7186 // even if we prove what we want to prove.
7187 if (RangeBetween.isFullSet())
7188 return RangeBetween;
7189 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7190 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7191 : RangeBetween.isWrappedSet();
7192 if (IsWrappedSet)
7193 return ConstantRange::getFull(BitWidth);
7194
7195 if (isKnownPositive(Step) &&
7196 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7197 return RangeBetween;
7198 if (isKnownNegative(Step) &&
7199 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7200 return RangeBetween;
7201 return ConstantRange::getFull(BitWidth);
7202}
7203
7204ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7205 const SCEV *Step,
7206 const APInt &MaxBECount) {
7207 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7208 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7209
7210 unsigned BitWidth = MaxBECount.getBitWidth();
7211 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7212 getTypeSizeInBits(Step->getType()) == BitWidth &&
7213 "mismatched bit widths");
7214
7215 struct SelectPattern {
7216 Value *Condition = nullptr;
7217 APInt TrueValue;
7218 APInt FalseValue;
7219
7220 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7221 const SCEV *S) {
7222 std::optional<unsigned> CastOp;
7223 APInt Offset(BitWidth, 0);
7224
7226 "Should be!");
7227
7228 // Peel off a constant offset. In the future we could consider being
7229 // smarter here and handle {Start+Step,+,Step} too.
7230 const APInt *Off;
7231 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7232 Offset = *Off;
7233
7234 // Peel off a cast operation
7235 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7236 CastOp = SCast->getSCEVType();
7237 S = SCast->getOperand();
7238 }
7239
7240 using namespace llvm::PatternMatch;
7241
7242 auto *SU = dyn_cast<SCEVUnknown>(S);
7243 const APInt *TrueVal, *FalseVal;
7244 if (!SU ||
7245 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7246 m_APInt(FalseVal)))) {
7247 Condition = nullptr;
7248 return;
7249 }
7250
7251 TrueValue = *TrueVal;
7252 FalseValue = *FalseVal;
7253
7254 // Re-apply the cast we peeled off earlier
7255 if (CastOp)
7256 switch (*CastOp) {
7257 default:
7258 llvm_unreachable("Unknown SCEV cast type!");
7259
7260 case scTruncate:
7261 TrueValue = TrueValue.trunc(BitWidth);
7262 FalseValue = FalseValue.trunc(BitWidth);
7263 break;
7264 case scZeroExtend:
7265 TrueValue = TrueValue.zext(BitWidth);
7266 FalseValue = FalseValue.zext(BitWidth);
7267 break;
7268 case scSignExtend:
7269 TrueValue = TrueValue.sext(BitWidth);
7270 FalseValue = FalseValue.sext(BitWidth);
7271 break;
7272 }
7273
7274 // Re-apply the constant offset we peeled off earlier
7275 TrueValue += Offset;
7276 FalseValue += Offset;
7277 }
7278
7279 bool isRecognized() { return Condition != nullptr; }
7280 };
7281
7282 SelectPattern StartPattern(*this, BitWidth, Start);
7283 if (!StartPattern.isRecognized())
7284 return ConstantRange::getFull(BitWidth);
7285
7286 SelectPattern StepPattern(*this, BitWidth, Step);
7287 if (!StepPattern.isRecognized())
7288 return ConstantRange::getFull(BitWidth);
7289
7290 if (StartPattern.Condition != StepPattern.Condition) {
7291 // We don't handle this case today; but we could, by considering four
7292 // possibilities below instead of two. I'm not sure if there are cases where
7293 // that will help over what getRange already does, though.
7294 return ConstantRange::getFull(BitWidth);
7295 }
7296
7297 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7298 // construct arbitrary general SCEV expressions here. This function is called
7299 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7300 // say) can end up caching a suboptimal value.
7301
7302 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7303 // C2352 and C2512 (otherwise it isn't needed).
7304
7305 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7306 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7307 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7308 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7309
7310 ConstantRange TrueRange =
7311 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7312 ConstantRange FalseRange =
7313 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7314
7315 return TrueRange.unionWith(FalseRange);
7316}
7317
7318SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7319 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7320 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7321
7322 // Return early if there are no flags to propagate to the SCEV.
7324 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7325 PDI && PDI->isDisjoint()) {
7327 } else {
7328 if (BinOp->hasNoUnsignedWrap())
7330 if (BinOp->hasNoSignedWrap())
7332 }
7333 if (Flags == SCEV::FlagAnyWrap)
7334 return SCEV::FlagAnyWrap;
7335
7336 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7337}
7338
7339const Instruction *
7340ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7341 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7342 return &*AddRec->getLoop()->getHeader()->begin();
7343 if (auto *U = dyn_cast<SCEVUnknown>(S))
7344 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7345 return I;
7346 return nullptr;
7347}
7348
7349const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7350 bool &Precise) {
7351 Precise = true;
7352 // Do a bounded search of the def relation of the requested SCEVs.
7353 SmallPtrSet<const SCEV *, 16> Visited;
7354 SmallVector<SCEVUse> Worklist;
7355 auto pushOp = [&](const SCEV *S) {
7356 if (!Visited.insert(S).second)
7357 return;
7358 // Threshold of 30 here is arbitrary.
7359 if (Visited.size() > 30) {
7360 Precise = false;
7361 return;
7362 }
7363 Worklist.push_back(S);
7364 };
7365
7366 for (SCEVUse S : Ops)
7367 pushOp(S);
7368
7369 const Instruction *Bound = nullptr;
7370 while (!Worklist.empty()) {
7371 SCEVUse S = Worklist.pop_back_val();
7372 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7373 if (!Bound || DT.dominates(Bound, DefI))
7374 Bound = DefI;
7375 } else {
7376 for (SCEVUse Op : S->operands())
7377 pushOp(Op);
7378 }
7379 }
7380 return Bound ? Bound : &*F.getEntryBlock().begin();
7381}
7382
7383const Instruction *
7384ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7385 bool Discard;
7386 return getDefiningScopeBound(Ops, Discard);
7387}
7388
7389bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7390 const Instruction *B) {
7391 if (A->getParent() == B->getParent() &&
7393 B->getIterator()))
7394 return true;
7395
7396 auto *BLoop = LI.getLoopFor(B->getParent());
7397 if (BLoop && BLoop->getHeader() == B->getParent() &&
7398 BLoop->getLoopPreheader() == A->getParent() &&
7400 A->getParent()->end()) &&
7401 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7402 B->getIterator()))
7403 return true;
7404 return false;
7405}
7406
7408 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7409 visitAll(Op, PC);
7410 return PC.MaybePoison.empty();
7411}
7412
7413bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7414 return !SCEVExprContains(Op, [this](const SCEV *S) {
7415 const SCEV *Op1;
7416 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7417 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7418 // is a non-zero constant, we have to assume the UDiv may be UB.
7419 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7420 });
7421}
7422
7423bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7424 // Only proceed if we can prove that I does not yield poison.
7426 return false;
7427
7428 // At this point we know that if I is executed, then it does not wrap
7429 // according to at least one of NSW or NUW. If I is not executed, then we do
7430 // not know if the calculation that I represents would wrap. Multiple
7431 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7432 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7433 // derived from other instructions that map to the same SCEV. We cannot make
7434 // that guarantee for cases where I is not executed. So we need to find a
7435 // upper bound on the defining scope for the SCEV, and prove that I is
7436 // executed every time we enter that scope. When the bounding scope is a
7437 // loop (the common case), this is equivalent to proving I executes on every
7438 // iteration of that loop.
7439 SmallVector<SCEVUse> SCEVOps;
7440 for (const Use &Op : I->operands()) {
7441 // I could be an extractvalue from a call to an overflow intrinsic.
7442 // TODO: We can do better here in some cases.
7443 if (isSCEVable(Op->getType()))
7444 SCEVOps.push_back(getSCEV(Op));
7445 }
7446 auto *DefI = getDefiningScopeBound(SCEVOps);
7447 return isGuaranteedToTransferExecutionTo(DefI, I);
7448}
7449
7450bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7451 // If we know that \c I can never be poison period, then that's enough.
7452 if (isSCEVExprNeverPoison(I))
7453 return true;
7454
7455 // If the loop only has one exit, then we know that, if the loop is entered,
7456 // any instruction dominating that exit will be executed. If any such
7457 // instruction would result in UB, the addrec cannot be poison.
7458 //
7459 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7460 // also handles uses outside the loop header (they just need to dominate the
7461 // single exit).
7462
7463 auto *ExitingBB = L->getExitingBlock();
7464 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7465 return false;
7466
7467 SmallPtrSet<const Value *, 16> KnownPoison;
7469
7470 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7471 // things that are known to be poison under that assumption go on the
7472 // Worklist.
7473 KnownPoison.insert(I);
7474 Worklist.push_back(I);
7475
7476 while (!Worklist.empty()) {
7477 const Instruction *Poison = Worklist.pop_back_val();
7478
7479 for (const Use &U : Poison->uses()) {
7480 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7481 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7482 DT.dominates(PoisonUser->getParent(), ExitingBB))
7483 return true;
7484
7485 if (propagatesPoison(U) && L->contains(PoisonUser))
7486 if (KnownPoison.insert(PoisonUser).second)
7487 Worklist.push_back(PoisonUser);
7488 }
7489 }
7490
7491 return false;
7492}
7493
7494ScalarEvolution::LoopProperties
7495ScalarEvolution::getLoopProperties(const Loop *L) {
7496 using LoopProperties = ScalarEvolution::LoopProperties;
7497
7498 auto Itr = LoopPropertiesCache.find(L);
7499 if (Itr == LoopPropertiesCache.end()) {
7500 auto HasSideEffects = [](Instruction *I) {
7501 if (auto *SI = dyn_cast<StoreInst>(I))
7502 return !SI->isSimple();
7503
7504 if (I->mayThrow())
7505 return true;
7506
7507 // Non-volatile memset / memcpy do not count as side-effect for forward
7508 // progress.
7509 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7510 return false;
7511
7512 return I->mayWriteToMemory();
7513 };
7514
7515 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7516 /*HasNoSideEffects*/ true};
7517
7518 for (auto *BB : L->getBlocks())
7519 for (auto &I : *BB) {
7521 LP.HasNoAbnormalExits = false;
7522 if (HasSideEffects(&I))
7523 LP.HasNoSideEffects = false;
7524 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7525 break; // We're already as pessimistic as we can get.
7526 }
7527
7528 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7529 assert(InsertPair.second && "We just checked!");
7530 Itr = InsertPair.first;
7531 }
7532
7533 return Itr->second;
7534}
7535
7537 // A mustprogress loop without side effects must be finite.
7538 // TODO: The check used here is very conservative. It's only *specific*
7539 // side effects which are well defined in infinite loops.
7540 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7541}
7542
7543const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7544 // Worklist item with a Value and a bool indicating whether all operands have
7545 // been visited already.
7548
7549 Stack.emplace_back(V, false);
7550 while (!Stack.empty()) {
7551 auto E = Stack.back();
7552 Value *CurV = E.getPointer();
7553
7554 if (getExistingSCEV(CurV)) {
7555 Stack.pop_back();
7556 continue;
7557 }
7558
7560 const SCEV *CreatedSCEV = nullptr;
7561 // If all operands have been visited already, create the SCEV.
7562 if (E.getInt()) {
7563 CreatedSCEV = createSCEV(CurV);
7564 } else {
7565 // Otherwise get the operands we need to create SCEV's for before creating
7566 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7567 // just use it.
7568 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7569 }
7570
7571 if (CreatedSCEV) {
7572 insertValueToMap(CurV, CreatedSCEV);
7573 Stack.pop_back();
7574 } else {
7575 Stack.back().setInt(true);
7576 // Queue its operands which need to be constructed.
7577 for (Value *Op : Ops)
7578 Stack.emplace_back(Op, false);
7579 }
7580 }
7581
7582 return getExistingSCEV(V);
7583}
7584
7585const SCEV *
7586ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7587 if (!isSCEVable(V->getType()))
7588 return getUnknown(V);
7589
7590 if (Instruction *I = dyn_cast<Instruction>(V)) {
7591 // Don't attempt to analyze instructions in blocks that aren't
7592 // reachable. Such instructions don't matter, and they aren't required
7593 // to obey basic rules for definitions dominating uses which this
7594 // analysis depends on.
7595 if (!DT.isReachableFromEntry(I->getParent()))
7596 return getUnknown(PoisonValue::get(V->getType()));
7597 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7598 return getConstant(CI);
7599 else if (isa<GlobalAlias>(V))
7600 return getUnknown(V);
7601 else if (!isa<ConstantExpr>(V))
7602 return getUnknown(V);
7603
7605 if (auto BO =
7607 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7608 switch (BO->Opcode) {
7609 case Instruction::Add:
7610 case Instruction::Mul: {
7611 // For additions and multiplications, traverse add/mul chains for which we
7612 // can potentially create a single SCEV, to reduce the number of
7613 // get{Add,Mul}Expr calls.
7614 do {
7615 if (BO->Op) {
7616 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7617 Ops.push_back(BO->Op);
7618 break;
7619 }
7620 }
7621 Ops.push_back(BO->RHS);
7622 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7624 if (!NewBO ||
7625 (BO->Opcode == Instruction::Add &&
7626 (NewBO->Opcode != Instruction::Add &&
7627 NewBO->Opcode != Instruction::Sub)) ||
7628 (BO->Opcode == Instruction::Mul &&
7629 NewBO->Opcode != Instruction::Mul)) {
7630 Ops.push_back(BO->LHS);
7631 break;
7632 }
7633 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7634 // requires a SCEV for the LHS.
7635 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7636 auto *I = dyn_cast<Instruction>(BO->Op);
7637 if (I && programUndefinedIfPoison(I)) {
7638 Ops.push_back(BO->LHS);
7639 break;
7640 }
7641 }
7642 BO = NewBO;
7643 } while (true);
7644 return nullptr;
7645 }
7646 case Instruction::Sub:
7647 case Instruction::UDiv:
7648 case Instruction::URem:
7649 break;
7650 case Instruction::AShr:
7651 case Instruction::Shl:
7652 case Instruction::Xor:
7653 if (!IsConstArg)
7654 return nullptr;
7655 break;
7656 case Instruction::And:
7657 case Instruction::Or:
7658 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7659 return nullptr;
7660 break;
7661 case Instruction::LShr:
7662 return getUnknown(V);
7663 default:
7664 llvm_unreachable("Unhandled binop");
7665 break;
7666 }
7667
7668 Ops.push_back(BO->LHS);
7669 Ops.push_back(BO->RHS);
7670 return nullptr;
7671 }
7672
7673 switch (U->getOpcode()) {
7674 case Instruction::Trunc:
7675 case Instruction::ZExt:
7676 case Instruction::SExt:
7677 case Instruction::PtrToAddr:
7678 case Instruction::PtrToInt:
7679 Ops.push_back(U->getOperand(0));
7680 return nullptr;
7681
7682 case Instruction::BitCast:
7683 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7684 Ops.push_back(U->getOperand(0));
7685 return nullptr;
7686 }
7687 return getUnknown(V);
7688
7689 case Instruction::SDiv:
7690 case Instruction::SRem:
7691 Ops.push_back(U->getOperand(0));
7692 Ops.push_back(U->getOperand(1));
7693 return nullptr;
7694
7695 case Instruction::GetElementPtr:
7696 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7697 "GEP source element type must be sized");
7698 llvm::append_range(Ops, U->operands());
7699 return nullptr;
7700
7701 case Instruction::IntToPtr:
7702 return getUnknown(V);
7703
7704 case Instruction::PHI:
7705 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7706 // relevant nodes for each of them.
7707 //
7708 // The first is just to call simplifyInstruction, and get something back
7709 // that isn't a PHI.
7710 if (Value *V = simplifyInstruction(
7711 cast<PHINode>(U),
7712 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7713 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7714 assert(V);
7715 Ops.push_back(V);
7716 return nullptr;
7717 }
7718 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7719 // operands which all perform the same operation, but haven't been
7720 // CSE'ed for whatever reason.
7721 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7722 assert(BO);
7723 Ops.push_back(BO);
7724 return nullptr;
7725 }
7726 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7727 // is equivalent to a select, and analyzes it like a select.
7728 {
7729 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7731 assert(Cond);
7732 assert(LHS);
7733 assert(RHS);
7734 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7735 Ops.push_back(CondICmp->getOperand(0));
7736 Ops.push_back(CondICmp->getOperand(1));
7737 }
7738 Ops.push_back(Cond);
7739 Ops.push_back(LHS);
7740 Ops.push_back(RHS);
7741 return nullptr;
7742 }
7743 }
7744 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7745 // so just construct it recursively.
7746 //
7747 // In addition to getNodeForPHI, also construct nodes which might be needed
7748 // by getRangeRef.
7750 for (Value *V : cast<PHINode>(U)->operands())
7751 Ops.push_back(V);
7752 return nullptr;
7753 }
7754 return nullptr;
7755
7756 case Instruction::Select: {
7757 // Check if U is a select that can be simplified to a SCEVUnknown.
7758 auto CanSimplifyToUnknown = [this, U]() {
7759 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7760 return false;
7761
7762 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7763 if (!ICI)
7764 return false;
7765 Value *LHS = ICI->getOperand(0);
7766 Value *RHS = ICI->getOperand(1);
7767 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7768 ICI->getPredicate() == CmpInst::ICMP_NE) {
7770 return true;
7771 } else if (getTypeSizeInBits(LHS->getType()) >
7772 getTypeSizeInBits(U->getType()))
7773 return true;
7774 return false;
7775 };
7776 if (CanSimplifyToUnknown())
7777 return getUnknown(U);
7778
7779 llvm::append_range(Ops, U->operands());
7780 return nullptr;
7781 break;
7782 }
7783 case Instruction::Call:
7784 case Instruction::Invoke:
7785 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7786 Ops.push_back(RV);
7787 return nullptr;
7788 }
7789
7790 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7791 switch (II->getIntrinsicID()) {
7792 case Intrinsic::abs:
7793 Ops.push_back(II->getArgOperand(0));
7794 return nullptr;
7795 case Intrinsic::umax:
7796 case Intrinsic::umin:
7797 case Intrinsic::smax:
7798 case Intrinsic::smin:
7799 case Intrinsic::usub_sat:
7800 case Intrinsic::uadd_sat:
7801 Ops.push_back(II->getArgOperand(0));
7802 Ops.push_back(II->getArgOperand(1));
7803 return nullptr;
7804 case Intrinsic::start_loop_iterations:
7805 case Intrinsic::annotation:
7806 case Intrinsic::ptr_annotation:
7807 Ops.push_back(II->getArgOperand(0));
7808 return nullptr;
7809 default:
7810 break;
7811 }
7812 }
7813 break;
7814 }
7815
7816 return nullptr;
7817}
7818
7819const SCEV *ScalarEvolution::createSCEV(Value *V) {
7820 if (!isSCEVable(V->getType()))
7821 return getUnknown(V);
7822
7823 if (Instruction *I = dyn_cast<Instruction>(V)) {
7824 // Don't attempt to analyze instructions in blocks that aren't
7825 // reachable. Such instructions don't matter, and they aren't required
7826 // to obey basic rules for definitions dominating uses which this
7827 // analysis depends on.
7828 if (!DT.isReachableFromEntry(I->getParent()))
7829 return getUnknown(PoisonValue::get(V->getType()));
7830 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7831 return getConstant(CI);
7832 else if (isa<GlobalAlias>(V))
7833 return getUnknown(V);
7834 else if (!isa<ConstantExpr>(V))
7835 return getUnknown(V);
7836
7837 const SCEV *LHS;
7838 const SCEV *RHS;
7839
7841 if (auto BO =
7843 switch (BO->Opcode) {
7844 case Instruction::Add: {
7845 // The simple thing to do would be to just call getSCEV on both operands
7846 // and call getAddExpr with the result. However if we're looking at a
7847 // bunch of things all added together, this can be quite inefficient,
7848 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7849 // Instead, gather up all the operands and make a single getAddExpr call.
7850 // LLVM IR canonical form means we need only traverse the left operands.
7852 do {
7853 if (BO->Op) {
7854 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7855 AddOps.push_back(OpSCEV);
7856 break;
7857 }
7858
7859 // If a NUW or NSW flag can be applied to the SCEV for this
7860 // addition, then compute the SCEV for this addition by itself
7861 // with a separate call to getAddExpr. We need to do that
7862 // instead of pushing the operands of the addition onto AddOps,
7863 // since the flags are only known to apply to this particular
7864 // addition - they may not apply to other additions that can be
7865 // formed with operands from AddOps.
7866 const SCEV *RHS = getSCEV(BO->RHS);
7867 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7868 if (Flags != SCEV::FlagAnyWrap) {
7869 const SCEV *LHS = getSCEV(BO->LHS);
7870 if (BO->Opcode == Instruction::Sub)
7871 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7872 else
7873 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7874 break;
7875 }
7876 }
7877
7878 if (BO->Opcode == Instruction::Sub)
7879 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7880 else
7881 AddOps.push_back(getSCEV(BO->RHS));
7882
7883 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7885 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7886 NewBO->Opcode != Instruction::Sub)) {
7887 AddOps.push_back(getSCEV(BO->LHS));
7888 break;
7889 }
7890 BO = NewBO;
7891 } while (true);
7892
7893 return getAddExpr(AddOps);
7894 }
7895
7896 case Instruction::Mul: {
7898 do {
7899 if (BO->Op) {
7900 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7901 MulOps.push_back(OpSCEV);
7902 break;
7903 }
7904
7905 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7906 if (Flags != SCEV::FlagAnyWrap) {
7907 LHS = getSCEV(BO->LHS);
7908 RHS = getSCEV(BO->RHS);
7909 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7910 break;
7911 }
7912 }
7913
7914 MulOps.push_back(getSCEV(BO->RHS));
7915 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7917 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7918 MulOps.push_back(getSCEV(BO->LHS));
7919 break;
7920 }
7921 BO = NewBO;
7922 } while (true);
7923
7924 return getMulExpr(MulOps);
7925 }
7926 case Instruction::UDiv:
7927 LHS = getSCEV(BO->LHS);
7928 RHS = getSCEV(BO->RHS);
7929 return getUDivExpr(LHS, RHS);
7930 case Instruction::URem:
7931 LHS = getSCEV(BO->LHS);
7932 RHS = getSCEV(BO->RHS);
7933 return getURemExpr(LHS, RHS);
7934 case Instruction::Sub: {
7936 if (BO->Op)
7937 Flags = getNoWrapFlagsFromUB(BO->Op);
7938
7939 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7940 // operand. While we don't model ptrtoint directly in SCEV, the
7941 // difference between two pointer addresses is well-defined.
7942 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7943 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7944 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7945 if (HasPtrLHS || HasPtrRHS) {
7946 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7947 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7948 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7949 // useful structure.
7950 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7951 bool BothPtr) -> const SCEV * {
7952 if (!HasPtr)
7953 return getSCEV(OrigOp);
7954 const SCEV *PtrSCEV = getSCEV(PtrOp);
7955 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7956 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7957 if (!isa<SCEVCouldNotCompute>(Addr) &&
7958 getTypeSizeInBits(OrigOp->getType()) <=
7959 getTypeSizeInBits(Addr->getType()))
7960 return getTruncateOrNoop(Addr, OrigOp->getType());
7961 }
7962 return getSCEV(OrigOp);
7963 };
7964 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7965 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7966 return getMinusSCEV(L, R, Flags);
7967 }
7968
7969 LHS = getSCEV(BO->LHS);
7970 RHS = getSCEV(BO->RHS);
7971 return getMinusSCEV(LHS, RHS, Flags);
7972 }
7973 case Instruction::And:
7974 // For an expression like x&255 that merely masks off the high bits,
7975 // use zext(trunc(x)) as the SCEV expression.
7976 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7977 if (CI->isZero())
7978 return getSCEV(BO->RHS);
7979 if (CI->isMinusOne())
7980 return getSCEV(BO->LHS);
7981 const APInt &A = CI->getValue();
7982
7983 // Instcombine's ShrinkDemandedConstant may strip bits out of
7984 // constants, obscuring what would otherwise be a low-bits mask.
7985 // Use computeKnownBits to compute what ShrinkDemandedConstant
7986 // knew about to reconstruct a low-bits mask value.
7987 unsigned LZ = A.countl_zero();
7988 unsigned TZ = A.countr_zero();
7989 unsigned BitWidth = A.getBitWidth();
7990 KnownBits Known(BitWidth);
7991 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
7992
7993 APInt EffectiveMask =
7994 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
7995 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
7996 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
7997 const SCEV *LHS = getSCEV(BO->LHS);
7998 const SCEV *ShiftedLHS = nullptr;
7999 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8000 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8001 // For an expression like (x * 8) & 8, simplify the multiply.
8002 unsigned MulZeros = OpC->getAPInt().countr_zero();
8003 unsigned GCD = std::min(MulZeros, TZ);
8004 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8006 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8007 append_range(MulOps, LHSMul->operands().drop_front());
8008 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8009 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8010 }
8011 }
8012 if (!ShiftedLHS)
8013 ShiftedLHS = getUDivExpr(LHS, MulCount);
8014 return getMulExpr(
8016 getTruncateExpr(ShiftedLHS,
8017 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8018 BO->LHS->getType()),
8019 MulCount);
8020 }
8021 }
8022 // Binary `and` is a bit-wise `umin`.
8023 if (BO->LHS->getType()->isIntegerTy(1)) {
8024 LHS = getSCEV(BO->LHS);
8025 RHS = getSCEV(BO->RHS);
8026 return getUMinExpr(LHS, RHS);
8027 }
8028 break;
8029
8030 case Instruction::Or:
8031 // Binary `or` is a bit-wise `umax`.
8032 if (BO->LHS->getType()->isIntegerTy(1)) {
8033 LHS = getSCEV(BO->LHS);
8034 RHS = getSCEV(BO->RHS);
8035 return getUMaxExpr(LHS, RHS);
8036 }
8037 break;
8038
8039 case Instruction::Xor:
8040 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8041 // If the RHS of xor is -1, then this is a not operation.
8042 if (CI->isMinusOne())
8043 return getNotSCEV(getSCEV(BO->LHS));
8044
8045 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8046 // This is a variant of the check for xor with -1, and it handles
8047 // the case where instcombine has trimmed non-demanded bits out
8048 // of an xor with -1.
8049 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8050 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8051 if (LBO->getOpcode() == Instruction::And &&
8052 LCI->getValue() == CI->getValue())
8053 if (const SCEVZeroExtendExpr *Z =
8055 Type *UTy = BO->LHS->getType();
8056 const SCEV *Z0 = Z->getOperand();
8057 Type *Z0Ty = Z0->getType();
8058 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8059
8060 // If C is a low-bits mask, the zero extend is serving to
8061 // mask off the high bits. Complement the operand and
8062 // re-apply the zext.
8063 if (CI->getValue().isMask(Z0TySize))
8064 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8065
8066 // If C is a single bit, it may be in the sign-bit position
8067 // before the zero-extend. In this case, represent the xor
8068 // using an add, which is equivalent, and re-apply the zext.
8069 APInt Trunc = CI->getValue().trunc(Z0TySize);
8070 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8071 Trunc.isSignMask())
8072 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8073 UTy);
8074 }
8075 }
8076 break;
8077
8078 case Instruction::Shl:
8079 // Turn shift left of a constant amount into a multiply.
8080 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8081 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8082
8083 // If the shift count is not less than the bitwidth, the result of
8084 // the shift is undefined. Don't try to analyze it, because the
8085 // resolution chosen here may differ from the resolution chosen in
8086 // other parts of the compiler.
8087 if (SA->getValue().uge(BitWidth))
8088 break;
8089
8090 // We can safely preserve the nuw flag in all cases. It's also safe to
8091 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8092 // requires special handling. It can be preserved as long as we're not
8093 // left shifting by bitwidth - 1.
8094 auto Flags = SCEV::FlagAnyWrap;
8095 if (BO->Op) {
8096 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8097 if (any(MulFlags & SCEV::FlagNSW) &&
8098 (any(MulFlags & SCEV::FlagNUW) ||
8099 SA->getValue().ult(BitWidth - 1)))
8101 if (any(MulFlags & SCEV::FlagNUW))
8103 }
8104
8105 ConstantInt *X = ConstantInt::get(
8106 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8107 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8108 }
8109 break;
8110
8111 case Instruction::AShr:
8112 // AShr X, C, where C is a constant.
8113 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8114 if (!CI)
8115 break;
8116
8117 Type *OuterTy = BO->LHS->getType();
8119 // If the shift count is not less than the bitwidth, the result of
8120 // the shift is undefined. Don't try to analyze it, because the
8121 // resolution chosen here may differ from the resolution chosen in
8122 // other parts of the compiler.
8123 if (CI->getValue().uge(BitWidth))
8124 break;
8125
8126 if (CI->isZero())
8127 return getSCEV(BO->LHS); // shift by zero --> noop
8128
8129 uint64_t AShrAmt = CI->getZExtValue();
8130 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8131
8132 Operator *L = dyn_cast<Operator>(BO->LHS);
8133 const SCEV *AddTruncateExpr = nullptr;
8134 ConstantInt *ShlAmtCI = nullptr;
8135 const SCEV *AddConstant = nullptr;
8136
8137 if (L && L->getOpcode() == Instruction::Add) {
8138 // X = Shl A, n
8139 // Y = Add X, c
8140 // Z = AShr Y, m
8141 // n, c and m are constants.
8142
8143 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8144 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8145 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8146 if (AddOperandCI) {
8147 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8148 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8149 // since we truncate to TruncTy, the AddConstant should be of the
8150 // same type, so create a new Constant with type same as TruncTy.
8151 // Also, the Add constant should be shifted right by AShr amount.
8152 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8153 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8154 // we model the expression as sext(add(trunc(A), c << n)), since the
8155 // sext(trunc) part is already handled below, we create a
8156 // AddExpr(TruncExp) which will be used later.
8157 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8158 }
8159 }
8160 } else if (L && L->getOpcode() == Instruction::Shl) {
8161 // X = Shl A, n
8162 // Y = AShr X, m
8163 // Both n and m are constant.
8164
8165 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8166 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8167 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8168 }
8169
8170 if (AddTruncateExpr && ShlAmtCI) {
8171 // We can merge the two given cases into a single SCEV statement,
8172 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8173 // a simpler case. The following code handles the two cases:
8174 //
8175 // 1) For a two-shift sext-inreg, i.e. n = m,
8176 // use sext(trunc(x)) as the SCEV expression.
8177 //
8178 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8179 // expression. We already checked that ShlAmt < BitWidth, so
8180 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8181 // ShlAmt - AShrAmt < Amt.
8182 const APInt &ShlAmt = ShlAmtCI->getValue();
8183 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8184 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8185 ShlAmtCI->getZExtValue() - AShrAmt);
8186 const SCEV *CompositeExpr =
8187 getMulExpr(AddTruncateExpr, getConstant(Mul));
8188 if (L->getOpcode() != Instruction::Shl)
8189 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8190
8191 return getSignExtendExpr(CompositeExpr, OuterTy);
8192 }
8193 }
8194 break;
8195 }
8196 }
8197
8198 switch (U->getOpcode()) {
8199 case Instruction::Trunc:
8200 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8201
8202 case Instruction::ZExt:
8203 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8204
8205 case Instruction::SExt:
8206 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8208 // The NSW flag of a subtract does not always survive the conversion to
8209 // A + (-1)*B. By pushing sign extension onto its operands we are much
8210 // more likely to preserve NSW and allow later AddRec optimisations.
8211 //
8212 // NOTE: This is effectively duplicating this logic from getSignExtend:
8213 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8214 // but by that point the NSW information has potentially been lost.
8215 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8216 Type *Ty = U->getType();
8217 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8218 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8219 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8220 }
8221 }
8222 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8223
8224 case Instruction::BitCast:
8225 // BitCasts are no-op casts so we just eliminate the cast.
8226 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8227 return getSCEV(U->getOperand(0));
8228 break;
8229
8230 case Instruction::PtrToAddr: {
8231 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8232 if (isa<SCEVCouldNotCompute>(IntOp))
8233 return getUnknown(V);
8234 return IntOp;
8235 }
8236
8237 case Instruction::PtrToInt:
8238 // SCEV only models ptrtoaddr.
8239 return getUnknown(V);
8240
8241 case Instruction::IntToPtr:
8242 // Just don't deal with inttoptr casts.
8243 return getUnknown(V);
8244
8245 case Instruction::SDiv:
8246 // If both operands are non-negative, this is just an udiv.
8247 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8248 isKnownNonNegative(getSCEV(U->getOperand(1))))
8249 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8250 break;
8251
8252 case Instruction::SRem:
8253 // If both operands are non-negative, this is just an urem.
8254 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8255 isKnownNonNegative(getSCEV(U->getOperand(1))))
8256 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8257 break;
8258
8259 case Instruction::GetElementPtr:
8260 return createNodeForGEP(cast<GEPOperator>(U));
8261
8262 case Instruction::PHI:
8263 return createNodeForPHI(cast<PHINode>(U));
8264
8265 case Instruction::Select:
8266 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8267 U->getOperand(2));
8268
8269 case Instruction::Call:
8270 case Instruction::Invoke:
8271 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8272 return getSCEV(RV);
8273
8274 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8275 switch (II->getIntrinsicID()) {
8276 case Intrinsic::abs:
8277 return getAbsExpr(
8278 getSCEV(II->getArgOperand(0)),
8279 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8280 case Intrinsic::umax:
8281 LHS = getSCEV(II->getArgOperand(0));
8282 RHS = getSCEV(II->getArgOperand(1));
8283 return getUMaxExpr(LHS, RHS);
8284 case Intrinsic::umin:
8285 LHS = getSCEV(II->getArgOperand(0));
8286 RHS = getSCEV(II->getArgOperand(1));
8287 return getUMinExpr(LHS, RHS);
8288 case Intrinsic::smax:
8289 LHS = getSCEV(II->getArgOperand(0));
8290 RHS = getSCEV(II->getArgOperand(1));
8291 return getSMaxExpr(LHS, RHS);
8292 case Intrinsic::smin:
8293 LHS = getSCEV(II->getArgOperand(0));
8294 RHS = getSCEV(II->getArgOperand(1));
8295 return getSMinExpr(LHS, RHS);
8296 case Intrinsic::usub_sat: {
8297 const SCEV *X = getSCEV(II->getArgOperand(0));
8298 const SCEV *Y = getSCEV(II->getArgOperand(1));
8299 const SCEV *ClampedY = getUMinExpr(X, Y);
8300 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8301 }
8302 case Intrinsic::uadd_sat: {
8303 const SCEV *X = getSCEV(II->getArgOperand(0));
8304 const SCEV *Y = getSCEV(II->getArgOperand(1));
8305 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8306 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8307 }
8308 case Intrinsic::start_loop_iterations:
8309 case Intrinsic::annotation:
8310 case Intrinsic::ptr_annotation:
8311 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8312 // just eqivalent to the first operand for SCEV purposes.
8313 return getSCEV(II->getArgOperand(0));
8314 case Intrinsic::vscale:
8315 return getVScale(II->getType());
8316 default:
8317 break;
8318 }
8319 }
8320 break;
8321 }
8322
8323 return getUnknown(V);
8324}
8325
8326//===----------------------------------------------------------------------===//
8327// Iteration Count Computation Code
8328//
8329
8331 if (isa<SCEVCouldNotCompute>(ExitCount))
8332 return getCouldNotCompute();
8333
8334 auto *ExitCountType = ExitCount->getType();
8335 assert(ExitCountType->isIntegerTy());
8336 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8337 1 + ExitCountType->getScalarSizeInBits());
8338 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8339}
8340
8342 Type *EvalTy,
8343 const Loop *L) {
8344 if (isa<SCEVCouldNotCompute>(ExitCount))
8345 return getCouldNotCompute();
8346
8347 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8348 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8349
8350 auto CanAddOneWithoutOverflow = [&]() {
8351 ConstantRange ExitCountRange =
8352 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8353 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8354 return true;
8355
8356 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8357 getMinusOne(ExitCount->getType()));
8358 };
8359
8360 // If we need to zero extend the backedge count, check if we can add one to
8361 // it prior to zero extending without overflow. Provided this is safe, it
8362 // allows better simplification of the +1.
8363 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8364 return getZeroExtendExpr(
8365 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8366
8367 // Get the total trip count from the count by adding 1. This may wrap.
8368 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8369}
8370
8371static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8372 if (!ExitCount)
8373 return 0;
8374
8375 ConstantInt *ExitConst = ExitCount->getValue();
8376
8377 // Guard against huge trip counts.
8378 if (ExitConst->getValue().getActiveBits() > 32)
8379 return 0;
8380
8381 // In case of integer overflow, this returns 0, which is correct.
8382 return ((unsigned)ExitConst->getZExtValue()) + 1;
8383}
8384
8386 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8387 return getConstantTripCount(ExitCount);
8388}
8389
8390unsigned
8392 const BasicBlock *ExitingBlock) {
8393 assert(ExitingBlock && "Must pass a non-null exiting block!");
8394 assert(L->isLoopExiting(ExitingBlock) &&
8395 "Exiting block must actually branch out of the loop!");
8396 const SCEVConstant *ExitCount =
8397 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8398 return getConstantTripCount(ExitCount);
8399}
8400
8402 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8403
8404 const auto *MaxExitCount =
8405 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8407 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8408}
8409
8411 SmallVector<BasicBlock *, 8> ExitingBlocks;
8412 L->getExitingBlocks(ExitingBlocks);
8413
8414 std::optional<unsigned> Res;
8415 for (auto *ExitingBB : ExitingBlocks) {
8416 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8417 if (!Res)
8418 Res = Multiple;
8419 Res = std::gcd(*Res, Multiple);
8420 }
8421 return Res.value_or(1);
8422}
8423
8425 const SCEV *ExitCount) {
8426 if (isa<SCEVCouldNotCompute>(ExitCount))
8427 return 1;
8428
8429 // Get the trip count
8430 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8431
8432 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8433 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8434 // the greatest power of 2 divisor less than 2^32.
8435 return Multiple.getActiveBits() > 32
8436 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8437 : (unsigned)Multiple.getZExtValue();
8438}
8439
8440/// Returns the largest constant divisor of the trip count of this loop as a
8441/// normal unsigned value, if possible. This means that the actual trip count is
8442/// always a multiple of the returned value (don't forget the trip count could
8443/// very well be zero as well!).
8444///
8445/// Returns 1 if the trip count is unknown or not guaranteed to be the
8446/// multiple of a constant (which is also the case if the trip count is simply
8447/// constant, use getSmallConstantTripCount for that case), Will also return 1
8448/// if the trip count is very large (>= 2^32).
8449///
8450/// As explained in the comments for getSmallConstantTripCount, this assumes
8451/// that control exits the loop via ExitingBlock.
8452unsigned
8454 const BasicBlock *ExitingBlock) {
8455 assert(ExitingBlock && "Must pass a non-null exiting block!");
8456 assert(L->isLoopExiting(ExitingBlock) &&
8457 "Exiting block must actually branch out of the loop!");
8458 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8459 return getSmallConstantTripMultiple(L, ExitCount);
8460}
8461
8463 const BasicBlock *ExitingBlock,
8464 ExitCountKind Kind) {
8465 switch (Kind) {
8466 case Exact:
8467 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8468 case SymbolicMaximum:
8469 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8470 case ConstantMaximum:
8471 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8472 };
8473 llvm_unreachable("Invalid ExitCountKind!");
8474}
8475
8477 const Loop *L, const BasicBlock *ExitingBlock,
8479 switch (Kind) {
8480 case Exact:
8481 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8482 Predicates);
8483 case SymbolicMaximum:
8484 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8485 Predicates);
8486 case ConstantMaximum:
8487 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8488 Predicates);
8489 };
8490 llvm_unreachable("Invalid ExitCountKind!");
8491}
8492
8495 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8496}
8497
8499 ExitCountKind Kind) {
8500 switch (Kind) {
8501 case Exact:
8502 return getBackedgeTakenInfo(L).getExact(L, this);
8503 case ConstantMaximum:
8504 return getBackedgeTakenInfo(L).getConstantMax(this);
8505 case SymbolicMaximum:
8506 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8507 };
8508 llvm_unreachable("Invalid ExitCountKind!");
8509}
8510
8513 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8514}
8515
8518 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8519}
8520
8522 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8523}
8524
8525/// Push PHI nodes in the header of the given loop onto the given Worklist.
8526static void PushLoopPHIs(const Loop *L,
8529 BasicBlock *Header = L->getHeader();
8530
8531 // Push all Loop-header PHIs onto the Worklist stack.
8532 for (PHINode &PN : Header->phis())
8533 if (Visited.insert(&PN).second)
8534 Worklist.push_back(&PN);
8535}
8536
8537ScalarEvolution::BackedgeTakenInfo &
8538ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8539 auto &BTI = getBackedgeTakenInfo(L);
8540 if (BTI.hasFullInfo())
8541 return BTI;
8542
8543 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8544
8545 if (!Pair.second)
8546 return Pair.first->second;
8547
8548 BackedgeTakenInfo Result =
8549 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8550
8551 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8552}
8553
8554ScalarEvolution::BackedgeTakenInfo &
8555ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8556 // Initially insert an invalid entry for this loop. If the insertion
8557 // succeeds, proceed to actually compute a backedge-taken count and
8558 // update the value. The temporary CouldNotCompute value tells SCEV
8559 // code elsewhere that it shouldn't attempt to request a new
8560 // backedge-taken count, which could result in infinite recursion.
8561 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8562 BackedgeTakenCounts.try_emplace(L);
8563 if (!Pair.second)
8564 return Pair.first->second;
8565
8566 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8567 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8568 // must be cleared in this scope.
8569 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8570
8571 // Now that we know more about the trip count for this loop, forget any
8572 // existing SCEV values for PHI nodes in this loop since they are only
8573 // conservative estimates made without the benefit of trip count
8574 // information. This invalidation is not necessary for correctness, and is
8575 // only done to produce more precise results.
8576 if (Result.hasAnyInfo()) {
8577 // Invalidate any expression using an addrec in this loop.
8578 SmallVector<SCEVUse, 8> ToForget;
8579 auto LoopUsersIt = LoopUsers.find(L);
8580 if (LoopUsersIt != LoopUsers.end())
8581 append_range(ToForget, LoopUsersIt->second);
8582 forgetMemoizedResults(ToForget);
8583
8584 // Invalidate constant-evolved loop header phis.
8585 for (PHINode &PN : L->getHeader()->phis())
8586 ConstantEvolutionLoopExitValue.erase(&PN);
8587 }
8588
8589 // Re-lookup the insert position, since the call to
8590 // computeBackedgeTakenCount above could result in a
8591 // recusive call to getBackedgeTakenInfo (on a different
8592 // loop), which would invalidate the iterator computed
8593 // earlier.
8594 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8595}
8596
8598 // This method is intended to forget all info about loops. It should
8599 // invalidate caches as if the following happened:
8600 // - The trip counts of all loops have changed arbitrarily
8601 // - Every llvm::Value has been updated in place to produce a different
8602 // result.
8603 BackedgeTakenCounts.clear();
8604 PredicatedBackedgeTakenCounts.clear();
8605 BECountUsers.clear();
8606 LoopPropertiesCache.clear();
8607 ConstantEvolutionLoopExitValue.clear();
8608 ValueExprMap.clear();
8609 ValuesAtScopes.clear();
8610 ValuesAtScopesUsers.clear();
8611 LoopDispositions.clear();
8612 BlockDispositions.clear();
8613 UnsignedRanges.clear();
8614 SignedRanges.clear();
8615 ExprValueMap.clear();
8616 HasRecMap.clear();
8617 ConstantMultipleCache.clear();
8618 PredicatedSCEVRewrites.clear();
8619 FoldCache.clear();
8620 FoldCacheUser.clear();
8621}
8622void ScalarEvolution::visitAndClearUsers(
8625 SmallVectorImpl<SCEVUse> &ToForget) {
8626 while (!Worklist.empty()) {
8627 Instruction *I = Worklist.pop_back_val();
8628 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8629 continue;
8630
8632 ValueExprMap.find_as(static_cast<Value *>(I));
8633 if (It != ValueExprMap.end()) {
8634 ToForget.push_back(It->second);
8635 eraseValueFromMap(It->first);
8636 if (PHINode *PN = dyn_cast<PHINode>(I))
8637 ConstantEvolutionLoopExitValue.erase(PN);
8638 }
8639
8640 PushDefUseChildren(I, Worklist, Visited);
8641 }
8642}
8643
8645 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8648 SmallVector<SCEVUse, 16> ToForget;
8649
8650 // Iterate over all the loops and sub-loops to drop SCEV information.
8651 while (!LoopWorklist.empty()) {
8652 auto *CurrL = LoopWorklist.pop_back_val();
8653
8654 // Drop any stored trip count value.
8655 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8656 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8657
8658 // Drop information about predicated SCEV rewrites for this loop.
8659 PredicatedSCEVRewrites.remove_if(
8660 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8661
8662 auto LoopUsersItr = LoopUsers.find(CurrL);
8663 if (LoopUsersItr != LoopUsers.end())
8664 llvm::append_range(ToForget, LoopUsersItr->second);
8665
8666 // Drop information about expressions based on loop-header PHIs.
8667 PushLoopPHIs(CurrL, Worklist, Visited);
8668 visitAndClearUsers(Worklist, Visited, ToForget);
8669
8670 LoopPropertiesCache.erase(CurrL);
8671 // Forget all contained loops too, to avoid dangling entries in the
8672 // ValuesAtScopes map.
8673 LoopWorklist.append(CurrL->begin(), CurrL->end());
8674 }
8675 forgetMemoizedResults(ToForget);
8676}
8677
8679 forgetLoop(L->getOutermostLoop());
8680}
8681
8684 if (!I) return;
8685
8686 // Drop information about expressions based on loop-header PHIs.
8689 SmallVector<SCEVUse, 8> ToForget;
8690 Worklist.push_back(I);
8691 Visited.insert(I);
8692 visitAndClearUsers(Worklist, Visited, ToForget);
8693
8694 forgetMemoizedResults(ToForget);
8695}
8696
8698 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8699 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8700 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8701 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8702 auto InvalidateValue = [&](Value *Val) {
8703 if (!isSCEVable(Val->getType()))
8704 return;
8705 if (const SCEV *S = getExistingSCEV(Val)) {
8706 struct InvalidationRootCollector {
8707 Loop *L;
8709
8710 InvalidationRootCollector(Loop *L) : L(L) {}
8711
8712 bool follow(const SCEV *S) {
8713 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8714 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8715 if (L->contains(I))
8716 Roots.push_back(S);
8717 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8718 if (L->contains(AddRec->getLoop()))
8719 Roots.push_back(S);
8720 }
8721 return true;
8722 }
8723 bool isDone() const { return false; }
8724 };
8725
8726 InvalidationRootCollector C(L);
8727 visitAll(S, C);
8728 forgetMemoizedResults(C.Roots);
8729 }
8730 };
8731
8732 InvalidateValue(V);
8733
8734 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8735 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8736 // expressions referencing loop-internal values.
8737 if (!isSCEVable(V->getType()) && any_of(V->incoming_values(), [](Value *Inc) {
8738 return isa<WithOverflowInst>(Inc);
8739 }))
8740 for (User *U : V->users())
8741 InvalidateValue(U);
8742 // Also perform the normal invalidation.
8743 forgetValue(V);
8744}
8745
8746void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8747
8749 // Unless a specific value is passed to invalidation, completely clear both
8750 // caches.
8751 if (!V) {
8752 BlockDispositions.clear();
8753 LoopDispositions.clear();
8754 return;
8755 }
8756
8757 if (!isSCEVable(V->getType()))
8758 return;
8759
8760 const SCEV *S = getExistingSCEV(V);
8761 if (!S)
8762 return;
8763
8764 // Invalidate the block and loop dispositions cached for S. Dispositions of
8765 // S's users may change if S's disposition changes (i.e. a user may change to
8766 // loop-invariant, if S changes to loop invariant), so also invalidate
8767 // dispositions of S's users recursively.
8768 SmallVector<SCEVUse, 8> Worklist = {S};
8770 while (!Worklist.empty()) {
8771 const SCEV *Curr = Worklist.pop_back_val();
8772 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8773 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8774 if (!LoopDispoRemoved && !BlockDispoRemoved)
8775 continue;
8776 auto Users = SCEVUsers.find(Curr);
8777 if (Users != SCEVUsers.end())
8778 for (const auto *User : Users->second)
8779 if (Seen.insert(User).second)
8780 Worklist.push_back(User);
8781 }
8782}
8783
8784/// Get the exact loop backedge taken count considering all loop exits. A
8785/// computable result can only be returned for loops with all exiting blocks
8786/// dominating the latch. howFarToZero assumes that the limit of each loop test
8787/// is never skipped. This is a valid assumption as long as the loop exits via
8788/// that test. For precise results, it is the caller's responsibility to specify
8789/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8790const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8791 const Loop *L, ScalarEvolution *SE,
8793 // If any exits were not computable, the loop is not computable.
8794 if (!isComplete() || ExitNotTaken.empty())
8795 return SE->getCouldNotCompute();
8796
8797 const BasicBlock *Latch = L->getLoopLatch();
8798 // All exiting blocks we have collected must dominate the only backedge.
8799 if (!Latch)
8800 return SE->getCouldNotCompute();
8801
8802 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8803 // count is simply a minimum out of all these calculated exit counts.
8805 for (const auto &ENT : ExitNotTaken) {
8806 const SCEV *BECount = ENT.ExactNotTaken;
8807 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8808 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8809 "We should only have known counts for exiting blocks that dominate "
8810 "latch!");
8811
8812 Ops.push_back(BECount);
8813
8814 if (Preds)
8815 append_range(*Preds, ENT.Predicates);
8816
8817 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8818 "Predicate should be always true!");
8819 }
8820
8821 // If an earlier exit exits on the first iteration (exit count zero), then
8822 // a later poison exit count should not propagate into the result. This are
8823 // exactly the semantics provided by umin_seq.
8824 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8825}
8826
8827const ScalarEvolution::ExitNotTakenInfo *
8828ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8829 const BasicBlock *ExitingBlock,
8830 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8831 for (const auto &ENT : ExitNotTaken)
8832 if (ENT.ExitingBlock == ExitingBlock) {
8833 if (ENT.hasAlwaysTruePredicate())
8834 return &ENT;
8835 else if (Predicates) {
8836 append_range(*Predicates, ENT.Predicates);
8837 return &ENT;
8838 }
8839 }
8840
8841 return nullptr;
8842}
8843
8844/// getConstantMax - Get the constant max backedge taken count for the loop.
8845const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8846 ScalarEvolution *SE,
8847 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8848 if (!getConstantMax())
8849 return SE->getCouldNotCompute();
8850
8851 for (const auto &ENT : ExitNotTaken)
8852 if (!ENT.hasAlwaysTruePredicate()) {
8853 if (!Predicates)
8854 return SE->getCouldNotCompute();
8855 append_range(*Predicates, ENT.Predicates);
8856 }
8857
8858 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8859 isa<SCEVConstant>(getConstantMax())) &&
8860 "No point in having a non-constant max backedge taken count!");
8861 return getConstantMax();
8862}
8863
8864const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8865 const Loop *L, ScalarEvolution *SE,
8866 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8867 if (!SymbolicMax) {
8868 // Form an expression for the maximum exit count possible for this loop. We
8869 // merge the max and exact information to approximate a version of
8870 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8871 // constants.
8872 SmallVector<SCEVUse, 4> ExitCounts;
8873
8874 for (const auto &ENT : ExitNotTaken) {
8875 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8876 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8877 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8878 "We should only have known counts for exiting blocks that "
8879 "dominate latch!");
8880 ExitCounts.push_back(ExitCount);
8881 if (Predicates)
8882 append_range(*Predicates, ENT.Predicates);
8883
8884 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8885 "Predicate should be always true!");
8886 }
8887 }
8888 if (ExitCounts.empty())
8889 SymbolicMax = SE->getCouldNotCompute();
8890 else
8891 SymbolicMax =
8892 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8893 }
8894 return SymbolicMax;
8895}
8896
8897bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8898 ScalarEvolution *SE) const {
8899 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8900 return !ENT.hasAlwaysTruePredicate();
8901 };
8902 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8903}
8904
8907
8909 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8910 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8914 // If we prove the max count is zero, so is the symbolic bound. This happens
8915 // in practice due to differences in a) how context sensitive we've chosen
8916 // to be and b) how we reason about bounds implied by UB.
8917 if (ConstantMaxNotTaken->isZero()) {
8918 this->ExactNotTaken = E = ConstantMaxNotTaken;
8919 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8920 }
8921
8924 "Exact is not allowed to be less precise than Constant Max");
8927 "Exact is not allowed to be less precise than Symbolic Max");
8930 "Symbolic Max is not allowed to be less precise than Constant Max");
8933 "No point in having a non-constant max backedge taken count!");
8935 for (const auto PredList : PredLists)
8936 for (const auto *P : PredList) {
8937 if (SeenPreds.contains(P))
8938 continue;
8939 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8940 SeenPreds.insert(P);
8941 Predicates.push_back(P);
8942 }
8943 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8944 "Backedge count should be int");
8946 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8947 "Max backedge count should be int");
8948}
8949
8957
8958/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8959/// computable exit into a persistent ExitNotTakenInfo array.
8960ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8962 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8963 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8964 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8965
8966 ExitNotTaken.reserve(ExitCounts.size());
8967 std::transform(ExitCounts.begin(), ExitCounts.end(),
8968 std::back_inserter(ExitNotTaken),
8969 [&](const EdgeExitInfo &EEI) {
8970 BasicBlock *ExitBB = EEI.first;
8971 const ExitLimit &EL = EEI.second;
8972 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
8973 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
8974 EL.Predicates);
8975 });
8976 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
8977 isa<SCEVConstant>(ConstantMax)) &&
8978 "No point in having a non-constant max backedge taken count!");
8979}
8980
8981/// Compute the number of times the backedge of the specified loop will execute.
8982ScalarEvolution::BackedgeTakenInfo
8983ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
8984 bool AllowPredicates) {
8985 SmallVector<BasicBlock *, 8> ExitingBlocks;
8986 L->getExitingBlocks(ExitingBlocks);
8987
8988 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8989
8991 bool CouldComputeBECount = true;
8992 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
8993 const SCEV *MustExitMaxBECount = nullptr;
8994 const SCEV *MayExitMaxBECount = nullptr;
8995 bool MustExitMaxOrZero = false;
8996 bool IsOnlyExit = ExitingBlocks.size() == 1;
8997
8998 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
8999 // and compute maxBECount.
9000 // Do a union of all the predicates here.
9001 for (BasicBlock *ExitBB : ExitingBlocks) {
9002 // We canonicalize untaken exits to br (constant), ignore them so that
9003 // proving an exit untaken doesn't negatively impact our ability to reason
9004 // about the loop as whole.
9005 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9006 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9007 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9008 if (ExitIfTrue == CI->isZero())
9009 continue;
9010 }
9011
9012 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9013
9014 assert((AllowPredicates || EL.Predicates.empty()) &&
9015 "Predicated exit limit when predicates are not allowed!");
9016
9017 // 1. For each exit that can be computed, add an entry to ExitCounts.
9018 // CouldComputeBECount is true only if all exits can be computed.
9019 if (EL.ExactNotTaken != getCouldNotCompute())
9020 ++NumExitCountsComputed;
9021 else
9022 // We couldn't compute an exact value for this exit, so
9023 // we won't be able to compute an exact value for the loop.
9024 CouldComputeBECount = false;
9025 // Remember exit count if either exact or symbolic is known. Because
9026 // Exact always implies symbolic, only check symbolic.
9027 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9028 ExitCounts.emplace_back(ExitBB, EL);
9029 else {
9030 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9031 "Exact is known but symbolic isn't?");
9032 ++NumExitCountsNotComputed;
9033 }
9034
9035 // 2. Derive the loop's MaxBECount from each exit's max number of
9036 // non-exiting iterations. Partition the loop exits into two kinds:
9037 // LoopMustExits and LoopMayExits.
9038 //
9039 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9040 // is a LoopMayExit. If any computable LoopMustExit is found, then
9041 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9042 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9043 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9044 // any
9045 // computable EL.ConstantMaxNotTaken.
9046 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9047 DT.dominates(ExitBB, Latch)) {
9048 if (!MustExitMaxBECount) {
9049 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9050 MustExitMaxOrZero = EL.MaxOrZero;
9051 } else {
9052 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9053 EL.ConstantMaxNotTaken);
9054 }
9055 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9056 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9057 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9058 else {
9059 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9060 EL.ConstantMaxNotTaken);
9061 }
9062 }
9063 }
9064 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9065 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9066 // The loop backedge will be taken the maximum or zero times if there's
9067 // a single exit that must be taken the maximum or zero times.
9068 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9069
9070 // Remember which SCEVs are used in exit limits for invalidation purposes.
9071 // We only care about non-constant SCEVs here, so we can ignore
9072 // EL.ConstantMaxNotTaken
9073 // and MaxBECount, which must be SCEVConstant.
9074 for (const auto &Pair : ExitCounts) {
9075 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9076 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9077 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9078 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9079 {L, AllowPredicates});
9080 }
9081 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9082 MaxBECount, MaxOrZero);
9083}
9084
9085ScalarEvolution::ExitLimit
9086ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9087 bool IsOnlyExit, bool AllowPredicates) {
9088 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9089 // If our exiting block does not dominate the latch, then its connection with
9090 // loop's exit limit may be far from trivial.
9091 const BasicBlock *Latch = L->getLoopLatch();
9092 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9093 return getCouldNotCompute();
9094
9095 Instruction *Term = ExitingBlock->getTerminator();
9096 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9097 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9098 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9099 "It should have one successor in loop and one exit block!");
9100 // Proceed to the next level to examine the exit condition expression.
9101 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9102 /*ControlsOnlyExit=*/IsOnlyExit,
9103 AllowPredicates);
9104 }
9105
9106 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9107 // For switch, make sure that there is a single exit from the loop.
9108 BasicBlock *Exit = nullptr;
9109 for (auto *SBB : successors(ExitingBlock))
9110 if (!L->contains(SBB)) {
9111 if (Exit) // Multiple exit successors.
9112 return getCouldNotCompute();
9113 Exit = SBB;
9114 }
9115 assert(Exit && "Exiting block must have at least one exit");
9116 return computeExitLimitFromSingleExitSwitch(
9117 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9118 }
9119
9120 return getCouldNotCompute();
9121}
9122
9124 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9125 bool AllowPredicates) {
9126 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9127 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9128 ControlsOnlyExit, AllowPredicates);
9129}
9130
9131std::optional<ScalarEvolution::ExitLimit>
9132ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9133 bool ExitIfTrue, bool ControlsOnlyExit,
9134 bool AllowPredicates) {
9135 (void)this->L;
9136 (void)this->ExitIfTrue;
9137 (void)this->AllowPredicates;
9138
9139 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9140 this->AllowPredicates == AllowPredicates &&
9141 "Variance in assumed invariant key components!");
9142 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9143 if (Itr == TripCountMap.end())
9144 return std::nullopt;
9145 return Itr->second;
9146}
9147
9148void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9149 bool ExitIfTrue,
9150 bool ControlsOnlyExit,
9151 bool AllowPredicates,
9152 const ExitLimit &EL) {
9153 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9154 this->AllowPredicates == AllowPredicates &&
9155 "Variance in assumed invariant key components!");
9156
9157 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9158 assert(InsertResult.second && "Expected successful insertion!");
9159 (void)InsertResult;
9160 (void)ExitIfTrue;
9161}
9162
9163ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9164 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9165 bool ControlsOnlyExit, bool AllowPredicates) {
9166
9167 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9168 AllowPredicates))
9169 return *MaybeEL;
9170
9171 ExitLimit EL = computeExitLimitFromCondImpl(
9172 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9173 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9174 return EL;
9175}
9176
9177ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9178 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9179 bool ControlsOnlyExit, bool AllowPredicates) {
9180 // Handle BinOp conditions (And, Or).
9181 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9182 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9183 return *LimitFromBinOp;
9184
9185 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9186 // Proceed to the next level to examine the icmp.
9187 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9188 ExitLimit EL =
9189 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9190 if (EL.hasFullInfo() || !AllowPredicates)
9191 return EL;
9192
9193 // Try again, but use SCEV predicates this time.
9194 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9195 ControlsOnlyExit,
9196 /*AllowPredicates=*/true);
9197 }
9198
9199 // Check for a constant condition. These are normally stripped out by
9200 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9201 // preserve the CFG and is temporarily leaving constant conditions
9202 // in place.
9203 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9204 if (ExitIfTrue == !CI->getZExtValue())
9205 // The backedge is always taken.
9206 return getCouldNotCompute();
9207 // The backedge is never taken.
9208 return getZero(CI->getType());
9209 }
9210
9211 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9212 // with a constant step, we can form an equivalent icmp predicate and figure
9213 // out how many iterations will be taken before we exit.
9214 const WithOverflowInst *WO;
9215 const APInt *C;
9216 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9217 match(WO->getRHS(), m_APInt(C))) {
9218 ConstantRange NWR =
9220 WO->getNoWrapKind());
9221 CmpInst::Predicate Pred;
9222 APInt NewRHSC, Offset;
9223 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9224 if (!ExitIfTrue)
9225 Pred = ICmpInst::getInversePredicate(Pred);
9226 auto *LHS = getSCEV(WO->getLHS());
9227 if (Offset != 0)
9229 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9230 ControlsOnlyExit, AllowPredicates);
9231 if (EL.hasAnyInfo())
9232 return EL;
9233 }
9234
9235 // If it's not an integer or pointer comparison then compute it the hard way.
9236 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9237}
9238
9239std::optional<ScalarEvolution::ExitLimit>
9240ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9241 const Loop *L,
9242 Value *ExitCond,
9243 bool ExitIfTrue,
9244 bool AllowPredicates) {
9245 // Check if the controlling expression for this loop is an And or Or.
9246 Value *Op0, *Op1;
9247 bool IsAnd;
9248 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9249 IsAnd = true;
9250 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9251 IsAnd = false;
9252 else
9253 return std::nullopt;
9254
9255 // A sub-condition of a non-trivial binop never solely controls the exit,
9256 // whether we exit always depends on both conditions.
9257 ExitLimit EL0 = computeExitLimitFromCondCached(
9258 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9259 ExitLimit EL1 = computeExitLimitFromCondCached(
9260 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9261
9262 // EitherMayExit is true in these two cases:
9263 // br (and Op0 Op1), loop, exit
9264 // br (or Op0 Op1), exit, loop
9265 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9266
9267 const SCEV *BECount = getCouldNotCompute();
9268 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9269 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9270 if (EitherMayExit) {
9271 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9272 // Both conditions must be same for the loop to continue executing.
9273 // Choose the less conservative count.
9274 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9275 EL1.ExactNotTaken != getCouldNotCompute()) {
9276 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9277 UseSequentialUMin);
9278 }
9279 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9280 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9281 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9282 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9283 else
9284 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9285 EL1.ConstantMaxNotTaken);
9286 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9287 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9288 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9289 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9290 else
9291 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9292 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9293 } else {
9294 // Both conditions must be same at the same time for the loop to exit.
9295 // For now, be conservative.
9296 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9297 BECount = EL0.ExactNotTaken;
9298 }
9299
9300 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9301 // to be more aggressive when computing BECount than when computing
9302 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9303 // and
9304 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9305 // EL1.ConstantMaxNotTaken to not.
9306 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9307 !isa<SCEVCouldNotCompute>(BECount))
9308 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9309 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9310 SymbolicMaxBECount =
9311 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9312 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9313 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9314}
9315
9316ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9317 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9318 bool AllowPredicates) {
9319 // If the condition was exit on true, convert the condition to exit on false
9320 CmpPredicate Pred;
9321 if (!ExitIfTrue)
9322 Pred = ExitCond->getCmpPredicate();
9323 else
9324 Pred = ExitCond->getInverseCmpPredicate();
9325 const ICmpInst::Predicate OriginalPred = Pred;
9326
9327 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9328 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9329
9330 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9331 AllowPredicates);
9332 if (EL.hasAnyInfo())
9333 return EL;
9334
9335 auto *ExhaustiveCount =
9336 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9337
9338 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9339 return ExhaustiveCount;
9340
9341 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9342 ExitCond->getOperand(1), L, OriginalPred);
9343}
9344ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9345 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9346 bool ControlsOnlyExit, bool AllowPredicates) {
9347
9348 // Try to evaluate any dependencies out of the loop.
9349 LHS = getSCEVAtScope(LHS, L);
9350 RHS = getSCEVAtScope(RHS, L);
9351
9352 // At this point, we would like to compute how many iterations of the
9353 // loop the predicate will return true for these inputs.
9354 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9355 // If there is a loop-invariant, force it into the RHS.
9356 std::swap(LHS, RHS);
9358 }
9359
9360 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9362 // Simplify the operands before analyzing them.
9363 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9364
9365 // If we have a comparison of a chrec against a constant, try to use value
9366 // ranges to answer this query.
9367 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9368 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9369 if (AddRec->getLoop() == L) {
9370 // Form the constant range.
9371 ConstantRange CompRange =
9372 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9373
9374 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9375 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9376 }
9377
9378 // If this loop must exit based on this condition (or execute undefined
9379 // behaviour), see if we can improve wrap flags. This is essentially
9380 // a must execute style proof.
9381 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9382 // If we can prove the test sequence produced must repeat the same values
9383 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9384 // because if it did, we'd have an infinite (undefined) loop.
9385 // TODO: We can peel off any functions which are invertible *in L*. Loop
9386 // invariant terms are effectively constants for our purposes here.
9387 SCEVUse InnerLHS = LHS;
9388 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9389 InnerLHS = ZExt->getOperand();
9390 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9391 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9392 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9393 /*OrNegative=*/true)) {
9394 auto Flags = AR->getNoWrapFlags();
9395 Flags = setFlags(Flags, SCEV::FlagNW);
9398 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9399 }
9400
9401 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9402 // From no-self-wrap, this follows trivially from the fact that every
9403 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9404 // last value before (un)signed wrap. Since we know that last value
9405 // didn't exit, nor will any smaller one.
9406 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9407 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9408 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9409 AR && AR->getLoop() == L && AR->isAffine() &&
9410 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9411 isKnownPositive(AR->getStepRecurrence(*this))) {
9412 auto Flags = AR->getNoWrapFlags();
9413 Flags = setFlags(Flags, WrapType);
9416 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9417 }
9418 }
9419 }
9420
9421 switch (Pred) {
9422 case ICmpInst::ICMP_NE: { // while (X != Y)
9423 // Convert to: while (X-Y != 0)
9424 if (LHS->getType()->isPointerTy()) {
9427 return LHS;
9428 }
9429 if (RHS->getType()->isPointerTy()) {
9432 return RHS;
9433 }
9434 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9435 AllowPredicates);
9436 if (EL.hasAnyInfo())
9437 return EL;
9438 break;
9439 }
9440 case ICmpInst::ICMP_EQ: { // while (X == Y)
9441 // Convert to: while (X-Y == 0)
9442 if (LHS->getType()->isPointerTy()) {
9445 return LHS;
9446 }
9447 if (RHS->getType()->isPointerTy()) {
9450 return RHS;
9451 }
9452 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9453 if (EL.hasAnyInfo()) return EL;
9454 break;
9455 }
9456 case ICmpInst::ICMP_SLE:
9457 case ICmpInst::ICMP_ULE:
9458 // Since the loop is finite, an invariant RHS cannot include the boundary
9459 // value, otherwise it would loop forever.
9460 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9461 !isLoopInvariant(RHS, L)) {
9462 // Otherwise, perform the addition in a wider type, to avoid overflow.
9463 // If the LHS is an addrec with the appropriate nowrap flag, the
9464 // extension will be sunk into it and the exit count can be analyzed.
9465 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9466 if (!OldType)
9467 break;
9468 // Prefer doubling the bitwidth over adding a single bit to make it more
9469 // likely that we use a legal type.
9470 auto *NewType =
9471 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9472 if (ICmpInst::isSigned(Pred)) {
9473 LHS = getSignExtendExpr(LHS, NewType);
9474 RHS = getSignExtendExpr(RHS, NewType);
9475 } else {
9476 LHS = getZeroExtendExpr(LHS, NewType);
9477 RHS = getZeroExtendExpr(RHS, NewType);
9478 }
9479 }
9481 [[fallthrough]];
9482 case ICmpInst::ICMP_SLT:
9483 case ICmpInst::ICMP_ULT: { // while (X < Y)
9484 bool IsSigned = ICmpInst::isSigned(Pred);
9485 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9486 AllowPredicates);
9487 if (EL.hasAnyInfo())
9488 return EL;
9489 break;
9490 }
9491 case ICmpInst::ICMP_SGE:
9492 case ICmpInst::ICMP_UGE:
9493 // Since the loop is finite, an invariant RHS cannot include the boundary
9494 // value, otherwise it would loop forever.
9495 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9496 !isLoopInvariant(RHS, L))
9497 break;
9499 [[fallthrough]];
9500 case ICmpInst::ICMP_SGT:
9501 case ICmpInst::ICMP_UGT: { // while (X > Y)
9502 bool IsSigned = ICmpInst::isSigned(Pred);
9503 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9504 AllowPredicates);
9505 if (EL.hasAnyInfo())
9506 return EL;
9507 break;
9508 }
9509 default:
9510 break;
9511 }
9512
9513 return getCouldNotCompute();
9514}
9515
9516ScalarEvolution::ExitLimit
9517ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9518 SwitchInst *Switch,
9519 BasicBlock *ExitingBlock,
9520 bool ControlsOnlyExit) {
9521 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9522
9523 // Give up if the exit is the default dest of a switch.
9524 if (Switch->getDefaultDest() == ExitingBlock)
9525 return getCouldNotCompute();
9526
9527 assert(L->contains(Switch->getDefaultDest()) &&
9528 "Default case must not exit the loop!");
9529 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9530 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9531
9532 // while (X != Y) --> while (X-Y != 0)
9533 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9534 if (EL.hasAnyInfo())
9535 return EL;
9536
9537 return getCouldNotCompute();
9538}
9539
9540static ConstantInt *
9542 ScalarEvolution &SE) {
9543 const SCEV *InVal = SE.getConstant(C);
9544 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9546 "Evaluation of SCEV at constant didn't fold correctly?");
9547 return cast<SCEVConstant>(Val)->getValue();
9548}
9549
9550ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9551 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9552 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9553 if (!RHS)
9554 return getCouldNotCompute();
9555
9556 const BasicBlock *Latch = L->getLoopLatch();
9557 if (!Latch)
9558 return getCouldNotCompute();
9559
9560 const BasicBlock *Predecessor = L->getLoopPredecessor();
9561 if (!Predecessor)
9562 return getCouldNotCompute();
9563
9564 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9565 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9566 // OutShiftAmt.
9567 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9568 Instruction::BinaryOps &OutOpCode,
9569 unsigned &OutShiftAmt) {
9570 using namespace PatternMatch;
9571
9572 ConstantInt *ShiftAmt;
9573 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9574 OutOpCode = Instruction::LShr;
9575 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9576 OutOpCode = Instruction::AShr;
9577 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9578 OutOpCode = Instruction::Shl;
9579 else
9580 return false;
9581
9582 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9583 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9584 return false;
9585 OutShiftAmt = Amt;
9586 return true;
9587 };
9588
9589 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9590 //
9591 // loop:
9592 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9593 // %iv.shifted = lshr i32 %iv, <positive constant>
9594 //
9595 // Return true on a successful match. Return the corresponding PHI node (%iv
9596 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9597 // shift amount in ShiftAmtOut.
9598 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9599 Instruction::BinaryOps &OpCodeOut,
9600 unsigned &ShiftAmtOut) {
9601 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9602
9603 {
9605 Value *V;
9606 unsigned Amt;
9607
9608 // If we encounter a shift instruction, "peel off" the shift operation,
9609 // and remember that we did so. Later when we inspect %iv's backedge
9610 // value, we will make sure that the backedge value uses the same
9611 // operation.
9612 //
9613 // Note: the peeled shift operation does not have to be the same
9614 // instruction as the one feeding into the PHI's backedge value. We only
9615 // really care about it being the same *kind* of shift instruction --
9616 // that's all that is required for our later inferences to hold.
9617 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9618 PostShiftOpCode = OpC;
9619 LHS = V;
9620 }
9621 }
9622
9623 PNOut = dyn_cast<PHINode>(LHS);
9624 if (!PNOut || PNOut->getParent() != L->getHeader())
9625 return false;
9626
9627 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9628 Value *OpLHS;
9629
9630 return
9631 // The backedge value for the PHI node must be a shift by a positive
9632 // amount
9633 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9634
9635 // of the PHI node itself
9636 OpLHS == PNOut &&
9637
9638 // and the kind of shift should be match the kind of shift we peeled
9639 // off, if any.
9640 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9641 };
9642
9643 PHINode *PN;
9645 unsigned ShiftAmt;
9646 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9647 return getCouldNotCompute();
9648
9649 const DataLayout &DL = getDataLayout();
9650
9651 // The key rationale for this optimization is that for some kinds of shift
9652 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9653 // within a finite number of iterations. If the condition guarding the
9654 // backedge (in the sense that the backedge is taken if the condition is true)
9655 // is false for the value the shift recurrence stabilizes to, then we know
9656 // that the backedge is taken only a finite number of times.
9657
9658 ConstantInt *StableValue = nullptr;
9659 switch (OpCode) {
9660 default:
9661 llvm_unreachable("Impossible case!");
9662
9663 case Instruction::AShr: {
9664 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9665 // bitwidth(K) iterations.
9666 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9667 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9668 Predecessor->getTerminator(), &DT);
9669 auto *Ty = cast<IntegerType>(RHS->getType());
9670 if (Known.isNonNegative())
9671 StableValue = ConstantInt::get(Ty, 0);
9672 else if (Known.isNegative())
9673 StableValue = ConstantInt::get(Ty, -1, true);
9674 else
9675 return getCouldNotCompute();
9676
9677 break;
9678 }
9679 case Instruction::LShr:
9680 case Instruction::Shl:
9681 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9682 // stabilize to 0 in at most bitwidth(K) iterations.
9683 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9684 break;
9685 }
9686
9687 auto *Result =
9688 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9689 assert(Result->getType()->isIntegerTy(1) &&
9690 "Otherwise cannot be an operand to a branch instruction");
9691
9692 if (Result->isNullValue()) {
9693 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9694 unsigned MaxBTC = BitWidth;
9695
9696 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9697 // compute a tighter max backedge-taken count from the range of the start
9698 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9699 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9700 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9701 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9702 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9703 const SCEV *StartSCEV = getSCEV(StartValue);
9704 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9705 if (MaxStart.isStrictlyPositive()) {
9706 unsigned ActiveBits = MaxStart.getActiveBits();
9707 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9708 MaxBTC = std::min(MaxBTC, RangeBTC);
9709 }
9710 }
9711
9712 const SCEV *UpperBound =
9714 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9715 }
9716
9717 return getCouldNotCompute();
9718}
9719
9720/// Return true if we can constant fold an instruction of the specified type,
9721/// assuming that all operands were constants.
9722static bool CanConstantFold(const Instruction *I) {
9726 return true;
9727
9728 if (const CallInst *CI = dyn_cast<CallInst>(I))
9729 if (const Function *F = CI->getCalledFunction())
9730 return canConstantFoldCallTo(CI, F);
9731 return false;
9732}
9733
9734/// Determine whether this instruction can constant evolve within this loop
9735/// assuming its operands can all constant evolve.
9736static bool canConstantEvolve(Instruction *I, const Loop *L) {
9737 // An instruction outside of the loop can't be derived from a loop PHI.
9738 if (!L->contains(I)) return false;
9739
9740 if (isa<PHINode>(I)) {
9741 // We don't currently keep track of the control flow needed to evaluate
9742 // PHIs, so we cannot handle PHIs inside of loops.
9743 return L->getHeader() == I->getParent();
9744 }
9745
9746 // If we won't be able to constant fold this expression even if the operands
9747 // are constants, bail early.
9748 return CanConstantFold(I);
9749}
9750
9751/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9752/// recursing through each instruction operand until reaching a loop header phi.
9753static PHINode *
9756 unsigned Depth) {
9758 return nullptr;
9759
9760 // Otherwise, we can evaluate this instruction if all of its operands are
9761 // constant or derived from a PHI node themselves.
9762 PHINode *PHI = nullptr;
9763 for (Value *Op : UseInst->operands()) {
9764 if (isa<Constant>(Op)) continue;
9765
9767 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9768
9769 PHINode *P = dyn_cast<PHINode>(OpInst);
9770 if (!P)
9771 // If this operand is already visited, reuse the prior result.
9772 // We may have P != PHI if this is the deepest point at which the
9773 // inconsistent paths meet.
9774 P = PHIMap.lookup(OpInst);
9775 if (!P) {
9776 // Recurse and memoize the results, whether a phi is found or not.
9777 // This recursive call invalidates pointers into PHIMap.
9778 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9779 PHIMap[OpInst] = P;
9780 }
9781 if (!P)
9782 return nullptr; // Not evolving from PHI
9783 if (PHI && PHI != P)
9784 return nullptr; // Evolving from multiple different PHIs.
9785 PHI = P;
9786 }
9787 // This is a expression evolving from a constant PHI!
9788 return PHI;
9789}
9790
9791/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9792/// in the loop that V is derived from. We allow arbitrary operations along the
9793/// way, but the operands of an operation must either be constants or a value
9794/// derived from a constant PHI. If this expression does not fit with these
9795/// constraints, return null.
9798 if (!I || !canConstantEvolve(I, L)) return nullptr;
9799
9800 if (PHINode *PN = dyn_cast<PHINode>(I))
9801 return PN;
9802
9803 // Record non-constant instructions contained by the loop.
9805 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9806}
9807
9808/// EvaluateExpression - Given an expression that passes the
9809/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9810/// in the loop has the value PHIVal. If we can't fold this expression for some
9811/// reason, return null.
9814 const DataLayout &DL,
9815 const TargetLibraryInfo *TLI) {
9816 // Convenient constant check, but redundant for recursive calls.
9817 if (Constant *C = dyn_cast<Constant>(V)) return C;
9819 if (!I) return nullptr;
9820
9821 if (Constant *C = Vals.lookup(I)) return C;
9822
9823 // An instruction inside the loop depends on a value outside the loop that we
9824 // weren't given a mapping for, or a value such as a call inside the loop.
9825 if (!canConstantEvolve(I, L)) return nullptr;
9826
9827 // An unmapped PHI can be due to a branch or another loop inside this loop,
9828 // or due to this not being the initial iteration through a loop where we
9829 // couldn't compute the evolution of this particular PHI last time.
9830 if (isa<PHINode>(I)) return nullptr;
9831
9832 std::vector<Constant*> Operands(I->getNumOperands());
9833
9834 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9835 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9836 if (!Operand) {
9837 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9838 if (!Operands[i]) return nullptr;
9839 continue;
9840 }
9841 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9842 Vals[Operand] = C;
9843 if (!C) return nullptr;
9844 Operands[i] = C;
9845 }
9846
9847 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9848 /*AllowNonDeterministic=*/false);
9849}
9850
9851
9852// If every incoming value to PN except the one for BB is a specific Constant,
9853// return that, else return nullptr.
9855 Constant *IncomingVal = nullptr;
9856
9857 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9858 if (PN->getIncomingBlock(i) == BB)
9859 continue;
9860
9861 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9862 if (!CurrentVal)
9863 return nullptr;
9864
9865 if (IncomingVal != CurrentVal) {
9866 if (IncomingVal)
9867 return nullptr;
9868 IncomingVal = CurrentVal;
9869 }
9870 }
9871
9872 return IncomingVal;
9873}
9874
9875/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9876/// in the header of its containing loop, we know the loop executes a
9877/// constant number of times, and the PHI node is just a recurrence
9878/// involving constants, fold it.
9879Constant *
9880ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9881 const APInt &BEs,
9882 const Loop *L) {
9883 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9884 if (!Inserted)
9885 return I->second;
9886
9888 return nullptr; // Not going to evaluate it.
9889
9890 Constant *&RetVal = I->second;
9891
9892 DenseMap<Instruction *, Constant *> CurrentIterVals;
9893 BasicBlock *Header = L->getHeader();
9894 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9895
9896 BasicBlock *Latch = L->getLoopLatch();
9897 if (!Latch)
9898 return nullptr;
9899
9900 for (PHINode &PHI : Header->phis()) {
9901 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9902 CurrentIterVals[&PHI] = StartCST;
9903 }
9904 if (!CurrentIterVals.count(PN))
9905 return RetVal = nullptr;
9906
9907 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9908
9909 // Execute the loop symbolically to determine the exit value.
9910 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9911 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9912
9913 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9914 unsigned IterationNum = 0;
9915 const DataLayout &DL = getDataLayout();
9916 for (; ; ++IterationNum) {
9917 if (IterationNum == NumIterations)
9918 return RetVal = CurrentIterVals[PN]; // Got exit value!
9919
9920 // Compute the value of the PHIs for the next iteration.
9921 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9922 DenseMap<Instruction *, Constant *> NextIterVals;
9923 Constant *NextPHI =
9924 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9925 if (!NextPHI)
9926 return nullptr; // Couldn't evaluate!
9927 NextIterVals[PN] = NextPHI;
9928
9929 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9930
9931 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9932 // cease to be able to evaluate one of them or if they stop evolving,
9933 // because that doesn't necessarily prevent us from computing PN.
9935 for (const auto &I : CurrentIterVals) {
9936 PHINode *PHI = dyn_cast<PHINode>(I.first);
9937 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9938 PHIsToCompute.emplace_back(PHI, I.second);
9939 }
9940 // We use two distinct loops because EvaluateExpression may invalidate any
9941 // iterators into CurrentIterVals.
9942 for (const auto &I : PHIsToCompute) {
9943 PHINode *PHI = I.first;
9944 Constant *&NextPHI = NextIterVals[PHI];
9945 if (!NextPHI) { // Not already computed.
9946 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9947 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9948 }
9949 if (NextPHI != I.second)
9950 StoppedEvolving = false;
9951 }
9952
9953 // If all entries in CurrentIterVals == NextIterVals then we can stop
9954 // iterating, the loop can't continue to change.
9955 if (StoppedEvolving)
9956 return RetVal = CurrentIterVals[PN];
9957
9958 CurrentIterVals.swap(NextIterVals);
9959 }
9960}
9961
9962const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
9963 Value *Cond,
9964 bool ExitWhen) {
9965 PHINode *PN = getConstantEvolvingPHI(Cond, L);
9966 if (!PN) return getCouldNotCompute();
9967
9968 // If the loop is canonicalized, the PHI will have exactly two entries.
9969 // That's the only form we support here.
9970 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
9971
9972 DenseMap<Instruction *, Constant *> CurrentIterVals;
9973 BasicBlock *Header = L->getHeader();
9974 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9975
9976 BasicBlock *Latch = L->getLoopLatch();
9977 assert(Latch && "Should follow from NumIncomingValues == 2!");
9978
9979 for (PHINode &PHI : Header->phis()) {
9980 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9981 CurrentIterVals[&PHI] = StartCST;
9982 }
9983 if (!CurrentIterVals.count(PN))
9984 return getCouldNotCompute();
9985
9986 // Okay, we find a PHI node that defines the trip count of this loop. Execute
9987 // the loop symbolically to determine when the condition gets a value of
9988 // "ExitWhen".
9989 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
9990 const DataLayout &DL = getDataLayout();
9991 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
9992 auto *CondVal = dyn_cast_or_null<ConstantInt>(
9993 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
9994
9995 // Couldn't symbolically evaluate.
9996 if (!CondVal) return getCouldNotCompute();
9997
9998 if (CondVal->getValue() == uint64_t(ExitWhen)) {
9999 ++NumBruteForceTripCountsComputed;
10000 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10001 }
10002
10003 // Update all the PHI nodes for the next iteration.
10004 DenseMap<Instruction *, Constant *> NextIterVals;
10005
10006 // Create a list of which PHIs we need to compute. We want to do this before
10007 // calling EvaluateExpression on them because that may invalidate iterators
10008 // into CurrentIterVals.
10009 SmallVector<PHINode *, 8> PHIsToCompute;
10010 for (const auto &I : CurrentIterVals) {
10011 PHINode *PHI = dyn_cast<PHINode>(I.first);
10012 if (!PHI || PHI->getParent() != Header) continue;
10013 PHIsToCompute.push_back(PHI);
10014 }
10015 for (PHINode *PHI : PHIsToCompute) {
10016 Constant *&NextPHI = NextIterVals[PHI];
10017 if (NextPHI) continue; // Already computed!
10018
10019 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10020 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10021 }
10022 CurrentIterVals.swap(NextIterVals);
10023 }
10024
10025 // Too many iterations were needed to evaluate.
10026 return getCouldNotCompute();
10027}
10028
10029const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10031 ValuesAtScopes[V];
10032 // Check to see if we've folded this expression at this loop before.
10033 for (auto &LS : Values)
10034 if (LS.first == L)
10035 return LS.second ? LS.second : V;
10036
10037 Values.emplace_back(L, nullptr);
10038
10039 // Otherwise compute it.
10040 const SCEV *C = computeSCEVAtScope(V, L);
10041 for (auto &LS : reverse(ValuesAtScopes[V]))
10042 if (LS.first == L) {
10043 LS.second = C;
10044 if (!isa<SCEVConstant>(C))
10045 ValuesAtScopesUsers[C].push_back({L, V});
10046 break;
10047 }
10048 return C;
10049}
10050
10051/// This builds up a Constant using the ConstantExpr interface. That way, we
10052/// will return Constants for objects which aren't represented by a
10053/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10054/// Returns NULL if the SCEV isn't representable as a Constant.
10056 switch (V->getSCEVType()) {
10057 case scCouldNotCompute:
10058 case scAddRecExpr:
10059 case scVScale:
10060 return nullptr;
10061 case scConstant:
10062 return cast<SCEVConstant>(V)->getValue();
10063 case scUnknown:
10065 case scPtrToAddr: {
10067 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10068 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10069
10070 return nullptr;
10071 }
10072 case scTruncate: {
10074 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10075 return ConstantExpr::getTrunc(CastOp, ST->getType());
10076 return nullptr;
10077 }
10078 case scAddExpr: {
10079 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10080 Constant *C = nullptr;
10081 for (const SCEV *Op : SA->operands()) {
10083 if (!OpC)
10084 return nullptr;
10085 if (!C) {
10086 C = OpC;
10087 continue;
10088 }
10089 assert(!C->getType()->isPointerTy() &&
10090 "Can only have one pointer, and it must be last");
10091 if (OpC->getType()->isPointerTy()) {
10092 // The offsets have been converted to bytes. We can add bytes using
10093 // an i8 GEP.
10094 C = ConstantExpr::getPtrAdd(OpC, C);
10095 } else {
10096 C = ConstantExpr::getAdd(C, OpC);
10097 }
10098 }
10099 return C;
10100 }
10101 case scMulExpr:
10102 case scSignExtend:
10103 case scZeroExtend:
10104 case scUDivExpr:
10105 case scSMaxExpr:
10106 case scUMaxExpr:
10107 case scSMinExpr:
10108 case scUMinExpr:
10110 return nullptr;
10111 }
10112 llvm_unreachable("Unknown SCEV kind!");
10113}
10114
10115const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10116 SmallVectorImpl<SCEVUse> &NewOps) {
10117 switch (S->getSCEVType()) {
10118 case scTruncate:
10119 case scZeroExtend:
10120 case scSignExtend:
10121 case scPtrToAddr:
10122 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10123 case scAddRecExpr: {
10124 auto *AddRec = cast<SCEVAddRecExpr>(S);
10125 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10126 }
10127 case scAddExpr:
10128 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10129 case scMulExpr:
10130 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10131 case scUDivExpr:
10132 return getUDivExpr(NewOps[0], NewOps[1]);
10133 case scUMaxExpr:
10134 case scSMaxExpr:
10135 case scUMinExpr:
10136 case scSMinExpr:
10137 return getMinMaxExpr(S->getSCEVType(), NewOps);
10139 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10140 case scConstant:
10141 case scVScale:
10142 case scUnknown:
10143 return S;
10144 case scCouldNotCompute:
10145 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10146 }
10147 llvm_unreachable("Unknown SCEV kind!");
10148}
10149
10150const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10151 switch (V->getSCEVType()) {
10152 case scConstant:
10153 case scVScale:
10154 return V;
10155 case scAddRecExpr: {
10156 // If this is a loop recurrence for a loop that does not contain L, then we
10157 // are dealing with the final value computed by the loop.
10158 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10159 // First, attempt to evaluate each operand.
10160 // Avoid performing the look-up in the common case where the specified
10161 // expression has no loop-variant portions.
10162 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10163 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10164 if (OpAtScope == AddRec->getOperand(i))
10165 continue;
10166
10167 // Okay, at least one of these operands is loop variant but might be
10168 // foldable. Build a new instance of the folded commutative expression.
10170 NewOps.reserve(AddRec->getNumOperands());
10171 append_range(NewOps, AddRec->operands().take_front(i));
10172 NewOps.push_back(OpAtScope);
10173 for (++i; i != e; ++i)
10174 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10175
10176 const SCEV *FoldedRec = getAddRecExpr(
10177 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10178 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10179 // The addrec may be folded to a nonrecurrence, for example, if the
10180 // induction variable is multiplied by zero after constant folding. Go
10181 // ahead and return the folded value.
10182 if (!AddRec)
10183 return FoldedRec;
10184 break;
10185 }
10186
10187 // If the scope is outside the addrec's loop, evaluate it by using the
10188 // loop exit value of the addrec.
10189 if (!AddRec->getLoop()->contains(L)) {
10190 // To evaluate this recurrence, we need to know how many times the AddRec
10191 // loop iterates. Compute this now.
10192 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10193 if (BackedgeTakenCount == getCouldNotCompute())
10194 return AddRec;
10195
10196 // Then, evaluate the AddRec.
10197 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10198 }
10199
10200 return AddRec;
10201 }
10202 case scTruncate:
10203 case scZeroExtend:
10204 case scSignExtend:
10205 case scPtrToAddr:
10206 case scAddExpr:
10207 case scMulExpr:
10208 case scUDivExpr:
10209 case scUMaxExpr:
10210 case scSMaxExpr:
10211 case scUMinExpr:
10212 case scSMinExpr:
10213 case scSequentialUMinExpr: {
10214 ArrayRef<SCEVUse> Ops = V->operands();
10215 // Avoid performing the look-up in the common case where the specified
10216 // expression has no loop-variant portions.
10217 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10218 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10219 if (OpAtScope != Ops[i].getPointer()) {
10220 // Okay, at least one of these operands is loop variant but might be
10221 // foldable. Build a new instance of the folded commutative expression.
10223 NewOps.reserve(Ops.size());
10224 append_range(NewOps, Ops.take_front(i));
10225 NewOps.push_back(OpAtScope);
10226
10227 for (++i; i != e; ++i) {
10228 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10229 NewOps.push_back(OpAtScope);
10230 }
10231
10232 return getWithOperands(V, NewOps);
10233 }
10234 }
10235 // If we got here, all operands are loop invariant.
10236 return V;
10237 }
10238 case scUnknown: {
10239 // If this instruction is evolved from a constant-evolving PHI, compute the
10240 // exit value from the loop without using SCEVs.
10241 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10243 if (!I)
10244 return V; // This is some other type of SCEVUnknown, just return it.
10245
10246 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10247 const Loop *CurrLoop = this->LI[I->getParent()];
10248 // Looking for loop exit value.
10249 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10250 PN->getParent() == CurrLoop->getHeader()) {
10251 // Okay, there is no closed form solution for the PHI node. Check
10252 // to see if the loop that contains it has a known backedge-taken
10253 // count. If so, we may be able to force computation of the exit
10254 // value.
10255 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10256 // This trivial case can show up in some degenerate cases where
10257 // the incoming IR has not yet been fully simplified.
10258 if (BackedgeTakenCount->isZero()) {
10259 Value *InitValue = nullptr;
10260 bool MultipleInitValues = false;
10261 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10262 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10263 if (!InitValue)
10264 InitValue = PN->getIncomingValue(i);
10265 else if (InitValue != PN->getIncomingValue(i)) {
10266 MultipleInitValues = true;
10267 break;
10268 }
10269 }
10270 }
10271 if (!MultipleInitValues && InitValue)
10272 return getSCEV(InitValue);
10273 }
10274 // Do we have a loop invariant value flowing around the backedge
10275 // for a loop which must execute the backedge?
10276 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10277 isKnownNonZero(BackedgeTakenCount) &&
10278 PN->getNumIncomingValues() == 2) {
10279
10280 unsigned InLoopPred =
10281 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10282 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10283 if (CurrLoop->isLoopInvariant(BackedgeVal))
10284 return getSCEV(BackedgeVal);
10285 }
10286 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10287 // Okay, we know how many times the containing loop executes. If
10288 // this is a constant evolving PHI node, get the final value at
10289 // the specified iteration number.
10290 Constant *RV =
10291 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10292 if (RV)
10293 return getSCEV(RV);
10294 }
10295 }
10296 }
10297
10298 // Okay, this is an expression that we cannot symbolically evaluate
10299 // into a SCEV. Check to see if it's possible to symbolically evaluate
10300 // the arguments into constants, and if so, try to constant propagate the
10301 // result. This is particularly useful for computing loop exit values.
10302 if (!CanConstantFold(I))
10303 return V; // This is some other type of SCEVUnknown, just return it.
10304
10305 SmallVector<Constant *, 4> Operands;
10306 Operands.reserve(I->getNumOperands());
10307 bool MadeImprovement = false;
10308 for (Value *Op : I->operands()) {
10309 if (Constant *C = dyn_cast<Constant>(Op)) {
10310 Operands.push_back(C);
10311 continue;
10312 }
10313
10314 // If any of the operands is non-constant and if they are
10315 // non-integer and non-pointer, don't even try to analyze them
10316 // with scev techniques.
10317 if (!isSCEVable(Op->getType()))
10318 return V;
10319
10320 const SCEV *OrigV = getSCEV(Op);
10321 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10322 MadeImprovement |= OrigV != OpV;
10323
10325 if (!C)
10326 return V;
10327 assert(C->getType() == Op->getType() && "Type mismatch");
10328 Operands.push_back(C);
10329 }
10330
10331 // Check to see if getSCEVAtScope actually made an improvement.
10332 if (!MadeImprovement)
10333 return V; // This is some other type of SCEVUnknown, just return it.
10334
10335 Constant *C = nullptr;
10336 const DataLayout &DL = getDataLayout();
10337 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10338 /*AllowNonDeterministic=*/false);
10339 if (!C)
10340 return V;
10341 return getSCEV(C);
10342 }
10343 case scCouldNotCompute:
10344 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10345 }
10346 llvm_unreachable("Unknown SCEV type!");
10347}
10348
10350 return getSCEVAtScope(getSCEV(V), L);
10351}
10352
10353const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10355 return stripInjectiveFunctions(ZExt->getOperand());
10357 return stripInjectiveFunctions(SExt->getOperand());
10358 return S;
10359}
10360
10361/// Finds the minimum unsigned root of the following equation:
10362///
10363/// A * X = B (mod N)
10364///
10365/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10366/// A and B isn't important.
10367///
10368/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10369static const SCEV *
10372 ScalarEvolution &SE, const Loop *L) {
10373 uint32_t BW = A.getBitWidth();
10374 assert(BW == SE.getTypeSizeInBits(B->getType()));
10375 assert(A != 0 && "A must be non-zero.");
10376
10377 // 1. D = gcd(A, N)
10378 //
10379 // The gcd of A and N may have only one prime factor: 2. The number of
10380 // trailing zeros in A is its multiplicity
10381 uint32_t Mult2 = A.countr_zero();
10382 // D = 2^Mult2
10383
10384 // 2. Check if B is divisible by D.
10385 //
10386 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10387 // is not less than multiplicity of this prime factor for D.
10388 unsigned MinTZ = SE.getMinTrailingZeros(B);
10389 // Try again with the terminator of the loop predecessor for context-specific
10390 // result, if MinTZ s too small.
10391 if (MinTZ < Mult2 && L->getLoopPredecessor())
10392 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10393 if (MinTZ < Mult2) {
10394 // Check if we can prove there's no remainder using URem.
10395 const SCEV *URem =
10396 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10397 const SCEV *Zero = SE.getZero(B->getType());
10398 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10399 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10400 if (!Predicates)
10401 return SE.getCouldNotCompute();
10402
10403 // Avoid adding a predicate that is known to be false.
10404 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10405 return SE.getCouldNotCompute();
10406 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10407 }
10408 }
10409
10410 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10411 // modulo (N / D).
10412 //
10413 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10414 // (N / D) in general. The inverse itself always fits into BW bits, though,
10415 // so we immediately truncate it.
10416 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10417 APInt I = AD.multiplicativeInverse().zext(BW);
10418
10419 // 4. Compute the minimum unsigned root of the equation:
10420 // I * (B / D) mod (N / D)
10421 // To simplify the computation, we factor out the divide by D:
10422 // (I * B mod N) / D
10423 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10424 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10425}
10426
10427/// For a given quadratic addrec, generate coefficients of the corresponding
10428/// quadratic equation, multiplied by a common value to ensure that they are
10429/// integers.
10430/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10431/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10432/// were multiplied by, and BitWidth is the bit width of the original addrec
10433/// coefficients.
10434/// This function returns std::nullopt if the addrec coefficients are not
10435/// compile- time constants.
10436static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10438 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10439 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10440 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10441 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10442 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10443 << *AddRec << '\n');
10444
10445 // We currently can only solve this if the coefficients are constants.
10446 if (!LC || !MC || !NC) {
10447 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10448 return std::nullopt;
10449 }
10450
10451 APInt L = LC->getAPInt();
10452 APInt M = MC->getAPInt();
10453 APInt N = NC->getAPInt();
10454 assert(!N.isZero() && "This is not a quadratic addrec");
10455
10456 unsigned BitWidth = LC->getAPInt().getBitWidth();
10457 unsigned NewWidth = BitWidth + 1;
10458 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10459 << BitWidth << '\n');
10460 // The sign-extension (as opposed to a zero-extension) here matches the
10461 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10462 N = N.sext(NewWidth);
10463 M = M.sext(NewWidth);
10464 L = L.sext(NewWidth);
10465
10466 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10467 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10468 // L+M, L+2M+N, L+3M+3N, ...
10469 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10470 //
10471 // The equation Acc = 0 is then
10472 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10473 // In a quadratic form it becomes:
10474 // N n^2 + (2M-N) n + 2L = 0.
10475
10476 APInt A = N;
10477 APInt B = 2 * M - A;
10478 APInt C = 2 * L;
10479 APInt T = APInt(NewWidth, 2);
10480 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10481 << "x + " << C << ", coeff bw: " << NewWidth
10482 << ", multiplied by " << T << '\n');
10483 return std::make_tuple(A, B, C, T, BitWidth);
10484}
10485
10486/// Helper function to compare optional APInts:
10487/// (a) if X and Y both exist, return min(X, Y),
10488/// (b) if neither X nor Y exist, return std::nullopt,
10489/// (c) if exactly one of X and Y exists, return that value.
10490static std::optional<APInt> MinOptional(std::optional<APInt> X,
10491 std::optional<APInt> Y) {
10492 if (X && Y) {
10493 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10494 APInt XW = X->sext(W);
10495 APInt YW = Y->sext(W);
10496 return XW.slt(YW) ? *X : *Y;
10497 }
10498 if (!X && !Y)
10499 return std::nullopt;
10500 return X ? *X : *Y;
10501}
10502
10503/// Helper function to truncate an optional APInt to a given BitWidth.
10504/// When solving addrec-related equations, it is preferable to return a value
10505/// that has the same bit width as the original addrec's coefficients. If the
10506/// solution fits in the original bit width, truncate it (except for i1).
10507/// Returning a value of a different bit width may inhibit some optimizations.
10508///
10509/// In general, a solution to a quadratic equation generated from an addrec
10510/// may require BW+1 bits, where BW is the bit width of the addrec's
10511/// coefficients. The reason is that the coefficients of the quadratic
10512/// equation are BW+1 bits wide (to avoid truncation when converting from
10513/// the addrec to the equation).
10514static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10515 unsigned BitWidth) {
10516 if (!X)
10517 return std::nullopt;
10518 unsigned W = X->getBitWidth();
10520 return X->trunc(BitWidth);
10521 return X;
10522}
10523
10524/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10525/// iterations. The values L, M, N are assumed to be signed, and they
10526/// should all have the same bit widths.
10527/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10528/// where BW is the bit width of the addrec's coefficients.
10529/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10530/// returned as such, otherwise the bit width of the returned value may
10531/// be greater than BW.
10532///
10533/// This function returns std::nullopt if
10534/// (a) the addrec coefficients are not constant, or
10535/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10536/// like x^2 = 5, no integer solutions exist, in other cases an integer
10537/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10538static std::optional<APInt>
10540 APInt A, B, C, M;
10541 unsigned BitWidth;
10542 auto T = GetQuadraticEquation(AddRec);
10543 if (!T)
10544 return std::nullopt;
10545
10546 std::tie(A, B, C, M, BitWidth) = *T;
10547 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10548 std::optional<APInt> X =
10550 if (!X)
10551 return std::nullopt;
10552
10553 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10554 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10555 if (!V->isZero())
10556 return std::nullopt;
10557
10558 return TruncIfPossible(X, BitWidth);
10559}
10560
10561/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10562/// iterations. The values M, N are assumed to be signed, and they
10563/// should all have the same bit widths.
10564/// Find the least n such that c(n) does not belong to the given range,
10565/// while c(n-1) does.
10566///
10567/// This function returns std::nullopt if
10568/// (a) the addrec coefficients are not constant, or
10569/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10570/// bounds of the range.
10571static std::optional<APInt>
10573 const ConstantRange &Range, ScalarEvolution &SE) {
10574 assert(AddRec->getOperand(0)->isZero() &&
10575 "Starting value of addrec should be 0");
10576 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10577 << Range << ", addrec " << *AddRec << '\n');
10578 // This case is handled in getNumIterationsInRange. Here we can assume that
10579 // we start in the range.
10580 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10581 "Addrec's initial value should be in range");
10582
10583 APInt A, B, C, M;
10584 unsigned BitWidth;
10585 auto T = GetQuadraticEquation(AddRec);
10586 if (!T)
10587 return std::nullopt;
10588
10589 // Be careful about the return value: there can be two reasons for not
10590 // returning an actual number. First, if no solutions to the equations
10591 // were found, and second, if the solutions don't leave the given range.
10592 // The first case means that the actual solution is "unknown", the second
10593 // means that it's known, but not valid. If the solution is unknown, we
10594 // cannot make any conclusions.
10595 // Return a pair: the optional solution and a flag indicating if the
10596 // solution was found.
10597 auto SolveForBoundary =
10598 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10599 // Solve for signed overflow and unsigned overflow, pick the lower
10600 // solution.
10601 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10602 << Bound << " (before multiplying by " << M << ")\n");
10603 Bound *= M; // The quadratic equation multiplier.
10604
10605 std::optional<APInt> SO;
10606 if (BitWidth > 1) {
10607 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10608 "signed overflow\n");
10610 }
10611 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10612 "unsigned overflow\n");
10613 std::optional<APInt> UO =
10615
10616 auto LeavesRange = [&] (const APInt &X) {
10617 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10618 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10619 if (Range.contains(V0->getValue()))
10620 return false;
10621 // X should be at least 1, so X-1 is non-negative.
10622 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10624 if (Range.contains(V1->getValue()))
10625 return true;
10626 return false;
10627 };
10628
10629 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10630 // can be a solution, but the function failed to find it. We cannot treat it
10631 // as "no solution".
10632 if (!SO || !UO)
10633 return {std::nullopt, false};
10634
10635 // Check the smaller value first to see if it leaves the range.
10636 // At this point, both SO and UO must have values.
10637 std::optional<APInt> Min = MinOptional(SO, UO);
10638 if (LeavesRange(*Min))
10639 return { Min, true };
10640 std::optional<APInt> Max = Min == SO ? UO : SO;
10641 if (LeavesRange(*Max))
10642 return { Max, true };
10643
10644 // Solutions were found, but were eliminated, hence the "true".
10645 return {std::nullopt, true};
10646 };
10647
10648 std::tie(A, B, C, M, BitWidth) = *T;
10649 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10650 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10651 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10652 auto SL = SolveForBoundary(Lower);
10653 auto SU = SolveForBoundary(Upper);
10654 // If any of the solutions was unknown, no meaninigful conclusions can
10655 // be made.
10656 if (!SL.second || !SU.second)
10657 return std::nullopt;
10658
10659 // Claim: The correct solution is not some value between Min and Max.
10660 //
10661 // Justification: Assuming that Min and Max are different values, one of
10662 // them is when the first signed overflow happens, the other is when the
10663 // first unsigned overflow happens. Crossing the range boundary is only
10664 // possible via an overflow (treating 0 as a special case of it, modeling
10665 // an overflow as crossing k*2^W for some k).
10666 //
10667 // The interesting case here is when Min was eliminated as an invalid
10668 // solution, but Max was not. The argument is that if there was another
10669 // overflow between Min and Max, it would also have been eliminated if
10670 // it was considered.
10671 //
10672 // For a given boundary, it is possible to have two overflows of the same
10673 // type (signed/unsigned) without having the other type in between: this
10674 // can happen when the vertex of the parabola is between the iterations
10675 // corresponding to the overflows. This is only possible when the two
10676 // overflows cross k*2^W for the same k. In such case, if the second one
10677 // left the range (and was the first one to do so), the first overflow
10678 // would have to enter the range, which would mean that either we had left
10679 // the range before or that we started outside of it. Both of these cases
10680 // are contradictions.
10681 //
10682 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10683 // solution is not some value between the Max for this boundary and the
10684 // Min of the other boundary.
10685 //
10686 // Justification: Assume that we had such Max_A and Min_B corresponding
10687 // to range boundaries A and B and such that Max_A < Min_B. If there was
10688 // a solution between Max_A and Min_B, it would have to be caused by an
10689 // overflow corresponding to either A or B. It cannot correspond to B,
10690 // since Min_B is the first occurrence of such an overflow. If it
10691 // corresponded to A, it would have to be either a signed or an unsigned
10692 // overflow that is larger than both eliminated overflows for A. But
10693 // between the eliminated overflows and this overflow, the values would
10694 // cover the entire value space, thus crossing the other boundary, which
10695 // is a contradiction.
10696
10697 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10698}
10699
10700ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10701 const Loop *L,
10702 bool ControlsOnlyExit,
10703 bool AllowPredicates) {
10704
10705 // This is only used for loops with a "x != y" exit test. The exit condition
10706 // is now expressed as a single expression, V = x-y. So the exit test is
10707 // effectively V != 0. We know and take advantage of the fact that this
10708 // expression only being used in a comparison by zero context.
10709
10711 // If the value is a constant
10712 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10713 // If the value is already zero, the branch will execute zero times.
10714 if (C->getValue()->isZero()) return C;
10715 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10716 }
10717
10718 const SCEVAddRecExpr *AddRec =
10719 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10720
10721 if (!AddRec && AllowPredicates)
10722 // Try to make this an AddRec using runtime tests, in the first X
10723 // iterations of this loop, where X is the SCEV expression found by the
10724 // algorithm below.
10725 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10726
10727 if (!AddRec || AddRec->getLoop() != L)
10728 return getCouldNotCompute();
10729
10730 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10731 // the quadratic equation to solve it.
10732 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10733 // We can only use this value if the chrec ends up with an exact zero
10734 // value at this index. When solving for "X*X != 5", for example, we
10735 // should not accept a root of 2.
10736 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10737 const auto *R = cast<SCEVConstant>(getConstant(*S));
10738 return ExitLimit(R, R, R, false, Predicates);
10739 }
10740 return getCouldNotCompute();
10741 }
10742
10743 // Otherwise we can only handle this if it is affine.
10744 if (!AddRec->isAffine())
10745 return getCouldNotCompute();
10746
10747 // If this is an affine expression, the execution count of this branch is
10748 // the minimum unsigned root of the following equation:
10749 //
10750 // Start + Step*N = 0 (mod 2^BW)
10751 //
10752 // equivalent to:
10753 //
10754 // Step*N = -Start (mod 2^BW)
10755 //
10756 // where BW is the common bit width of Start and Step.
10757
10758 // Get the initial value for the loop.
10759 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10760 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10761
10762 if (!isLoopInvariant(Step, L))
10763 return getCouldNotCompute();
10764
10765 LoopGuards Guards = LoopGuards::collect(L, *this);
10766 // Specialize step for this loop so we get context sensitive facts below.
10767 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10768
10769 // For positive steps (counting up until unsigned overflow):
10770 // N = -Start/Step (as unsigned)
10771 // For negative steps (counting down to zero):
10772 // N = Start/-Step
10773 // First compute the unsigned distance from zero in the direction of Step.
10774 bool CountDown = isKnownNegative(StepWLG);
10775 if (!CountDown && !isKnownNonNegative(StepWLG))
10776 return getCouldNotCompute();
10777
10778 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10779 // Handle unitary steps, which cannot wraparound.
10780 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10781 // N = Distance (as unsigned)
10782
10783 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10784 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10785 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10786
10787 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10788 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10789 // case, and see if we can improve the bound.
10790 //
10791 // Explicitly handling this here is necessary because getUnsignedRange
10792 // isn't context-sensitive; it doesn't know that we only care about the
10793 // range inside the loop.
10794 const SCEV *Zero = getZero(Distance->getType());
10795 const SCEV *One = getOne(Distance->getType());
10796 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10797 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10798 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10799 // as "unsigned_max(Distance + 1) - 1".
10800 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10801 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10802 }
10803 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10804 Predicates);
10805 }
10806
10807 // If the condition controls loop exit (the loop exits only if the expression
10808 // is true) and the addition is no-wrap we can use unsigned divide to
10809 // compute the backedge count. In this case, the step may not divide the
10810 // distance, but we don't care because if the condition is "missed" the loop
10811 // will have undefined behavior due to wrapping.
10812 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10813 loopHasNoAbnormalExits(AddRec->getLoop())) {
10814
10815 // If the stride is zero and the start is non-zero, the loop must be
10816 // infinite. In C++, most loops are finite by assumption, in which case the
10817 // step being zero implies UB must execute if the loop is entered.
10818 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10819 !isKnownNonZero(StepWLG))
10820 return getCouldNotCompute();
10821
10822 const SCEV *Exact =
10823 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10824 const SCEV *ConstantMax = getCouldNotCompute();
10825 if (Exact != getCouldNotCompute()) {
10826 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10827 ConstantMax =
10829 }
10830 const SCEV *SymbolicMax =
10831 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10832 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10833 }
10834
10835 // Solve the general equation.
10836 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10837 if (!StepC || StepC->getValue()->isZero())
10838 return getCouldNotCompute();
10839 const SCEV *E = SolveLinEquationWithOverflow(
10840 StepC->getAPInt(), getNegativeSCEV(Start),
10841 AllowPredicates ? &Predicates : nullptr, *this, L);
10842
10843 const SCEV *M = E;
10844 if (E != getCouldNotCompute()) {
10845 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10846 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10847 }
10848 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10849 return ExitLimit(E, M, S, false, Predicates);
10850}
10851
10852ScalarEvolution::ExitLimit
10853ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10854 // Loops that look like: while (X == 0) are very strange indeed. We don't
10855 // handle them yet except for the trivial case. This could be expanded in the
10856 // future as needed.
10857
10858 // If the value is a constant, check to see if it is known to be non-zero
10859 // already. If so, the backedge will execute zero times.
10860 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10861 if (!C->getValue()->isZero())
10862 return getZero(C->getType());
10863 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10864 }
10865
10866 // We could implement others, but I really doubt anyone writes loops like
10867 // this, and if they did, they would already be constant folded.
10868 return getCouldNotCompute();
10869}
10870
10871std::pair<const BasicBlock *, const BasicBlock *>
10872ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10873 const {
10874 // If the block has a unique predecessor, then there is no path from the
10875 // predecessor to the block that does not go through the direct edge
10876 // from the predecessor to the block.
10877 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10878 return {Pred, BB};
10879
10880 // A loop's header is defined to be a block that dominates the loop.
10881 // If the header has a unique predecessor outside the loop, it must be
10882 // a block that has exactly one successor that can reach the loop.
10883 if (const Loop *L = LI.getLoopFor(BB))
10884 return {L->getLoopPredecessor(), L->getHeader()};
10885
10886 return {nullptr, BB};
10887}
10888
10889/// SCEV structural equivalence is usually sufficient for testing whether two
10890/// expressions are equal, however for the purposes of looking for a condition
10891/// guarding a loop, it can be useful to be a little more general, since a
10892/// front-end may have replicated the controlling expression.
10893static bool HasSameValue(const SCEV *A, const SCEV *B) {
10894 // Quick check to see if they are the same SCEV.
10895 if (A == B) return true;
10896
10897 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10898 // Not all instructions that are "identical" compute the same value. For
10899 // instance, two distinct alloca instructions allocating the same type are
10900 // identical and do not read memory; but compute distinct values.
10901 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10902 };
10903
10904 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10905 // two different instructions with the same value. Check for this case.
10906 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10907 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10908 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10909 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10910 if (ComputesEqualValues(AI, BI))
10911 return true;
10912
10913 // Otherwise assume they may have a different value.
10914 return false;
10915}
10916
10917static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10918 const SCEV *Op0, *Op1;
10919 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10920 return false;
10921 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10922 LHS = Op1;
10923 return true;
10924 }
10925 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10926 LHS = Op0;
10927 return true;
10928 }
10929 return false;
10930}
10931
10933 SCEVUse &RHS, unsigned Depth) {
10934 bool Changed = false;
10935 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10936 // '0 != 0'.
10937 auto TrivialCase = [&](bool TriviallyTrue) {
10939 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10940 return true;
10941 };
10942 // If we hit the max recursion limit bail out.
10943 if (Depth >= 3)
10944 return false;
10945
10946 const SCEV *NewLHS, *NewRHS;
10947 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
10948 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
10949 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
10950 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
10951
10952 // (X * vscale) pred (Y * vscale) ==> X pred Y
10953 // when both multiples are NSW.
10954 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
10955 // when both multiples are NUW.
10956 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
10957 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
10958 !ICmpInst::isSigned(Pred))) {
10959 LHS = NewLHS;
10960 RHS = NewRHS;
10961 Changed = true;
10962 }
10963 }
10964
10965 // Canonicalize a constant to the right side.
10966 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
10967 // Check for both operands constant.
10968 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
10969 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
10970 return TrivialCase(false);
10971 return TrivialCase(true);
10972 }
10973 // Otherwise swap the operands to put the constant on the right.
10974 std::swap(LHS, RHS);
10976 Changed = true;
10977 }
10978
10979 // (K + A) pred (K + B) --> A pred B
10980 // For equality, no flags are needed.
10981 // For signed, both adds must be NSW. For unsigned, both must be NUW.
10982 {
10983 const SCEVConstant *C = nullptr;
10984 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
10985 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
10986 const auto *LAdd = cast<SCEVAddExpr>(LHS);
10987 const auto *RAdd = cast<SCEVAddExpr>(RHS);
10988 if (ICmpInst::isEquality(Pred) ||
10989 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
10990 RAdd->hasNoSignedWrap()) ||
10991 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
10992 RAdd->hasNoUnsignedWrap())) {
10993 LHS = NewLHS;
10994 RHS = NewRHS;
10995 Changed = true;
10996 }
10997 }
10998 }
10999
11000 // (C * A) pred (C * B) --> A pred B
11001 // For equality predicates, both muls must be NUW or both must be NSW
11002 // (either suffices to make multiplication by C injective; C == 0 is
11003 // impossible because SCEV folds 0 * X to 0).
11004 // For signed ordering, C must be positive and both muls must be NSW.
11005 // For unsigned ordering, both muls must be NUW.
11006 {
11007 const SCEVConstant *C = nullptr;
11008 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11009 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11010 const auto *LMul = cast<SCEVMulExpr>(LHS);
11011 const auto *RMul = cast<SCEVMulExpr>(RHS);
11012 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11013 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11014 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11015 (ICmpInst::isSigned(Pred) && BothNSW &&
11016 C->getAPInt().isStrictlyPositive()) ||
11017 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11018 LHS = NewLHS;
11019 RHS = NewRHS;
11020 Changed = true;
11021 }
11022 }
11023 }
11024
11025 // If we're comparing an addrec with a value which is loop-invariant in the
11026 // addrec's loop, put the addrec on the left. Also make a dominance check,
11027 // as both operands could be addrecs loop-invariant in each other's loop.
11028 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11029 const Loop *L = AR->getLoop();
11030 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11031 std::swap(LHS, RHS);
11033 Changed = true;
11034 }
11035 }
11036
11037 // If there's a constant operand, canonicalize comparisons with boundary
11038 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11039 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11040 const APInt &RA = RC->getAPInt();
11041
11042 bool SimplifiedByConstantRange = false;
11043
11044 if (!ICmpInst::isEquality(Pred)) {
11046 if (ExactCR.isFullSet())
11047 return TrivialCase(true);
11048 if (ExactCR.isEmptySet())
11049 return TrivialCase(false);
11050
11051 APInt NewRHS;
11052 CmpInst::Predicate NewPred;
11053 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11054 ICmpInst::isEquality(NewPred)) {
11055 // We were able to convert an inequality to an equality.
11056 Pred = NewPred;
11057 RHS = getConstant(NewRHS);
11058 Changed = SimplifiedByConstantRange = true;
11059 }
11060 }
11061
11062 if (!SimplifiedByConstantRange) {
11063 switch (Pred) {
11064 default:
11065 break;
11066 case ICmpInst::ICMP_EQ:
11067 case ICmpInst::ICMP_NE:
11068 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11069 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11070 Changed = true;
11071 break;
11072
11073 // The "Should have been caught earlier!" messages refer to the fact
11074 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11075 // should have fired on the corresponding cases, and canonicalized the
11076 // check to trivial case.
11077
11078 case ICmpInst::ICMP_UGE:
11079 assert(!RA.isMinValue() && "Should have been caught earlier!");
11080 Pred = ICmpInst::ICMP_UGT;
11081 RHS = getConstant(RA - 1);
11082 Changed = true;
11083 break;
11084 case ICmpInst::ICMP_ULE:
11085 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11086 Pred = ICmpInst::ICMP_ULT;
11087 RHS = getConstant(RA + 1);
11088 Changed = true;
11089 break;
11090 case ICmpInst::ICMP_SGE:
11091 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11092 Pred = ICmpInst::ICMP_SGT;
11093 RHS = getConstant(RA - 1);
11094 Changed = true;
11095 break;
11096 case ICmpInst::ICMP_SLE:
11097 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11098 Pred = ICmpInst::ICMP_SLT;
11099 RHS = getConstant(RA + 1);
11100 Changed = true;
11101 break;
11102 }
11103 }
11104 }
11105
11106 // Check for obvious equality.
11107 if (HasSameValue(LHS, RHS)) {
11108 if (ICmpInst::isTrueWhenEqual(Pred))
11109 return TrivialCase(true);
11111 return TrivialCase(false);
11112 }
11113
11114 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11115 // adding or subtracting 1 from one of the operands.
11116 switch (Pred) {
11117 case ICmpInst::ICMP_SLE:
11118 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11119 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11121 Pred = ICmpInst::ICMP_SLT;
11122 Changed = true;
11123 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11124 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11126 Pred = ICmpInst::ICMP_SLT;
11127 Changed = true;
11128 }
11129 break;
11130 case ICmpInst::ICMP_SGE:
11131 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11132 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11134 Pred = ICmpInst::ICMP_SGT;
11135 Changed = true;
11136 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11137 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11139 Pred = ICmpInst::ICMP_SGT;
11140 Changed = true;
11141 }
11142 break;
11143 case ICmpInst::ICMP_ULE:
11144 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11145 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11147 Pred = ICmpInst::ICMP_ULT;
11148 Changed = true;
11149 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11150 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11151 Pred = ICmpInst::ICMP_ULT;
11152 Changed = true;
11153 }
11154 break;
11155 case ICmpInst::ICMP_UGE:
11156 // If RHS is an op we can fold the -1, try that first.
11157 // Otherwise prefer LHS to preserve the nuw flag.
11158 if ((isa<SCEVConstant>(RHS) ||
11160 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11161 !getUnsignedRangeMin(RHS).isMinValue()) {
11162 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11163 Pred = ICmpInst::ICMP_UGT;
11164 Changed = true;
11165 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11166 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11168 Pred = ICmpInst::ICMP_UGT;
11169 Changed = true;
11170 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11171 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11172 Pred = ICmpInst::ICMP_UGT;
11173 Changed = true;
11174 }
11175 break;
11176 default:
11177 break;
11178 }
11179
11180 // TODO: More simplifications are possible here.
11181
11182 // Recursively simplify until we either hit a recursion limit or nothing
11183 // changes.
11184 if (Changed)
11185 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11186
11187 return Changed;
11188}
11189
11191 return getSignedRangeMax(S).isNegative();
11192}
11193
11197
11199 return !getSignedRangeMin(S).isNegative();
11200}
11201
11205
11207 // Query push down for cases where the unsigned range is
11208 // less than sufficient.
11209 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11210 return isKnownNonZero(SExt->getOperand(0));
11211 return getUnsignedRangeMin(S) != 0;
11212}
11213
11215 bool OrNegative) {
11216 auto NonRecursive = [OrNegative](const SCEV *S) {
11217 if (auto *C = dyn_cast<SCEVConstant>(S))
11218 return C->getAPInt().isPowerOf2() ||
11219 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11220
11221 // vscale is a power-of-two.
11222 return isa<SCEVVScale>(S);
11223 };
11224
11225 if (NonRecursive(S))
11226 return true;
11227
11228 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11229 if (!Mul)
11230 return false;
11231 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11232}
11233
11235 const SCEV *S, uint64_t M,
11237 if (M == 0)
11238 return false;
11239 if (M == 1)
11240 return true;
11241
11242 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11243 // starts with a multiple of M and at every iteration step S only adds
11244 // multiples of M.
11245 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11246 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11247 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11248
11249 // For a constant, check that "S % M == 0".
11250 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11251 APInt C = Cst->getAPInt();
11252 return C.urem(M) == 0;
11253 }
11254
11255 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11256
11257 // Basic tests have failed.
11258 // Check "S % M == 0" at compile time and record runtime Assumptions.
11259 auto *STy = dyn_cast<IntegerType>(S->getType());
11260 const SCEV *SmodM =
11261 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11262 const SCEV *Zero = getZero(STy);
11263
11264 // Check whether "S % M == 0" is known at compile time.
11265 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11266 return true;
11267
11268 // Check whether "S % M != 0" is known at compile time.
11269 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11270 return false;
11271
11273
11274 // Detect redundant predicates.
11275 for (auto *A : Assumptions)
11276 if (A->implies(P, *this))
11277 return true;
11278
11279 // Only record non-redundant predicates.
11280 Assumptions.push_back(P);
11281 return true;
11282}
11283
11285 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11287}
11288
11289std::pair<const SCEV *, const SCEV *>
11291 // Compute SCEV on entry of loop L.
11292 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11293 if (Start == getCouldNotCompute())
11294 return { Start, Start };
11295 // Compute post increment SCEV for loop L.
11296 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11297 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11298 return { Start, PostInc };
11299}
11300
11302 SCEVUse RHS) {
11303 // First collect all loops.
11305 getUsedLoops(LHS, LoopsUsed);
11306 getUsedLoops(RHS, LoopsUsed);
11307
11308 if (LoopsUsed.empty())
11309 return false;
11310
11311 // Domination relationship must be a linear order on collected loops.
11312#ifndef NDEBUG
11313 for (const auto *L1 : LoopsUsed)
11314 for (const auto *L2 : LoopsUsed)
11315 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11316 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11317 "Domination relationship is not a linear order");
11318#endif
11319
11320 const Loop *MDL =
11321 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11322 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11323 });
11324
11325 // Get init and post increment value for LHS.
11326 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11327 // if LHS contains unknown non-invariant SCEV then bail out.
11328 if (SplitLHS.first == getCouldNotCompute())
11329 return false;
11330 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11331 // Get init and post increment value for RHS.
11332 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11333 // if RHS contains unknown non-invariant SCEV then bail out.
11334 if (SplitRHS.first == getCouldNotCompute())
11335 return false;
11336 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11337 // It is possible that init SCEV contains an invariant load but it does
11338 // not dominate MDL and is not available at MDL loop entry, so we should
11339 // check it here.
11340 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11341 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11342 return false;
11343
11344 // It seems backedge guard check is faster than entry one so in some cases
11345 // it can speed up whole estimation by short circuit
11346 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11347 SplitRHS.second) &&
11348 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11349}
11350
11352 SCEVUse RHS) {
11353 // Canonicalize the inputs first.
11354 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11355
11356 if (isKnownViaInduction(Pred, LHS, RHS))
11357 return true;
11358
11359 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11360 return true;
11361
11362 // Otherwise see what can be done with some simple reasoning.
11363 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11364}
11365
11367 const SCEV *LHS,
11368 const SCEV *RHS) {
11369 if (isKnownPredicate(Pred, LHS, RHS))
11370 return true;
11372 return false;
11373 return std::nullopt;
11374}
11375
11377 const SCEV *RHS,
11378 const Instruction *CtxI) {
11379 // TODO: Analyze guards and assumes from Context's block.
11380 return isKnownPredicate(Pred, LHS, RHS) ||
11381 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11382}
11383
11384std::optional<bool>
11386 const SCEV *RHS, const Instruction *CtxI) {
11387 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11388 if (KnownWithoutContext)
11389 return KnownWithoutContext;
11390
11391 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11392 return true;
11394 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11395 return false;
11396 return std::nullopt;
11397}
11398
11400 const SCEVAddRecExpr *LHS,
11401 const SCEV *RHS) {
11402 const Loop *L = LHS->getLoop();
11403 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11404 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11405}
11406
11407std::optional<ScalarEvolution::MonotonicPredicateType>
11409 ICmpInst::Predicate Pred) {
11410 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11411
11412#ifndef NDEBUG
11413 // Verify an invariant: inverting the predicate should turn a monotonically
11414 // increasing change to a monotonically decreasing one, and vice versa.
11415 if (Result) {
11416 auto ResultSwapped =
11417 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11418
11419 assert(*ResultSwapped != *Result &&
11420 "monotonicity should flip as we flip the predicate");
11421 }
11422#endif
11423
11424 return Result;
11425}
11426
11427std::optional<ScalarEvolution::MonotonicPredicateType>
11428ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11429 ICmpInst::Predicate Pred) {
11430 // A zero step value for LHS means the induction variable is essentially a
11431 // loop invariant value. We don't really depend on the predicate actually
11432 // flipping from false to true (for increasing predicates, and the other way
11433 // around for decreasing predicates), all we care about is that *if* the
11434 // predicate changes then it only changes from false to true.
11435 //
11436 // A zero step value in itself is not very useful, but there may be places
11437 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11438 // as general as possible.
11439
11440 // Only handle LE/LT/GE/GT predicates.
11441 if (!ICmpInst::isRelational(Pred))
11442 return std::nullopt;
11443
11444 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11445 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11446 "Should be greater or less!");
11447
11448 // Check that AR does not wrap.
11449 if (ICmpInst::isUnsigned(Pred)) {
11450 if (!LHS->hasNoUnsignedWrap())
11451 return std::nullopt;
11453 }
11454 assert(ICmpInst::isSigned(Pred) &&
11455 "Relational predicate is either signed or unsigned!");
11456 if (!LHS->hasNoSignedWrap())
11457 return std::nullopt;
11458
11459 const SCEV *Step = LHS->getStepRecurrence(*this);
11460
11461 if (isKnownNonNegative(Step))
11463
11464 if (isKnownNonPositive(Step))
11466
11467 return std::nullopt;
11468}
11469
11470std::optional<ScalarEvolution::LoopInvariantPredicate>
11472 const SCEV *RHS, const Loop *L,
11473 const Instruction *CtxI) {
11474 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11475 if (!isLoopInvariant(RHS, L)) {
11476 if (!isLoopInvariant(LHS, L))
11477 return std::nullopt;
11478
11479 std::swap(LHS, RHS);
11481 }
11482
11483 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11484 if (!ArLHS || ArLHS->getLoop() != L)
11485 return std::nullopt;
11486
11487 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11488 if (!MonotonicType)
11489 return std::nullopt;
11490 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11491 // true as the loop iterates, and the backedge is control dependent on
11492 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11493 //
11494 // * if the predicate was false in the first iteration then the predicate
11495 // is never evaluated again, since the loop exits without taking the
11496 // backedge.
11497 // * if the predicate was true in the first iteration then it will
11498 // continue to be true for all future iterations since it is
11499 // monotonically increasing.
11500 //
11501 // For both the above possibilities, we can replace the loop varying
11502 // predicate with its value on the first iteration of the loop (which is
11503 // loop invariant).
11504 //
11505 // A similar reasoning applies for a monotonically decreasing predicate, by
11506 // replacing true with false and false with true in the above two bullets.
11508 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11509
11510 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11512 RHS);
11513
11514 if (!CtxI)
11515 return std::nullopt;
11516 // Try to prove via context.
11517 // TODO: Support other cases.
11518 switch (Pred) {
11519 default:
11520 break;
11521 case ICmpInst::ICMP_ULE:
11522 case ICmpInst::ICMP_ULT: {
11523 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11524 // Given preconditions
11525 // (1) ArLHS does not cross the border of positive and negative parts of
11526 // range because of:
11527 // - Positive step; (TODO: lift this limitation)
11528 // - nuw - does not cross zero boundary;
11529 // - nsw - does not cross SINT_MAX boundary;
11530 // (2) ArLHS <s RHS
11531 // (3) RHS >=s 0
11532 // we can replace the loop variant ArLHS <u RHS condition with loop
11533 // invariant Start(ArLHS) <u RHS.
11534 //
11535 // Because of (1) there are two options:
11536 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11537 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11538 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11539 // Because of (2) ArLHS <u RHS is trivially true.
11540 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11541 // We can strengthen this to Start(ArLHS) <u RHS.
11542 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11543 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11544 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11545 isKnownNonNegative(RHS) &&
11546 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11548 RHS);
11549 }
11550 }
11551
11552 return std::nullopt;
11553}
11554
11555std::optional<ScalarEvolution::LoopInvariantPredicate>
11557 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11558 const Instruction *CtxI, const SCEV *MaxIter) {
11560 Pred, LHS, RHS, L, CtxI, MaxIter))
11561 return LIP;
11562 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11563 // Number of iterations expressed as UMIN isn't always great for expressing
11564 // the value on the last iteration. If the straightforward approach didn't
11565 // work, try the following trick: if the a predicate is invariant for X, it
11566 // is also invariant for umin(X, ...). So try to find something that works
11567 // among subexpressions of MaxIter expressed as umin.
11568 for (SCEVUse Op : UMin->operands())
11570 Pred, LHS, RHS, L, CtxI, Op))
11571 return LIP;
11572 return std::nullopt;
11573}
11574
11575std::optional<ScalarEvolution::LoopInvariantPredicate>
11577 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11578 const Instruction *CtxI, const SCEV *MaxIter) {
11579 // Try to prove the following set of facts:
11580 // - The predicate is monotonic in the iteration space.
11581 // - If the check does not fail on the 1st iteration:
11582 // - No overflow will happen during first MaxIter iterations;
11583 // - It will not fail on the MaxIter'th iteration.
11584 // If the check does fail on the 1st iteration, we leave the loop and no
11585 // other checks matter.
11586
11587 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11588 if (!isLoopInvariant(RHS, L)) {
11589 if (!isLoopInvariant(LHS, L))
11590 return std::nullopt;
11591
11592 std::swap(LHS, RHS);
11594 }
11595
11596 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11597 if (!AR || AR->getLoop() != L)
11598 return std::nullopt;
11599
11600 // Even if both are valid, we need to consistently chose the unsigned or the
11601 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11602 // predicate.
11603 Pred = Pred.dropSameSign();
11604
11605 // The predicate must be relational (i.e. <, <=, >=, >).
11606 if (!ICmpInst::isRelational(Pred))
11607 return std::nullopt;
11608
11609 // TODO: Support steps other than +/- 1.
11610 const SCEV *Step = AR->getStepRecurrence(*this);
11611 auto *One = getOne(Step->getType());
11612 auto *MinusOne = getNegativeSCEV(One);
11613 if (Step != One && Step != MinusOne)
11614 return std::nullopt;
11615
11616 // Type mismatch here means that MaxIter is potentially larger than max
11617 // unsigned value in start type, which mean we cannot prove no wrap for the
11618 // indvar.
11619 if (AR->getType() != MaxIter->getType())
11620 return std::nullopt;
11621
11622 // Value of IV on suggested last iteration.
11623 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11624 // Does it still meet the requirement?
11625 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11626 return std::nullopt;
11627 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11628 // not exceed max unsigned value of this type), this effectively proves
11629 // that there is no wrap during the iteration. To prove that there is no
11630 // signed/unsigned wrap, we need to check that
11631 // Start <= Last for step = 1 or Start >= Last for step = -1.
11632 ICmpInst::Predicate NoOverflowPred =
11634 if (Step == MinusOne)
11635 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11636 const SCEV *Start = AR->getStart();
11637 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11638 return std::nullopt;
11639
11640 // Everything is fine.
11641 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11642}
11643
11644bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11645 SCEVUse LHS,
11646 SCEVUse RHS) {
11647 if (HasSameValue(LHS, RHS))
11648 return ICmpInst::isTrueWhenEqual(Pred);
11649
11650 auto CheckRange = [&](bool IsSigned) {
11651 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11652 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11653 return RangeLHS.icmp(Pred, RangeRHS);
11654 };
11655
11656 // The check at the top of the function catches the case where the values are
11657 // known to be equal.
11658 if (Pred == CmpInst::ICMP_EQ)
11659 return false;
11660
11661 if (Pred == CmpInst::ICMP_NE) {
11662 if (CheckRange(true) || CheckRange(false))
11663 return true;
11664 auto *Diff = getMinusSCEV(LHS, RHS);
11665 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11666 }
11667
11668 return CheckRange(CmpInst::isSigned(Pred));
11669}
11670
11671bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11673 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11674 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11675 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11676 // OutC1 and OutC2.
11677 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11678 APInt &OutC2,
11679 SCEV::NoWrapFlags ExpectedFlags) {
11680 SCEVUse XNonConstOp, XConstOp;
11681 SCEVUse YNonConstOp, YConstOp;
11682 SCEV::NoWrapFlags XFlagsPresent;
11683 SCEV::NoWrapFlags YFlagsPresent;
11684
11685 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11686 XConstOp = getZero(X->getType());
11687 XNonConstOp = X;
11688 XFlagsPresent = ExpectedFlags;
11689 }
11690 if (!isa<SCEVConstant>(XConstOp))
11691 return false;
11692
11693 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11694 YConstOp = getZero(Y->getType());
11695 YNonConstOp = Y;
11696 YFlagsPresent = ExpectedFlags;
11697 }
11698
11699 if (YNonConstOp != XNonConstOp)
11700 return false;
11701
11702 if (!isa<SCEVConstant>(YConstOp))
11703 return false;
11704
11705 // When matching ADDs with NUW flags (and unsigned predicates), only the
11706 // second ADD (with the larger constant) requires NUW.
11707 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11708 return false;
11709 if (ExpectedFlags != SCEV::FlagNUW &&
11710 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11711 return false;
11712 }
11713
11714 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11715 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11716
11717 return true;
11718 };
11719
11720 APInt C1;
11721 APInt C2;
11722
11723 switch (Pred) {
11724 default:
11725 break;
11726
11727 case ICmpInst::ICMP_SGE:
11728 std::swap(LHS, RHS);
11729 [[fallthrough]];
11730 case ICmpInst::ICMP_SLE:
11731 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11732 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11733 return true;
11734
11735 break;
11736
11737 case ICmpInst::ICMP_SGT:
11738 std::swap(LHS, RHS);
11739 [[fallthrough]];
11740 case ICmpInst::ICMP_SLT:
11741 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11742 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11743 return true;
11744
11745 break;
11746
11747 case ICmpInst::ICMP_UGE:
11748 std::swap(LHS, RHS);
11749 [[fallthrough]];
11750 case ICmpInst::ICMP_ULE:
11751 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11752 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11753 return true;
11754
11755 break;
11756
11757 case ICmpInst::ICMP_UGT:
11758 std::swap(LHS, RHS);
11759 [[fallthrough]];
11760 case ICmpInst::ICMP_ULT:
11761 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11762 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11763 return true;
11764 break;
11765 }
11766
11767 return false;
11768}
11769
11770bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11772 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11773 return false;
11774
11775 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11776 // the stack can result in exponential time complexity.
11777 SaveAndRestore Restore(ProvingSplitPredicate, true);
11778
11779 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11780 //
11781 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11782 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11783 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11784 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11785 // use isKnownPredicate later if needed.
11786 return isKnownNonNegative(RHS) &&
11789}
11790
11791bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11792 const SCEV *LHS, const SCEV *RHS) {
11793 // No need to even try if we know the module has no guards.
11794 if (!HasGuards)
11795 return false;
11796
11797 return any_of(*BB, [&](const Instruction &I) {
11798 using namespace llvm::PatternMatch;
11799
11800 Value *Condition;
11802 m_Value(Condition))) &&
11803 isImpliedCond(Pred, LHS, RHS, Condition, false);
11804 });
11805}
11806
11807/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11808/// protected by a conditional between LHS and RHS. This is used to
11809/// to eliminate casts.
11811 CmpPredicate Pred,
11812 const SCEV *LHS,
11813 const SCEV *RHS) {
11814 // Interpret a null as meaning no loop, where there is obviously no guard
11815 // (interprocedural conditions notwithstanding). Do not bother about
11816 // unreachable loops.
11817 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11818 return true;
11819
11820 if (VerifyIR)
11821 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11822 "This cannot be done on broken IR!");
11823
11824
11825 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11826 return true;
11827
11828 BasicBlock *Latch = L->getLoopLatch();
11829 if (!Latch)
11830 return false;
11831
11832 CondBrInst *LoopContinuePredicate =
11834 if (LoopContinuePredicate &&
11835 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11836 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11837 return true;
11838
11839 // We don't want more than one activation of the following loops on the stack
11840 // -- that can lead to O(n!) time complexity.
11841 if (WalkingBEDominatingConds)
11842 return false;
11843
11844 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11845
11846 // See if we can exploit a trip count to prove the predicate.
11847 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11848 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11849 if (LatchBECount != getCouldNotCompute()) {
11850 // We know that Latch branches back to the loop header exactly
11851 // LatchBECount times. This means the backdege condition at Latch is
11852 // equivalent to "{0,+,1} u< LatchBECount".
11853 Type *Ty = LatchBECount->getType();
11854 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
11855 const SCEV *LoopCounter =
11856 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11857 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11858 LatchBECount))
11859 return true;
11860 }
11861
11862 // Check conditions due to any @llvm.assume intrinsics.
11863 for (auto &AssumeVH : AC.assumptions()) {
11864 if (!AssumeVH)
11865 continue;
11866 auto *CI = cast<CallInst>(AssumeVH);
11867 if (!DT.dominates(CI, Latch->getTerminator()))
11868 continue;
11869
11870 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11871 return true;
11872 }
11873
11874 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11875 return true;
11876
11877 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11878 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11879 assert(DTN && "should reach the loop header before reaching the root!");
11880
11881 BasicBlock *BB = DTN->getBlock();
11882 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11883 return true;
11884
11885 BasicBlock *PBB = BB->getSinglePredecessor();
11886 if (!PBB)
11887 continue;
11888
11890 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11891 continue;
11892
11893 // If we have an edge `E` within the loop body that dominates the only
11894 // latch, the condition guarding `E` also guards the backedge. This
11895 // reasoning works only for loops with a single latch.
11896 // We're constructively (and conservatively) enumerating edges within the
11897 // loop body that dominate the latch. The dominator tree better agree
11898 // with us on this:
11899 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11900 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11901 BB != ContBr->getSuccessor(0)))
11902 return true;
11903 }
11904
11905 return false;
11906}
11907
11909 CmpPredicate Pred,
11910 const SCEV *LHS,
11911 const SCEV *RHS) {
11912 // Do not bother proving facts for unreachable code.
11913 if (!DT.isReachableFromEntry(BB))
11914 return true;
11915 if (VerifyIR)
11916 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11917 "This cannot be done on broken IR!");
11918
11919 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
11920 // the facts (a >= b && a != b) separately. A typical situation is when the
11921 // non-strict comparison is known from ranges and non-equality is known from
11922 // dominating predicates. If we are proving strict comparison, we always try
11923 // to prove non-equality and non-strict comparison separately.
11924 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
11925 const bool ProvingStrictComparison =
11926 Pred != NonStrictPredicate.dropSameSign();
11927 bool ProvedNonStrictComparison = false;
11928 bool ProvedNonEquality = false;
11929
11930 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
11931 if (!ProvedNonStrictComparison)
11932 ProvedNonStrictComparison = Fn(NonStrictPredicate);
11933 if (!ProvedNonEquality)
11934 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
11935 if (ProvedNonStrictComparison && ProvedNonEquality)
11936 return true;
11937 return false;
11938 };
11939
11940 if (ProvingStrictComparison) {
11941 auto ProofFn = [&](CmpPredicate P) {
11942 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
11943 };
11944 if (SplitAndProve(ProofFn))
11945 return true;
11946 }
11947
11948 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
11949 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
11950 const Instruction *CtxI = &BB->front();
11951 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
11952 return true;
11953 if (ProvingStrictComparison) {
11954 auto ProofFn = [&](CmpPredicate P) {
11955 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
11956 };
11957 if (SplitAndProve(ProofFn))
11958 return true;
11959 }
11960 return false;
11961 };
11962
11963 // Starting at the block's predecessor, climb up the predecessor chain, as long
11964 // as there are predecessors that can be found that have unique successors
11965 // leading to the original block.
11966 const Loop *ContainingLoop = LI.getLoopFor(BB);
11967 const BasicBlock *PredBB;
11968 if (ContainingLoop && ContainingLoop->getHeader() == BB)
11969 PredBB = ContainingLoop->getLoopPredecessor();
11970 else
11971 PredBB = BB->getSinglePredecessor();
11972 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
11973 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
11974 const CondBrInst *BlockEntryPredicate =
11975 dyn_cast<CondBrInst>(Pair.first->getTerminator());
11976 if (!BlockEntryPredicate)
11977 continue;
11978
11979 if (ProveViaCond(BlockEntryPredicate->getCondition(),
11980 BlockEntryPredicate->getSuccessor(0) != Pair.second))
11981 return true;
11982 }
11983
11984 // Check conditions due to any @llvm.assume intrinsics.
11985 for (auto &AssumeVH : AC.assumptions()) {
11986 if (!AssumeVH)
11987 continue;
11988 auto *CI = cast<CallInst>(AssumeVH);
11989 if (!DT.dominates(CI, BB))
11990 continue;
11991
11992 if (ProveViaCond(CI->getArgOperand(0), false))
11993 return true;
11994 }
11995
11996 // Check conditions due to any @llvm.experimental.guard intrinsics.
11997 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
11998 F.getParent(), Intrinsic::experimental_guard);
11999 if (GuardDecl)
12000 for (const auto *GU : GuardDecl->users())
12001 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12002 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12003 if (ProveViaCond(Guard->getArgOperand(0), false))
12004 return true;
12005 return false;
12006}
12007
12009 const SCEV *LHS,
12010 const SCEV *RHS) {
12011 // Interpret a null as meaning no loop, where there is obviously no guard
12012 // (interprocedural conditions notwithstanding).
12013 if (!L)
12014 return false;
12015
12016 // Both LHS and RHS must be available at loop entry.
12018 "LHS is not available at Loop Entry");
12020 "RHS is not available at Loop Entry");
12021
12022 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12023 return true;
12024
12025 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12026}
12027
12028bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12029 const SCEV *RHS,
12030 const Value *FoundCondValue, bool Inverse,
12031 const Instruction *CtxI) {
12032 // False conditions implies anything. Do not bother analyzing it further.
12033 if (FoundCondValue ==
12034 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12035 return true;
12036
12037 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12038 return false;
12039
12040 llvm::scope_exit ClearOnExit(
12041 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12042
12043 // Recursively handle And and Or conditions.
12044 const Value *Op0, *Op1;
12045 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12046 if (!Inverse)
12047 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12048 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12049 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12050 if (Inverse)
12051 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12052 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12053 }
12054
12055 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12056 if (!ICI) return false;
12057
12058 // Now that we found a conditional branch that dominates the loop or controls
12059 // the loop latch. Check to see if it is the comparison we are looking for.
12060 CmpPredicate FoundPred;
12061 if (Inverse)
12062 FoundPred = ICI->getInverseCmpPredicate();
12063 else
12064 FoundPred = ICI->getCmpPredicate();
12065
12066 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12067 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12068
12069 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12070}
12071
12072bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12073 const SCEV *RHS, CmpPredicate FoundPred,
12074 const SCEV *FoundLHS, const SCEV *FoundRHS,
12075 const Instruction *CtxI) {
12076 // Balance the types.
12077 if (getTypeSizeInBits(LHS->getType()) <
12078 getTypeSizeInBits(FoundLHS->getType())) {
12079 // For unsigned and equality predicates, try to prove that both found
12080 // operands fit into narrow unsigned range. If so, try to prove facts in
12081 // narrow types.
12082 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12083 !FoundRHS->getType()->isPointerTy()) {
12084 auto *NarrowType = LHS->getType();
12085 auto *WideType = FoundLHS->getType();
12086 auto BitWidth = getTypeSizeInBits(NarrowType);
12087 const SCEV *MaxValue = getZeroExtendExpr(
12089 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12090 MaxValue) &&
12091 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12092 MaxValue)) {
12093 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12094 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12095 // We cannot preserve samesign after truncation.
12096 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12097 TruncFoundLHS, TruncFoundRHS, CtxI))
12098 return true;
12099 }
12100 }
12101
12102 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12103 return false;
12104 if (CmpInst::isSigned(Pred)) {
12105 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12106 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12107 } else {
12108 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12109 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12110 }
12111 } else if (getTypeSizeInBits(LHS->getType()) >
12112 getTypeSizeInBits(FoundLHS->getType())) {
12113 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12114 return false;
12115 if (CmpInst::isSigned(FoundPred)) {
12116 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12117 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12118 } else {
12119 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12120 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12121 }
12122 }
12123 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12124 FoundRHS, CtxI);
12125}
12126
12127bool ScalarEvolution::isImpliedCondBalancedTypes(
12128 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12129 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12131 getTypeSizeInBits(FoundLHS->getType()) &&
12132 "Types should be balanced!");
12133 // Canonicalize the query to match the way instcombine will have
12134 // canonicalized the comparison.
12135 if (SimplifyICmpOperands(Pred, LHS, RHS))
12136 if (LHS == RHS)
12137 return CmpInst::isTrueWhenEqual(Pred);
12138 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12139 if (FoundLHS == FoundRHS)
12140 return CmpInst::isFalseWhenEqual(FoundPred);
12141
12142 // Check to see if we can make the LHS or RHS match.
12143 if (LHS == FoundRHS || RHS == FoundLHS) {
12144 if (isa<SCEVConstant>(RHS)) {
12145 std::swap(FoundLHS, FoundRHS);
12146 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12147 } else {
12148 std::swap(LHS, RHS);
12150 }
12151 }
12152
12153 // Check whether the found predicate is the same as the desired predicate.
12154 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12155 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12156
12157 // Check whether swapping the found predicate makes it the same as the
12158 // desired predicate.
12159 if (auto P = CmpPredicate::getMatching(
12160 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12161 // We can write the implication
12162 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12163 // using one of the following ways:
12164 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12165 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12166 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12167 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12168 // Forms 1. and 2. require swapping the operands of one condition. Don't
12169 // do this if it would break canonical constant/addrec ordering.
12171 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12172 LHS, FoundLHS, FoundRHS, CtxI);
12173 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12174 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12175
12176 // There's no clear preference between forms 3. and 4., try both. Avoid
12177 // forming getNotSCEV of pointer values as the resulting subtract is
12178 // not legal.
12179 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12180 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12181 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12182 FoundRHS, CtxI))
12183 return true;
12184
12185 if (!FoundLHS->getType()->isPointerTy() &&
12186 !FoundRHS->getType()->isPointerTy() &&
12187 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12188 getNotSCEV(FoundRHS), CtxI))
12189 return true;
12190
12191 return false;
12192 }
12193
12194 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12196 assert(P1 != P2 && "Handled earlier!");
12197 return CmpInst::isRelational(P2) &&
12199 };
12200 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12201 // Unsigned comparison is the same as signed comparison when both the
12202 // operands are non-negative or negative.
12203 if (haveSameSign(FoundLHS, FoundRHS))
12204 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12205 // Create local copies that we can freely swap and canonicalize our
12206 // conditions to "le/lt".
12207 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12208 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12209 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12210 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12211 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12212 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12213 std::swap(CanonicalLHS, CanonicalRHS);
12214 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12215 }
12216 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12217 "Must be!");
12218 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12219 ICmpInst::isLE(CanonicalFoundPred)) &&
12220 "Must be!");
12221 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12222 // Use implication:
12223 // x <u y && y >=s 0 --> x <s y.
12224 // If we can prove the left part, the right part is also proven.
12225 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12226 CanonicalRHS, CanonicalFoundLHS,
12227 CanonicalFoundRHS);
12228 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12229 // Use implication:
12230 // x <s y && y <s 0 --> x <u y.
12231 // If we can prove the left part, the right part is also proven.
12232 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12233 CanonicalRHS, CanonicalFoundLHS,
12234 CanonicalFoundRHS);
12235 }
12236
12237 // Check if we can make progress by sharpening ranges.
12238 if (FoundPred == ICmpInst::ICMP_NE &&
12239 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12240
12241 const SCEVConstant *C = nullptr;
12242 const SCEV *V = nullptr;
12243
12244 if (isa<SCEVConstant>(FoundLHS)) {
12245 C = cast<SCEVConstant>(FoundLHS);
12246 V = FoundRHS;
12247 } else {
12248 C = cast<SCEVConstant>(FoundRHS);
12249 V = FoundLHS;
12250 }
12251
12252 // The guarding predicate tells us that C != V. If the known range
12253 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12254 // range we consider has to correspond to same signedness as the
12255 // predicate we're interested in folding.
12256
12257 APInt Min = ICmpInst::isSigned(Pred) ?
12259
12260 if (Min == C->getAPInt()) {
12261 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12262 // This is true even if (Min + 1) wraps around -- in case of
12263 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12264
12265 APInt SharperMin = Min + 1;
12266
12267 switch (Pred) {
12268 case ICmpInst::ICMP_SGE:
12269 case ICmpInst::ICMP_UGE:
12270 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12271 // RHS, we're done.
12272 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12273 CtxI))
12274 return true;
12275 [[fallthrough]];
12276
12277 case ICmpInst::ICMP_SGT:
12278 case ICmpInst::ICMP_UGT:
12279 // We know from the range information that (V `Pred` Min ||
12280 // V == Min). We know from the guarding condition that !(V
12281 // == Min). This gives us
12282 //
12283 // V `Pred` Min || V == Min && !(V == Min)
12284 // => V `Pred` Min
12285 //
12286 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12287
12288 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12289 return true;
12290 break;
12291
12292 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12293 case ICmpInst::ICMP_SLE:
12294 case ICmpInst::ICMP_ULE:
12295 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12296 LHS, V, getConstant(SharperMin), CtxI))
12297 return true;
12298 [[fallthrough]];
12299
12300 case ICmpInst::ICMP_SLT:
12301 case ICmpInst::ICMP_ULT:
12302 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12303 LHS, V, getConstant(Min), CtxI))
12304 return true;
12305 break;
12306
12307 default:
12308 // No change
12309 break;
12310 }
12311 }
12312 }
12313
12314 // Check whether the actual condition is beyond sufficient.
12315 if (FoundPred == ICmpInst::ICMP_EQ)
12316 if (ICmpInst::isTrueWhenEqual(Pred))
12317 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12318 return true;
12319 if (Pred == ICmpInst::ICMP_NE)
12320 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12321 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12322 return true;
12323
12324 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12325 return true;
12326
12327 // Otherwise assume the worst.
12328 return false;
12329}
12330
12331bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12332 SCEV::NoWrapFlags &Flags) {
12333 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12334 return false;
12335
12336 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12337 return true;
12338}
12339
12340std::optional<APInt>
12342 // We avoid subtracting expressions here because this function is usually
12343 // fairly deep in the call stack (i.e. is called many times).
12344
12345 unsigned BW = getTypeSizeInBits(More->getType());
12346 APInt Diff(BW, 0);
12347 APInt DiffMul(BW, 1);
12348 // Try various simplifications to reduce the difference to a constant. Limit
12349 // the number of allowed simplifications to keep compile-time low.
12350 for (unsigned I = 0; I < 8; ++I) {
12351 if (More == Less)
12352 return Diff;
12353
12354 // Reduce addrecs with identical steps to their start value.
12356 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12357 const auto *MAR = cast<SCEVAddRecExpr>(More);
12358
12359 if (LAR->getLoop() != MAR->getLoop())
12360 return std::nullopt;
12361
12362 // We look at affine expressions only; not for correctness but to keep
12363 // getStepRecurrence cheap.
12364 if (!LAR->isAffine() || !MAR->isAffine())
12365 return std::nullopt;
12366
12367 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12368 return std::nullopt;
12369
12370 Less = LAR->getStart();
12371 More = MAR->getStart();
12372 continue;
12373 }
12374
12375 // Try to match a common constant multiply.
12376 auto MatchConstMul =
12377 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12378 const APInt *C;
12379 const SCEV *Op;
12380 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12381 return {{Op, *C}};
12382 return std::nullopt;
12383 };
12384 if (auto MatchedMore = MatchConstMul(More)) {
12385 if (auto MatchedLess = MatchConstMul(Less)) {
12386 if (MatchedMore->second == MatchedLess->second) {
12387 More = MatchedMore->first;
12388 Less = MatchedLess->first;
12389 DiffMul *= MatchedMore->second;
12390 continue;
12391 }
12392 }
12393 }
12394
12395 // Try to cancel out common factors in two add expressions.
12397 auto Add = [&](const SCEV *S, int Mul) {
12398 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12399 if (Mul == 1) {
12400 Diff += C->getAPInt() * DiffMul;
12401 } else {
12402 assert(Mul == -1);
12403 Diff -= C->getAPInt() * DiffMul;
12404 }
12405 } else
12406 Multiplicity[S] += Mul;
12407 };
12408 auto Decompose = [&](const SCEV *S, int Mul) {
12409 if (isa<SCEVAddExpr>(S)) {
12410 for (const SCEV *Op : S->operands())
12411 Add(Op, Mul);
12412 } else
12413 Add(S, Mul);
12414 };
12415 Decompose(More, 1);
12416 Decompose(Less, -1);
12417
12418 // Check whether all the non-constants cancel out, or reduce to new
12419 // More/Less values.
12420 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12421 for (const auto &[S, Mul] : Multiplicity) {
12422 if (Mul == 0)
12423 continue;
12424 if (Mul == 1) {
12425 if (NewMore)
12426 return std::nullopt;
12427 NewMore = S;
12428 } else if (Mul == -1) {
12429 if (NewLess)
12430 return std::nullopt;
12431 NewLess = S;
12432 } else
12433 return std::nullopt;
12434 }
12435
12436 // Values stayed the same, no point in trying further.
12437 if (NewMore == More || NewLess == Less)
12438 return std::nullopt;
12439
12440 More = NewMore;
12441 Less = NewLess;
12442
12443 // Reduced to constant.
12444 if (!More && !Less)
12445 return Diff;
12446
12447 // Left with variable on only one side, bail out.
12448 if (!More || !Less)
12449 return std::nullopt;
12450 }
12451
12452 // Did not reduce to constant.
12453 return std::nullopt;
12454}
12455
12456bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12457 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12458 const SCEV *FoundRHS, const Instruction *CtxI) {
12459 // Try to recognize the following pattern:
12460 //
12461 // FoundRHS = ...
12462 // ...
12463 // loop:
12464 // FoundLHS = {Start,+,W}
12465 // context_bb: // Basic block from the same loop
12466 // known(Pred, FoundLHS, FoundRHS)
12467 //
12468 // If some predicate is known in the context of a loop, it is also known on
12469 // each iteration of this loop, including the first iteration. Therefore, in
12470 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12471 // prove the original pred using this fact.
12472 if (!CtxI)
12473 return false;
12474 const BasicBlock *ContextBB = CtxI->getParent();
12475 // Make sure AR varies in the context block.
12476 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12477 const Loop *L = AR->getLoop();
12478 const auto *Latch = L->getLoopLatch();
12479 // Make sure that context belongs to the loop and executes on 1st iteration
12480 // (if it ever executes at all).
12481 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12482 return false;
12483 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12484 return false;
12485 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12486 }
12487
12488 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12489 const Loop *L = AR->getLoop();
12490 const auto *Latch = L->getLoopLatch();
12491 // Make sure that context belongs to the loop and executes on 1st iteration
12492 // (if it ever executes at all).
12493 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12494 return false;
12495 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12496 return false;
12497 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12498 }
12499
12500 return false;
12501}
12502
12503bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12504 const SCEV *LHS,
12505 const SCEV *RHS,
12506 const SCEV *FoundLHS,
12507 const SCEV *FoundRHS) {
12508 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12509 return false;
12510
12511 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12512 if (!AddRecLHS)
12513 return false;
12514
12515 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12516 if (!AddRecFoundLHS)
12517 return false;
12518
12519 // We'd like to let SCEV reason about control dependencies, so we constrain
12520 // both the inequalities to be about add recurrences on the same loop. This
12521 // way we can use isLoopEntryGuardedByCond later.
12522
12523 const Loop *L = AddRecFoundLHS->getLoop();
12524 if (L != AddRecLHS->getLoop())
12525 return false;
12526
12527 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12528 //
12529 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12530 // ... (2)
12531 //
12532 // Informal proof for (2), assuming (1) [*]:
12533 //
12534 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12535 //
12536 // Then
12537 //
12538 // FoundLHS s< FoundRHS s< INT_MIN - C
12539 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12540 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12541 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12542 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12543 // <=> FoundLHS + C s< FoundRHS + C
12544 //
12545 // [*]: (1) can be proved by ruling out overflow.
12546 //
12547 // [**]: This can be proved by analyzing all the four possibilities:
12548 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12549 // (A s>= 0, B s>= 0).
12550 //
12551 // Note:
12552 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12553 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12554 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12555 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12556 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12557 // C)".
12558
12559 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12560 if (!LDiff)
12561 return false;
12562 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12563 if (!RDiff || *LDiff != *RDiff)
12564 return false;
12565
12566 if (LDiff->isMinValue())
12567 return true;
12568
12569 APInt FoundRHSLimit;
12570
12571 if (Pred == CmpInst::ICMP_ULT) {
12572 FoundRHSLimit = -(*RDiff);
12573 } else {
12574 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12575 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12576 }
12577
12578 // Try to prove (1) or (2), as needed.
12579 return isAvailableAtLoopEntry(FoundRHS, L) &&
12580 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12581 getConstant(FoundRHSLimit));
12582}
12583
12584bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12585 const SCEV *RHS, const SCEV *FoundLHS,
12586 const SCEV *FoundRHS, unsigned Depth) {
12587 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12588
12589 llvm::scope_exit ClearOnExit([&]() {
12590 if (LPhi) {
12591 bool Erased = PendingMerges.erase(LPhi);
12592 assert(Erased && "Failed to erase LPhi!");
12593 (void)Erased;
12594 }
12595 if (RPhi) {
12596 bool Erased = PendingMerges.erase(RPhi);
12597 assert(Erased && "Failed to erase RPhi!");
12598 (void)Erased;
12599 }
12600 });
12601
12602 // Find respective Phis and check that they are not being pending.
12603 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12604 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12605 if (!PendingMerges.insert(Phi).second)
12606 return false;
12607 LPhi = Phi;
12608 }
12609 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12610 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12611 // If we detect a loop of Phi nodes being processed by this method, for
12612 // example:
12613 //
12614 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12615 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12616 //
12617 // we don't want to deal with a case that complex, so return conservative
12618 // answer false.
12619 if (!PendingMerges.insert(Phi).second)
12620 return false;
12621 RPhi = Phi;
12622 }
12623
12624 // If none of LHS, RHS is a Phi, nothing to do here.
12625 if (!LPhi && !RPhi)
12626 return false;
12627
12628 // If there is a SCEVUnknown Phi we are interested in, make it left.
12629 if (!LPhi) {
12630 std::swap(LHS, RHS);
12631 std::swap(FoundLHS, FoundRHS);
12632 std::swap(LPhi, RPhi);
12634 }
12635
12636 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12637 const BasicBlock *LBB = LPhi->getParent();
12638 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12639
12640 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12641 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12642 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12643 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12644 };
12645
12646 if (RPhi && RPhi->getParent() == LBB) {
12647 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12648 // If we compare two Phis from the same block, and for each entry block
12649 // the predicate is true for incoming values from this block, then the
12650 // predicate is also true for the Phis.
12651 for (const BasicBlock *IncBB : predecessors(LBB)) {
12652 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12653 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12654 if (!ProvedEasily(L, R))
12655 return false;
12656 }
12657 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12658 // Case two: RHS is also a Phi from the same basic block, and it is an
12659 // AddRec. It means that there is a loop which has both AddRec and Unknown
12660 // PHIs, for it we can compare incoming values of AddRec from above the loop
12661 // and latch with their respective incoming values of LPhi.
12662 // TODO: Generalize to handle loops with many inputs in a header.
12663 if (LPhi->getNumIncomingValues() != 2) return false;
12664
12665 auto *RLoop = RAR->getLoop();
12666 auto *Predecessor = RLoop->getLoopPredecessor();
12667 assert(Predecessor && "Loop with AddRec with no predecessor?");
12668 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12669 if (!ProvedEasily(L1, RAR->getStart()))
12670 return false;
12671 auto *Latch = RLoop->getLoopLatch();
12672 assert(Latch && "Loop with AddRec with no latch?");
12673 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12674 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12675 return false;
12676 } else {
12677 // In all other cases go over inputs of LHS and compare each of them to RHS,
12678 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12679 // At this point RHS is either a non-Phi, or it is a Phi from some block
12680 // different from LBB.
12681 for (const BasicBlock *IncBB : predecessors(LBB)) {
12682 // Check that RHS is available in this block.
12683 if (!dominates(RHS, IncBB))
12684 return false;
12685 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12686 // Make sure L does not refer to a value from a potentially previous
12687 // iteration of a loop.
12688 if (!properlyDominates(L, LBB))
12689 return false;
12690 // Addrecs are considered to properly dominate their loop, so are missed
12691 // by the previous check. Discard any values that have computable
12692 // evolution in this loop.
12693 if (auto *Loop = LI.getLoopFor(LBB))
12695 return false;
12696 if (!ProvedEasily(L, RHS))
12697 return false;
12698 }
12699 }
12700 return true;
12701}
12702
12703bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12704 const SCEV *LHS,
12705 const SCEV *RHS,
12706 const SCEV *FoundLHS,
12707 const SCEV *FoundRHS) {
12708 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12709 // sure that we are dealing with same LHS.
12710 if (RHS == FoundRHS) {
12711 std::swap(LHS, RHS);
12712 std::swap(FoundLHS, FoundRHS);
12714 }
12715 if (LHS != FoundLHS)
12716 return false;
12717
12718 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12719 if (!SUFoundRHS)
12720 return false;
12721
12722 Value *Shiftee, *ShiftValue;
12723
12724 using namespace PatternMatch;
12725 if (match(SUFoundRHS->getValue(),
12726 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12727 auto *ShifteeS = getSCEV(Shiftee);
12728 // Prove one of the following:
12729 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12730 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12731 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12732 // ---> LHS <s RHS
12733 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12734 // ---> LHS <=s RHS
12735 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12736 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12737 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12738 if (isKnownNonNegative(ShifteeS))
12739 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12740 }
12741
12742 return false;
12743}
12744
12745bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12746 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12747 const SCEV *FoundRHS) {
12748 // Only valid for equality predicates: (A == B) implies (C == D) when
12749 // the SCEV difference A - B equals C - D (they check the same
12750 // underlying relationship at every iteration).
12751 if (!ICmpInst::isEquality(Pred))
12752 return false;
12753
12754 // Restrict to cases involving loop recurrences - that's where this
12755 // pattern arises (correlated IV comparisons). This avoids calling
12756 // getMinusSCEV on arbitrary non-loop expressions.
12758 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12759 return false;
12760
12761 // AddRecs from different loops can never produce matching differences.
12762 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12763 if (!QueryAddRec)
12764 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12765 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12766 if (!FoundAddRec)
12767 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12768 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12769 return false;
12770
12771 // If the strides differ, the differences can never match.
12772 if (QueryAddRec->getStepRecurrence(*this) !=
12773 FoundAddRec->getStepRecurrence(*this))
12774 return false;
12775
12776 // Compute differences. For pointer-typed operands sharing the same base,
12777 // getMinusSCEV strips the common base and returns an integer SCEV.
12778 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12779 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12780 if (isa<SCEVCouldNotCompute>(FoundDiff))
12781 return false;
12782
12783 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12784 if (isa<SCEVCouldNotCompute>(Diff))
12785 return false;
12786
12787 return Diff == FoundDiff;
12788}
12789
12790bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12791 const SCEV *RHS,
12792 const SCEV *FoundLHS,
12793 const SCEV *FoundRHS,
12794 const Instruction *CtxI) {
12795 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12796 FoundRHS) ||
12797 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12798 FoundRHS) ||
12799 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12800 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12801 CtxI) ||
12802 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12803 FoundRHS) ||
12804 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12805}
12806
12807/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12808template <typename MinMaxExprType>
12809static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12810 const SCEV *Candidate) {
12811 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12812 if (!MinMaxExpr)
12813 return false;
12814
12815 return is_contained(MinMaxExpr->operands(), Candidate);
12816}
12817
12819 CmpPredicate Pred, const SCEV *LHS,
12820 const SCEV *RHS) {
12821 // If both sides are affine addrecs for the same loop, with equal
12822 // steps, and we know the recurrences don't wrap, then we only
12823 // need to check the predicate on the starting values.
12824
12825 if (!ICmpInst::isRelational(Pred))
12826 return false;
12827
12828 const SCEV *LStart, *RStart, *Step;
12829 const Loop *L;
12830 if (!match(LHS,
12831 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12833 m_SpecificLoop(L))))
12834 return false;
12839 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12840 return false;
12841
12842 return SE.isKnownPredicate(Pred, LStart, RStart);
12843}
12844
12845/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12846/// expression?
12848 const SCEV *LHS, const SCEV *RHS) {
12849 switch (Pred) {
12850 default:
12851 return false;
12852
12853 case ICmpInst::ICMP_SGE:
12854 std::swap(LHS, RHS);
12855 [[fallthrough]];
12856 case ICmpInst::ICMP_SLE:
12857 return
12858 // min(A, ...) <= A
12860 // A <= max(A, ...)
12862
12863 case ICmpInst::ICMP_UGE:
12864 std::swap(LHS, RHS);
12865 [[fallthrough]];
12866 case ICmpInst::ICMP_ULE:
12867 return
12868 // min(A, ...) <= A
12869 // FIXME: what about umin_seq?
12871 // A <= max(A, ...)
12873
12874 case ICmpInst::ICMP_UGT:
12875 std::swap(LHS, RHS);
12876 [[fallthrough]];
12877 case ICmpInst::ICMP_ULT:
12878 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12879 // umin(Ops) u< RHS.
12880 //
12881 // Use computeConstantDifference instead of the more powerful
12882 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
12883 // is called from isKnownViaNonRecursiveReasoning, so recursing into
12884 // the full predicate prover would be expensive.
12885 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
12886 for (SCEVUse Op : Min->operands()) {
12887 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
12888 // When Op and RHS share a common base differing by a
12889 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
12890 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
12891 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
12892 return true;
12893 }
12894 }
12895 return false;
12896 }
12897
12898 llvm_unreachable("covered switch fell through?!");
12899}
12900
12901bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
12902 const SCEV *RHS,
12903 const SCEV *FoundLHS,
12904 const SCEV *FoundRHS,
12905 unsigned Depth) {
12908 "LHS and RHS have different sizes?");
12909 assert(getTypeSizeInBits(FoundLHS->getType()) ==
12910 getTypeSizeInBits(FoundRHS->getType()) &&
12911 "FoundLHS and FoundRHS have different sizes?");
12912 // We want to avoid hurting the compile time with analysis of too big trees.
12914 return false;
12915
12916 // We only want to work with GT comparison so far.
12917 if (ICmpInst::isLT(Pred)) {
12919 std::swap(LHS, RHS);
12920 std::swap(FoundLHS, FoundRHS);
12921 }
12922
12924
12925 // For unsigned, try to reduce it to corresponding signed comparison.
12926 if (P == ICmpInst::ICMP_UGT)
12927 // We can replace unsigned predicate with its signed counterpart if all
12928 // involved values are non-negative.
12929 // TODO: We could have better support for unsigned.
12930 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
12931 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
12932 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
12933 // use this fact to prove that LHS and RHS are non-negative.
12934 const SCEV *MinusOne = getMinusOne(LHS->getType());
12935 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
12936 FoundRHS) &&
12937 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
12938 FoundRHS))
12940 }
12941
12942 if (P != ICmpInst::ICMP_SGT)
12943 return false;
12944
12945 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
12946 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
12947 return Ext->getOperand();
12948 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
12949 // the constant in some cases.
12950 return S;
12951 };
12952
12953 // Acquire values from extensions.
12954 auto *OrigLHS = LHS;
12955 auto *OrigFoundLHS = FoundLHS;
12956 LHS = GetOpFromSExt(LHS);
12957 FoundLHS = GetOpFromSExt(FoundLHS);
12958
12959 // Is the SGT predicate can be proved trivially or using the found context.
12960 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
12961 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
12962 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
12963 FoundRHS, Depth + 1);
12964 };
12965
12966 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
12967 // We want to avoid creation of any new non-constant SCEV. Since we are
12968 // going to compare the operands to RHS, we should be certain that we don't
12969 // need any size extensions for this. So let's decline all cases when the
12970 // sizes of types of LHS and RHS do not match.
12971 // TODO: Maybe try to get RHS from sext to catch more cases?
12973 return false;
12974
12975 // Should not overflow.
12976 if (!LHSAddExpr->hasNoSignedWrap())
12977 return false;
12978
12979 SCEVUse LL = LHSAddExpr->getOperand(0);
12980 SCEVUse LR = LHSAddExpr->getOperand(1);
12981 auto *MinusOne = getMinusOne(RHS->getType());
12982
12983 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
12984 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
12985 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
12986 };
12987 // Try to prove the following rule:
12988 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
12989 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
12990 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
12991 return true;
12992 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
12993 Value *LL, *LR;
12994 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
12995
12996 using namespace llvm::PatternMatch;
12997
12998 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
12999 // Rules for division.
13000 // We are going to perform some comparisons with Denominator and its
13001 // derivative expressions. In general case, creating a SCEV for it may
13002 // lead to a complex analysis of the entire graph, and in particular it
13003 // can request trip count recalculation for the same loop. This would
13004 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13005 // this, we only want to create SCEVs that are constants in this section.
13006 // So we bail if Denominator is not a constant.
13007 if (!isa<ConstantInt>(LR))
13008 return false;
13009
13010 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13011
13012 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13013 // then a SCEV for the numerator already exists and matches with FoundLHS.
13014 auto *Numerator = getExistingSCEV(LL);
13015 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13016 return false;
13017
13018 // Make sure that the numerator matches with FoundLHS and the denominator
13019 // is positive.
13020 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13021 return false;
13022
13023 auto *DTy = Denominator->getType();
13024 auto *FRHSTy = FoundRHS->getType();
13025 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13026 // One of types is a pointer and another one is not. We cannot extend
13027 // them properly to a wider type, so let us just reject this case.
13028 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13029 // to avoid this check.
13030 return false;
13031
13032 // Given that:
13033 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13034 auto *WTy = getWiderType(DTy, FRHSTy);
13035 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13036 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13037
13038 // Try to prove the following rule:
13039 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13040 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13041 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13042 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13043 if (isKnownNonPositive(RHS) &&
13044 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13045 return true;
13046
13047 // Try to prove the following rule:
13048 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13049 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13050 // If we divide it by Denominator > 2, then:
13051 // 1. If FoundLHS is negative, then the result is 0.
13052 // 2. If FoundLHS is non-negative, then the result is non-negative.
13053 // Anyways, the result is non-negative.
13054 auto *MinusOne = getMinusOne(WTy);
13055 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13056 if (isKnownNegative(RHS) &&
13057 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13058 return true;
13059 }
13060 }
13061
13062 // If our expression contained SCEVUnknown Phis, and we split it down and now
13063 // need to prove something for them, try to prove the predicate for every
13064 // possible incoming values of those Phis.
13065 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13066 return true;
13067
13068 return false;
13069}
13070
13072 const SCEV *RHS) {
13073 // zext x u<= sext x, sext x s<= zext x
13074 const SCEV *Op;
13075 switch (Pred) {
13076 case ICmpInst::ICMP_SGE:
13077 std::swap(LHS, RHS);
13078 [[fallthrough]];
13079 case ICmpInst::ICMP_SLE: {
13080 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13081 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13083 }
13084 case ICmpInst::ICMP_UGE:
13085 std::swap(LHS, RHS);
13086 [[fallthrough]];
13087 case ICmpInst::ICMP_ULE: {
13088 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13089 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13091 }
13092 default:
13093 return false;
13094 };
13095 llvm_unreachable("unhandled case");
13096}
13097
13098bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13099 SCEVUse LHS,
13100 SCEVUse RHS) {
13101 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13102 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13103 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13104 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13105 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13106}
13107
13108bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13109 const SCEV *LHS,
13110 const SCEV *RHS,
13111 const SCEV *FoundLHS,
13112 const SCEV *FoundRHS) {
13113 switch (Pred) {
13114 default:
13115 llvm_unreachable("Unexpected CmpPredicate value!");
13116 case ICmpInst::ICMP_EQ:
13117 case ICmpInst::ICMP_NE:
13118 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13119 return true;
13120 break;
13121 case ICmpInst::ICMP_SLT:
13122 case ICmpInst::ICMP_SLE:
13123 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13124 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13125 return true;
13126 break;
13127 case ICmpInst::ICMP_SGT:
13128 case ICmpInst::ICMP_SGE:
13129 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13130 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13131 return true;
13132 break;
13133 case ICmpInst::ICMP_ULT:
13134 case ICmpInst::ICMP_ULE:
13135 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13136 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13137 return true;
13138 break;
13139 case ICmpInst::ICMP_UGT:
13140 case ICmpInst::ICMP_UGE:
13141 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13142 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13143 return true;
13144 break;
13145 }
13146
13147 // Maybe it can be proved via operations?
13148 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13149 return true;
13150
13151 return false;
13152}
13153
13154bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13155 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13156 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13157 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13158 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13159 // reduce the compile time impact of this optimization.
13160 return false;
13161
13162 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13163 if (!Addend)
13164 return false;
13165
13166 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13167
13168 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13169 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13170 ConstantRange FoundLHSRange =
13171 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13172
13173 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13174 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13175
13176 // We can also compute the range of values for `LHS` that satisfy the
13177 // consequent, "`LHS` `Pred` `RHS`":
13178 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13179 // The antecedent implies the consequent if every value of `LHS` that
13180 // satisfies the antecedent also satisfies the consequent.
13181 return LHSRange.icmp(Pred, ConstRHS);
13182}
13183
13184bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13185 bool IsSigned) {
13186 assert(isKnownPositive(Stride) && "Positive stride expected!");
13187
13188 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13189 const SCEV *One = getOne(Stride->getType());
13190
13191 if (IsSigned) {
13192 APInt MaxRHS = getSignedRangeMax(RHS);
13193 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13194 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13195
13196 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13197 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13198 }
13199
13200 APInt MaxRHS = getUnsignedRangeMax(RHS);
13201 APInt MaxValue = APInt::getMaxValue(BitWidth);
13202 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13203
13204 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13205 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13206}
13207
13208bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13209 bool IsSigned) {
13210
13211 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13212 const SCEV *One = getOne(Stride->getType());
13213
13214 if (IsSigned) {
13215 APInt MinRHS = getSignedRangeMin(RHS);
13216 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13217 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13218
13219 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13220 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13221 }
13222
13223 APInt MinRHS = getUnsignedRangeMin(RHS);
13224 APInt MinValue = APInt::getMinValue(BitWidth);
13225 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13226
13227 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13228 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13229}
13230
13232 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13233 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13234 // expression fixes the case of N=0.
13235 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13236 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13237 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13238}
13239
13240const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13241 const SCEV *Stride,
13242 const SCEV *End,
13243 unsigned BitWidth,
13244 bool IsSigned) {
13245 // The logic in this function assumes we can represent a positive stride.
13246 // If we can't, the backedge-taken count must be zero.
13247 if (IsSigned && BitWidth == 1)
13248 return getZero(Stride->getType());
13249
13250 // This code below only been closely audited for negative strides in the
13251 // unsigned comparison case, it may be correct for signed comparison, but
13252 // that needs to be established.
13253 if (IsSigned && isKnownNegative(Stride))
13254 return getCouldNotCompute();
13255
13256 // Calculate the maximum backedge count based on the range of values
13257 // permitted by Start, End, and Stride.
13258 APInt MinStart =
13259 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13260
13261 APInt MinStride =
13262 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13263
13264 // We assume either the stride is positive, or the backedge-taken count
13265 // is zero. So force StrideForMaxBECount to be at least one.
13266 APInt One(BitWidth, 1);
13267 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13268 : APIntOps::umax(One, MinStride);
13269
13270 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13271 : APInt::getMaxValue(BitWidth);
13272 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13273
13274 // Although End can be a MAX expression we estimate MaxEnd considering only
13275 // the case End = RHS of the loop termination condition. This is safe because
13276 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13277 // taken count.
13278 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13279 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13280
13281 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13282 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13283 : APIntOps::umax(MaxEnd, MinStart);
13284
13285 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13286 getConstant(StrideForMaxBECount) /* Step */);
13287}
13288
13290ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13291 const Loop *L, bool IsSigned,
13292 bool ControlsOnlyExit, bool AllowPredicates) {
13294
13296 bool PredicatedIV = false;
13297 if (!IV) {
13298 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13299 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13300 if (AR && AR->getLoop() == L && AR->isAffine()) {
13301 auto canProveNUW = [&]() {
13302 // We can use the comparison to infer no-wrap flags only if it fully
13303 // controls the loop exit.
13304 if (!ControlsOnlyExit)
13305 return false;
13306
13307 if (!isLoopInvariant(RHS, L))
13308 return false;
13309
13310 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13311 // We need the sequence defined by AR to strictly increase in the
13312 // unsigned integer domain for the logic below to hold.
13313 return false;
13314
13315 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13316 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13317 // If RHS <=u Limit, then there must exist a value V in the sequence
13318 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13319 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13320 // overflow occurs. This limit also implies that a signed comparison
13321 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13322 // the high bits on both sides must be zero.
13323 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13324 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13325 Limit = Limit.zext(OuterBitWidth);
13326 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13327 };
13328 auto Flags = AR->getNoWrapFlags();
13329 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13330 Flags = setFlags(Flags, SCEV::FlagNUW);
13331
13332 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13333 if (AR->hasNoUnsignedWrap()) {
13334 // Emulate what getZeroExtendExpr would have done during construction
13335 // if we'd been able to infer the fact just above at that time.
13336 const SCEV *Step = AR->getStepRecurrence(*this);
13337 Type *Ty = ZExt->getType();
13338 auto *S = getAddRecExpr(
13340 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13342 }
13343 }
13344 }
13345 }
13346
13347
13348 if (!IV && AllowPredicates) {
13349 // Try to make this an AddRec using runtime tests, in the first X
13350 // iterations of this loop, where X is the SCEV expression found by the
13351 // algorithm below.
13352 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13353 PredicatedIV = true;
13354 }
13355
13356 // Avoid weird loops
13357 if (!IV || IV->getLoop() != L || !IV->isAffine())
13358 return getCouldNotCompute();
13359
13360 // A precondition of this method is that the condition being analyzed
13361 // reaches an exiting branch which dominates the latch. Given that, we can
13362 // assume that an increment which violates the nowrap specification and
13363 // produces poison must cause undefined behavior when the resulting poison
13364 // value is branched upon and thus we can conclude that the backedge is
13365 // taken no more often than would be required to produce that poison value.
13366 // Note that a well defined loop can exit on the iteration which violates
13367 // the nowrap specification if there is another exit (either explicit or
13368 // implicit/exceptional) which causes the loop to execute before the
13369 // exiting instruction we're analyzing would trigger UB.
13370 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13371 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13373
13374 const SCEV *Stride = IV->getStepRecurrence(*this);
13375
13376 bool PositiveStride = isKnownPositive(Stride);
13377
13378 // Whether the IV may reach the maximum value before the exit is taken.
13379 bool IVMayOverflow = true;
13380
13381 // Avoid negative or zero stride values.
13382 if (!PositiveStride) {
13383 // We can compute the correct backedge taken count for loops with unknown
13384 // strides if we can prove that the loop is not an infinite loop with side
13385 // effects. Here's the loop structure we are trying to handle -
13386 //
13387 // i = start
13388 // do {
13389 // A[i] = i;
13390 // i += s;
13391 // } while (i < end);
13392 //
13393 // The backedge taken count for such loops is evaluated as -
13394 // (max(end, start + stride) - start - 1) /u stride
13395 //
13396 // The additional preconditions that we need to check to prove correctness
13397 // of the above formula is as follows -
13398 //
13399 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13400 // NoWrap flag).
13401 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13402 // no side effects within the loop)
13403 // c) loop has a single static exit (with no abnormal exits)
13404 //
13405 // Precondition a) implies that if the stride is negative, this is a single
13406 // trip loop. The backedge taken count formula reduces to zero in this case.
13407 //
13408 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13409 // then a zero stride means the backedge can't be taken without executing
13410 // undefined behavior.
13411 //
13412 // The positive stride case is the same as isKnownPositive(Stride) returning
13413 // true (original behavior of the function).
13414 //
13415 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13417 return getCouldNotCompute();
13418
13419 if (!isKnownNonZero(Stride)) {
13420 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13421 // if it might eventually be greater than start and if so, on which
13422 // iteration. We can't even produce a useful upper bound.
13423 if (!isLoopInvariant(RHS, L))
13424 return getCouldNotCompute();
13425
13426 // We allow a potentially zero stride, but we need to divide by stride
13427 // below. Since the loop can't be infinite and this check must control
13428 // the sole exit, we can infer the exit must be taken on the first
13429 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13430 // we know the numerator in the divides below must be zero, so we can
13431 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13432 // and produce the right result.
13433 // FIXME: Handle the case where Stride is poison?
13434 auto wouldZeroStrideBeUB = [&]() {
13435 // Proof by contradiction. Suppose the stride were zero. If we can
13436 // prove that the backedge *is* taken on the first iteration, then since
13437 // we know this condition controls the sole exit, we must have an
13438 // infinite loop. We can't have a (well defined) infinite loop per
13439 // check just above.
13440 // Note: The (Start - Stride) term is used to get the start' term from
13441 // (start' + stride,+,stride). Remember that we only care about the
13442 // result of this expression when stride == 0 at runtime.
13443 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13444 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13445 };
13446 if (!wouldZeroStrideBeUB()) {
13447 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13448 }
13449 }
13450 } else {
13451 // Avoid proven overflow cases: this will ensure that the backedge taken
13452 // count will not generate any unsigned overflow.
13453 IVMayOverflow = canIVOverflowOnLT(RHS, Stride, IsSigned);
13454 if (IVMayOverflow && !NoWrap)
13455 return getCouldNotCompute();
13456 }
13457
13458 // On all paths just preceeding, we established the following invariant:
13459 // IV can be assumed not to overflow up to and including the exiting
13460 // iteration. We proved this in one of two ways:
13461 // 1) We can show overflow doesn't occur before the exiting iteration
13462 // 1a) canIVOverflowOnLT, and b) step of one
13463 // 2) We can show that if overflow occurs, the loop must execute UB
13464 // before any possible exit.
13465 // Note that we have not yet proved RHS invariant (in general).
13466
13467 const SCEV *Start = IV->getStart();
13468
13469 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13470 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13471 // Use integer-typed versions for actual computation; we can't subtract
13472 // pointers in general.
13473 const SCEV *OrigStart = Start;
13474 const SCEV *OrigRHS = RHS;
13475 if (Start->getType()->isPointerTy()) {
13476 Start = getPtrToAddrExpr(Start);
13477 if (isa<SCEVCouldNotCompute>(Start))
13478 return Start;
13479 }
13480 if (RHS->getType()->isPointerTy()) {
13483 return RHS;
13484 }
13485
13486 const SCEV *End = nullptr, *BECount = nullptr,
13487 *BECountIfBackedgeTaken = nullptr;
13488 if (!isLoopInvariant(RHS, L)) {
13489 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13490 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13491 any(RHSAddRec->getNoWrapFlags())) {
13492 // The structure of loop we are trying to calculate backedge count of:
13493 //
13494 // left = left_start
13495 // right = right_start
13496 //
13497 // while(left < right){
13498 // ... do something here ...
13499 // left += s1; // stride of left is s1 (s1 > 0)
13500 // right += s2; // stride of right is s2 (s2 < 0)
13501 // }
13502 //
13503
13504 const SCEV *RHSStart = RHSAddRec->getStart();
13505 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13506
13507 // If Stride - RHSStride is positive and does not overflow, we can write
13508 // backedge count as ->
13509 // ceil((End - Start) /u (Stride - RHSStride))
13510 // Where, End = max(RHSStart, Start)
13511
13512 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13513 if (isKnownNegative(RHSStride) &&
13514 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13515 RHSStride)) {
13516
13517 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13518 if (isKnownPositive(Denominator)) {
13519 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13520 : getUMaxExpr(RHSStart, Start);
13521
13522 // We can do this because End >= Start, as End = max(RHSStart, Start)
13523 const SCEV *Delta = getMinusSCEV(End, Start);
13524
13525 BECount = getUDivCeilSCEV(Delta, Denominator);
13526 BECountIfBackedgeTaken =
13527 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13528 }
13529 }
13530 }
13531 if (BECount == nullptr) {
13532 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13533 // given the start, stride and max value for the end bound of the
13534 // loop (RHS), and the fact that IV does not overflow (which is
13535 // checked above).
13536 const SCEV *MaxBECount = computeMaxBECountForLT(
13537 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13538 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13539 MaxBECount, false /*MaxOrZero*/, Predicates);
13540 }
13541 } else {
13542 // We use the expression (max(End,Start)-Start)/Stride to describe the
13543 // backedge count, as if the backedge is taken at least once
13544 // max(End,Start) is End and so the result is as above, and if not
13545 // max(End,Start) is Start so we get a backedge count of zero.
13546 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13547 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13548 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13549 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13550 // Can we prove (max(RHS,Start) > Start - Stride?
13551 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13552 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13553 // In this case, we can use a refined formula for computing backedge
13554 // taken count. The general formula remains:
13555 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13556 // We want to use the alternate formula:
13557 // "((End - 1) - (Start - Stride)) /u Stride"
13558 // Let's do a quick case analysis to show these are equivalent under
13559 // our precondition that max(RHS,Start) > Start - Stride.
13560 // * For RHS <= Start, the backedge-taken count must be zero.
13561 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13562 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13563 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13564 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13565 // reducing this to the stride of 1 case.
13566 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13567 // Stride".
13568 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13569 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13570 // "((RHS - (Start - Stride) - 1) /u Stride".
13571 // Our preconditions trivially imply no overflow in that form.
13572 const SCEV *MinusOne = getMinusOne(Stride->getType());
13573 const SCEV *Numerator =
13574 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13575 BECount = getUDivExpr(Numerator, Stride);
13576 }
13577
13578 if (!BECount) {
13579 auto canProveRHSGreaterThanEqualStart = [&]() {
13580 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13581 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13582 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13583
13584 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13585 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13586 return true;
13587
13588 // (RHS > Start - 1) implies RHS >= Start.
13589 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13590 // "Start - 1" doesn't overflow.
13591 // * For signed comparison, if Start - 1 does overflow, it's equal
13592 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13593 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13594 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13595 //
13596 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13597 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13598 auto *StartMinusOne =
13599 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13600 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13601 };
13602
13603 // If we know that RHS >= Start in the context of loop, then we know
13604 // that max(RHS, Start) = RHS at this point.
13605 if (canProveRHSGreaterThanEqualStart()) {
13606 End = RHS;
13607 } else {
13608 // If RHS < Start, the backedge will be taken zero times. So in
13609 // general, we can write the backedge-taken count as:
13610 //
13611 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13612 //
13613 // We convert it to the following to make it more convenient for SCEV:
13614 //
13615 // ceil(max(RHS, Start) - Start) / Stride
13616 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13617
13618 // See what would happen if we assume the backedge is taken. This is
13619 // used to compute MaxBECount.
13620 BECountIfBackedgeTaken =
13621 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13622 }
13623
13624 // At this point, we know:
13625 //
13626 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13627 // 2. The index variable doesn't overflow.
13628 //
13629 // Therefore, we know N exists such that
13630 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13631 // doesn't overflow.
13632 //
13633 // Using this information, try to prove whether the addition in
13634 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13635 //
13636 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13637 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13638 // the (Stride - 1) addition below cannot overflow.
13639 const SCEV *One = getOne(Stride->getType());
13640 bool MayAddOverflow = IVMayOverflow && [&] {
13641 if (isKnownToBeAPowerOfTwo(Stride)) {
13642 // Suppose Stride is a power of two, and Start/End are unsigned
13643 // integers. Let UMAX be the largest representable unsigned
13644 // integer.
13645 //
13646 // By the preconditions of this function, we know
13647 // "(Start + Stride * N) >= End", and this doesn't overflow.
13648 // As a formula:
13649 //
13650 // End <= (Start + Stride * N) <= UMAX
13651 //
13652 // Subtracting Start from all the terms:
13653 //
13654 // End - Start <= Stride * N <= UMAX - Start
13655 //
13656 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13657 //
13658 // End - Start <= Stride * N <= UMAX
13659 //
13660 // Stride * N is a multiple of Stride. Therefore,
13661 //
13662 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13663 //
13664 // Since Stride is a power of two, UMAX + 1 is divisible by
13665 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13666 // write:
13667 //
13668 // End - Start <= Stride * N <= UMAX - Stride - 1
13669 //
13670 // Dropping the middle term:
13671 //
13672 // End - Start <= UMAX - Stride - 1
13673 //
13674 // Adding Stride - 1 to both sides:
13675 //
13676 // (End - Start) + (Stride - 1) <= UMAX
13677 //
13678 // In other words, the addition doesn't have unsigned overflow.
13679 //
13680 // A similar proof works if we treat Start/End as signed values.
13681 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13682 // to use signed max instead of unsigned max. Note that we're
13683 // trying to prove a lack of unsigned overflow in either case.
13684 return false;
13685 }
13686 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13687 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13688 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13689 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13690 // 1 <s End.
13691 //
13692 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13693 // End.
13694 return false;
13695 }
13696 return true;
13697 }();
13698
13699 const SCEV *Delta = getMinusSCEV(End, Start);
13700 if (!MayAddOverflow) {
13701 // floor((D + (S - 1)) / S)
13702 // We prefer this formulation if it's legal because it's fewer
13703 // operations.
13704 BECount =
13705 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13706 } else {
13707 BECount = getUDivCeilSCEV(Delta, Stride);
13708 }
13709 }
13710 }
13711
13712 const SCEV *ConstantMaxBECount;
13713 bool MaxOrZero = false;
13714 if (isa<SCEVConstant>(BECount)) {
13715 ConstantMaxBECount = BECount;
13716 } else if (BECountIfBackedgeTaken &&
13717 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13718 // If we know exactly how many times the backedge will be taken if it's
13719 // taken at least once, then the backedge count will either be that or
13720 // zero.
13721 ConstantMaxBECount = BECountIfBackedgeTaken;
13722 MaxOrZero = true;
13723 } else {
13724 ConstantMaxBECount = computeMaxBECountForLT(
13725 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13726 }
13727
13728 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13729 !isa<SCEVCouldNotCompute>(BECount))
13730 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13731
13732 const SCEV *SymbolicMaxBECount =
13733 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13734 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13735 Predicates);
13736}
13737
13738ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13739 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13740 bool ControlsOnlyExit, bool AllowPredicates) {
13742 // We handle only IV > Invariant
13743 if (!isLoopInvariant(RHS, L))
13744 return getCouldNotCompute();
13745
13746 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13747 if (!IV && AllowPredicates)
13748 // Try to make this an AddRec using runtime tests, in the first X
13749 // iterations of this loop, where X is the SCEV expression found by the
13750 // algorithm below.
13751 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13752
13753 // Avoid weird loops
13754 if (!IV || IV->getLoop() != L || !IV->isAffine())
13755 return getCouldNotCompute();
13756
13757 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13758 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13760
13761 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13762
13763 // Avoid negative or zero stride values
13764 if (!isKnownPositive(Stride))
13765 return getCouldNotCompute();
13766
13767 // Avoid proven overflow cases: this will ensure that the backedge taken count
13768 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13769 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13770 // behaviors like the case of C language.
13771 bool MayAddOverflow = false;
13772 const SCEV *Start = IV->getStart();
13773 const SCEV *End = RHS;
13774 if (!Stride->isOne() && canIVOverflowOnGT(RHS, Stride, IsSigned)) {
13775 if (!NoWrap)
13776 return getCouldNotCompute();
13777 MayAddOverflow = true;
13778 }
13779
13780 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13781 // If we know that Start >= RHS in the context of loop, then we know that
13782 // min(RHS, Start) = RHS at this point.
13784 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13785 End = RHS;
13786 else
13787 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13788 }
13789
13790 if (Start->getType()->isPointerTy()) {
13791 Start = getPtrToAddrExpr(Start);
13792 if (isa<SCEVCouldNotCompute>(Start))
13793 return Start;
13794 }
13795 if (End->getType()->isPointerTy()) {
13796 End = getPtrToAddrExpr(End);
13797 if (isa<SCEVCouldNotCompute>(End))
13798 return End;
13799 }
13800
13801 const SCEV *Delta = getMinusSCEV(Start, End);
13802 const SCEV *BECount;
13803 if (MayAddOverflow) {
13804 // The ceiling division instead needs Start >= End, so that (Start - End) is
13805 // the exact unsigned distance between them.
13807 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, End))
13808 return getCouldNotCompute();
13809 BECount = getUDivCeilSCEV(Delta, Stride);
13810 } else {
13811 // Compute ((Start - End) + (Stride - 1)) / Stride, if the IV cannot
13812 // overflow as it requires fewer operations.
13813 const SCEV *One = getOne(Stride->getType());
13814 BECount = getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13815 }
13816
13817 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13819
13820 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13821 : getUnsignedRangeMin(Stride);
13822
13823 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13824 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13825 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13826
13827 // Although End can be a MIN expression we estimate MinEnd considering only
13828 // the case End = RHS. This is safe because in the other case (Start - End)
13829 // is zero, leading to a zero maximum backedge taken count.
13830 APInt MinEnd =
13831 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13832 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13833
13834 const SCEV *ConstantMaxBECount =
13835 isa<SCEVConstant>(BECount)
13836 ? BECount
13837 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13838 getConstant(MinStride));
13839
13840 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13841 ConstantMaxBECount = BECount;
13842 const SCEV *SymbolicMaxBECount =
13843 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13844
13845 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13846 Predicates);
13847}
13848
13850 ScalarEvolution &SE) const {
13851 if (Range.isFullSet()) // Infinite loop.
13852 return SE.getCouldNotCompute();
13853
13854 // If the start is a non-zero constant, shift the range to simplify things.
13855 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13856 if (!SC->getValue()->isZero()) {
13858 Operands[0] = SE.getZero(SC->getType());
13859 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13861 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13862 return ShiftedAddRec->getNumIterationsInRange(
13863 Range.subtract(SC->getAPInt()), SE);
13864 // This is strange and shouldn't happen.
13865 return SE.getCouldNotCompute();
13866 }
13867
13868 // The only time we can solve this is when we have all constant indices.
13869 // Otherwise, we cannot determine the overflow conditions.
13870 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
13871 return SE.getCouldNotCompute();
13872
13873 // Okay at this point we know that all elements of the chrec are constants and
13874 // that the start element is zero.
13875
13876 // First check to see if the range contains zero. If not, the first
13877 // iteration exits.
13878 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13879 if (!Range.contains(APInt(BitWidth, 0)))
13880 return SE.getZero(getType());
13881
13882 if (isAffine()) {
13883 // If this is an affine expression then we have this situation:
13884 // Solve {0,+,A} in Range === Ax in Range
13885
13886 // We know that zero is in the range. If A is positive then we know that
13887 // the upper value of the range must be the first possible exit value.
13888 // If A is negative then the lower of the range is the last possible loop
13889 // value. Also note that we already checked for a full range.
13890 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13891 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13892
13893 // The exit value should be (End+A)/A.
13894 APInt ExitVal = (End + A).udiv(A);
13895 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13896
13897 // Evaluate at the exit value. If we really did fall out of the valid
13898 // range, then we computed our trip count, otherwise wrap around or other
13899 // things must have happened.
13900 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13901 if (Range.contains(Val->getValue()))
13902 return SE.getCouldNotCompute(); // Something strange happened
13903
13904 // Ensure that the previous value is in the range.
13905 assert(Range.contains(
13907 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13908 "Linear scev computation is off in a bad way!");
13909 return SE.getConstant(ExitValue);
13910 }
13911
13912 if (isQuadratic()) {
13913 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13914 return SE.getConstant(*S);
13915 }
13916
13917 return SE.getCouldNotCompute();
13918}
13919
13920const SCEVAddRecExpr *
13922 assert(getNumOperands() > 1 && "AddRec with zero step?");
13923 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13924 // but in this case we cannot guarantee that the value returned will be an
13925 // AddRec because SCEV does not have a fixed point where it stops
13926 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13927 // may happen if we reach arithmetic depth limit while simplifying. So we
13928 // construct the returned value explicitly.
13930 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13931 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13932 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13933 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13934 // We know that the last operand is not a constant zero (otherwise it would
13935 // have been popped out earlier). This guarantees us that if the result has
13936 // the same last operand, then it will also not be popped out, meaning that
13937 // the returned value will be an AddRec.
13938 const SCEV *Last = getOperand(getNumOperands() - 1);
13939 assert(!Last->isZero() && "Recurrency with zero step?");
13940 Ops.push_back(Last);
13943}
13944
13945// Return true when S contains at least an undef value.
13947 return SCEVExprContains(
13948 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
13949}
13950
13951// Return true when S contains a value that is a nullptr.
13953 return SCEVExprContains(S, [](const SCEV *S) {
13954 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
13955 return SU->getValue() == nullptr;
13956 return false;
13957 });
13958}
13959
13960/// Return the size of an element read or written by Inst.
13962 Type *Ty;
13963 Type *PtrTy;
13964 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
13965 Ty = Store->getValueOperand()->getType();
13966 PtrTy = Store->getPointerOperandType();
13967 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
13968 Ty = Load->getType();
13969 PtrTy = Load->getPointerOperandType();
13970 } else {
13971 return nullptr;
13972 }
13973
13974 Type *ETy = getEffectiveSCEVType(PtrTy);
13975 return getSizeOfExpr(ETy, Ty);
13976}
13977
13978//===----------------------------------------------------------------------===//
13979// SCEVCallbackVH Class Implementation
13980//===----------------------------------------------------------------------===//
13981
13983 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13984 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
13985 SE->ConstantEvolutionLoopExitValue.erase(PN);
13986 SE->eraseValueFromMap(getValPtr());
13987 // this now dangles!
13988}
13989
13990void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
13991 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
13992
13993 // Forget all the expressions associated with users of the old value,
13994 // so that future queries will recompute the expressions using the new
13995 // value.
13996 SE->forgetValue(getValPtr());
13997 // this now dangles!
13998}
13999
14000ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14001 : CallbackVH(V), SE(se) {}
14002
14003//===----------------------------------------------------------------------===//
14004// ScalarEvolution Class Implementation
14005//===----------------------------------------------------------------------===//
14006
14009 LoopInfo &LI)
14010 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14011 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14012 LoopDispositions(64), BlockDispositions(64) {
14013 // To use guards for proving predicates, we need to scan every instruction in
14014 // relevant basic blocks, and not just terminators. Doing this is a waste of
14015 // time if the IR does not actually contain any calls to
14016 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14017 //
14018 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14019 // to _add_ guards to the module when there weren't any before, and wants
14020 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14021 // efficient in lieu of being smart in that rather obscure case.
14022
14023 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14024 F.getParent(), Intrinsic::experimental_guard);
14025 HasGuards = GuardDecl && !GuardDecl->use_empty();
14026}
14027
14029 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14030 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14031 ValueExprMap(std::move(Arg.ValueExprMap)),
14032 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14033 PendingMerges(std::move(Arg.PendingMerges)),
14034 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14035 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14036 PredicatedBackedgeTakenCounts(
14037 std::move(Arg.PredicatedBackedgeTakenCounts)),
14038 BECountUsers(std::move(Arg.BECountUsers)),
14039 ConstantEvolutionLoopExitValue(
14040 std::move(Arg.ConstantEvolutionLoopExitValue)),
14041 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14042 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14043 LoopDispositions(std::move(Arg.LoopDispositions)),
14044 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14045 BlockDispositions(std::move(Arg.BlockDispositions)),
14046 SCEVUsers(std::move(Arg.SCEVUsers)),
14047 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14048 SignedRanges(std::move(Arg.SignedRanges)),
14049 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14050 UniquePreds(std::move(Arg.UniquePreds)),
14051 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14052 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14053 LoopUsers(std::move(Arg.LoopUsers)),
14054 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14055 FirstUnknown(Arg.FirstUnknown) {
14056 Arg.FirstUnknown = nullptr;
14057}
14058
14060 // Iterate through all the SCEVUnknown instances and call their
14061 // destructors, so that they release their references to their values.
14062 for (SCEVUnknown *U = FirstUnknown; U;) {
14063 SCEVUnknown *Tmp = U;
14064 U = U->Next;
14065 Tmp->~SCEVUnknown();
14066 }
14067 FirstUnknown = nullptr;
14068
14069 ExprValueMap.clear();
14070 ValueExprMap.clear();
14071 HasRecMap.clear();
14072 BackedgeTakenCounts.clear();
14073 PredicatedBackedgeTakenCounts.clear();
14074
14075 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14076 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14077 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14078 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14079}
14080
14084
14085/// When printing a top-level SCEV for trip counts, it's helpful to include
14086/// a type for constants which are otherwise hard to disambiguate.
14087static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14088 if (isa<SCEVConstant>(S))
14089 OS << *S->getType() << " ";
14090 OS << *S;
14091}
14092
14094 const Loop *L) {
14095 // Print all inner loops first
14096 for (Loop *I : *L)
14097 PrintLoopInfo(OS, SE, I);
14098
14099 OS << "Loop ";
14100 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14101 OS << ": ";
14102
14103 SmallVector<BasicBlock *, 8> ExitingBlocks;
14104 L->getExitingBlocks(ExitingBlocks);
14105 if (ExitingBlocks.size() != 1)
14106 OS << "<multiple exits> ";
14107
14108 auto *BTC = SE->getBackedgeTakenCount(L);
14109 if (!isa<SCEVCouldNotCompute>(BTC)) {
14110 OS << "backedge-taken count is ";
14111 PrintSCEVWithTypeHint(OS, BTC);
14112 } else
14113 OS << "Unpredictable backedge-taken count.";
14114 OS << "\n";
14115
14116 if (ExitingBlocks.size() > 1)
14117 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14118 OS << " exit count for " << ExitingBlock->getName() << ": ";
14119 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14120 PrintSCEVWithTypeHint(OS, EC);
14121 if (isa<SCEVCouldNotCompute>(EC)) {
14122 // Retry with predicates.
14124 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14125 if (!isa<SCEVCouldNotCompute>(EC)) {
14126 OS << "\n predicated exit count for " << ExitingBlock->getName()
14127 << ": ";
14128 PrintSCEVWithTypeHint(OS, EC);
14129 OS << "\n Predicates:\n";
14130 for (const auto *P : Predicates)
14131 P->print(OS, 4);
14132 }
14133 }
14134 OS << "\n";
14135 }
14136
14137 OS << "Loop ";
14138 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14139 OS << ": ";
14140
14141 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14142 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14143 OS << "constant max backedge-taken count is ";
14144 PrintSCEVWithTypeHint(OS, ConstantBTC);
14146 OS << ", actual taken count either this or zero.";
14147 } else {
14148 OS << "Unpredictable constant max backedge-taken count. ";
14149 }
14150
14151 OS << "\n"
14152 "Loop ";
14153 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14154 OS << ": ";
14155
14156 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14157 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14158 OS << "symbolic max backedge-taken count is ";
14159 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14161 OS << ", actual taken count either this or zero.";
14162 } else {
14163 OS << "Unpredictable symbolic max backedge-taken count. ";
14164 }
14165 OS << "\n";
14166
14167 if (ExitingBlocks.size() > 1)
14168 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14169 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14170 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14172 PrintSCEVWithTypeHint(OS, ExitBTC);
14173 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14174 // Retry with predicates.
14176 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14178 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14179 OS << "\n predicated symbolic max exit count for "
14180 << ExitingBlock->getName() << ": ";
14181 PrintSCEVWithTypeHint(OS, ExitBTC);
14182 OS << "\n Predicates:\n";
14183 for (const auto *P : Predicates)
14184 P->print(OS, 4);
14185 }
14186 }
14187 OS << "\n";
14188 }
14189
14191 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14192 if (PBT != BTC) {
14193 OS << "Loop ";
14194 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14195 OS << ": ";
14196 if (!isa<SCEVCouldNotCompute>(PBT)) {
14197 OS << "Predicated backedge-taken count is ";
14198 PrintSCEVWithTypeHint(OS, PBT);
14199 } else
14200 OS << "Unpredictable predicated backedge-taken count.";
14201 OS << "\n";
14202 OS << " Predicates:\n";
14203 for (const auto *P : Preds)
14204 P->print(OS, 4);
14205 }
14206 Preds.clear();
14207
14208 auto *PredConstantMax =
14210 if (PredConstantMax != ConstantBTC) {
14211 OS << "Loop ";
14212 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14213 OS << ": ";
14214 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14215 OS << "Predicated constant max backedge-taken count is ";
14216 PrintSCEVWithTypeHint(OS, PredConstantMax);
14217 } else
14218 OS << "Unpredictable predicated constant max backedge-taken count.";
14219 OS << "\n";
14220 OS << " Predicates:\n";
14221 for (const auto *P : Preds)
14222 P->print(OS, 4);
14223 }
14224 Preds.clear();
14225
14226 auto *PredSymbolicMax =
14228 if (SymbolicBTC != PredSymbolicMax) {
14229 OS << "Loop ";
14230 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14231 OS << ": ";
14232 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14233 OS << "Predicated symbolic max backedge-taken count is ";
14234 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14235 } else
14236 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14237 OS << "\n";
14238 OS << " Predicates:\n";
14239 for (const auto *P : Preds)
14240 P->print(OS, 4);
14241 }
14242
14244 OS << "Loop ";
14245 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14246 OS << ": ";
14247 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14248 }
14249}
14250
14251namespace llvm {
14252// Note: these overloaded operators need to be in the llvm namespace for them
14253// to be resolved correctly. If we put them outside the llvm namespace, the
14254//
14255// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14256//
14257// code below "breaks" and start printing raw enum values as opposed to the
14258// string values.
14261 switch (LD) {
14263 OS << "Variant";
14264 break;
14266 OS << "Invariant";
14267 break;
14269 OS << "Uniform";
14270 break;
14272 OS << "Computable";
14273 break;
14274 }
14275 return OS;
14276}
14277
14280 switch (BD) {
14282 OS << "DoesNotDominate";
14283 break;
14285 OS << "Dominates";
14286 break;
14288 OS << "ProperlyDominates";
14289 break;
14290 }
14291 return OS;
14292}
14293} // namespace llvm
14294
14296 // ScalarEvolution's implementation of the print method is to print
14297 // out SCEV values of all instructions that are interesting. Doing
14298 // this potentially causes it to create new SCEV objects though,
14299 // which technically conflicts with the const qualifier. This isn't
14300 // observable from outside the class though, so casting away the
14301 // const isn't dangerous.
14302 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14303
14304 if (ClassifyExpressions) {
14305 OS << "Classifying expressions for: ";
14306 F.printAsOperand(OS, /*PrintType=*/false);
14307 OS << "\n";
14308 for (Instruction &I : instructions(F))
14309 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14310 OS << I << '\n';
14311 OS << " --> ";
14312 const SCEV *SV = SE.getSCEV(&I);
14313 SV->print(OS);
14314 if (!isa<SCEVCouldNotCompute>(SV)) {
14315 OS << " U: ";
14316 SE.getUnsignedRange(SV).print(OS);
14317 OS << " S: ";
14318 SE.getSignedRange(SV).print(OS);
14319 }
14320
14321 const Loop *L = LI.getLoopFor(I.getParent());
14322
14323 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14324 if (AtUse != SV) {
14325 OS << " --> ";
14326 OS << AtUse;
14327 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14328 OS << " U: ";
14329 SE.getUnsignedRange(AtUse).print(OS);
14330 OS << " S: ";
14331 SE.getSignedRange(AtUse).print(OS);
14332 }
14333 }
14334
14335 if (L) {
14336 OS << "\t\t" "Exits: ";
14337 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14338 if (!SE.isLoopInvariant(ExitValue, L)) {
14339 OS << "<<Unknown>>";
14340 } else {
14341 OS << ExitValue;
14342 }
14343
14344 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14345 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14346 OS << LS;
14347 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14348 OS << ": " << SE.getLoopDisposition(SV, Iter);
14349 }
14350
14351 for (const auto *InnerL : depth_first(L)) {
14352 if (InnerL == L)
14353 continue;
14354 OS << LS;
14355 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14356 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14357 }
14358
14359 OS << " }";
14360 }
14361
14362 OS << "\n";
14363 }
14364 }
14365
14366 OS << "Determining loop execution counts for: ";
14367 F.printAsOperand(OS, /*PrintType=*/false);
14368 OS << "\n";
14369 for (Loop *I : LI)
14370 PrintLoopInfo(OS, &SE, I);
14371}
14372
14375 auto &Values = LoopDispositions[S];
14376 for (auto &V : Values) {
14377 if (V.getPointer() == L)
14378 return V.getInt();
14379 }
14380 Values.emplace_back(L, LoopVariant);
14381 LoopDisposition D = computeLoopDisposition(S, L);
14382 auto &Values2 = LoopDispositions[S];
14383 for (auto &V : llvm::reverse(Values2)) {
14384 if (V.getPointer() == L) {
14385 V.setInt(D);
14386 break;
14387 }
14388 }
14389 return D;
14390}
14391
14393ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14394 switch (S->getSCEVType()) {
14395 case scConstant:
14396 case scVScale:
14397 return LoopInvariant;
14398 case scAddRecExpr: {
14399 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14400
14401 // If L is the addrec's loop, it's computable.
14402 if (AR->getLoop() == L)
14403 return LoopComputable;
14404
14405 // Add recurrences are never invariant in the function-body (null loop).
14406 if (!L)
14407 return LoopVariant;
14408
14409 // Everything that is not defined at loop entry is variant.
14410 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14411 if (L->contains(AR->getLoop()) &&
14412 llvm::all_of(AR->operands(),
14413 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14414 return LoopUniform;
14415
14416 return LoopVariant;
14417 }
14418 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14419 " dominate the contained loop's header?");
14420
14421 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14422 if (AR->getLoop()->contains(L))
14423 return LoopInvariant;
14424
14425 // This recurrence is variant w.r.t. L if any of its operands
14426 // are variant.
14427 for (SCEVUse Op : AR->operands())
14428 if (!isLoopInvariant(Op, L))
14429 return LoopVariant;
14430
14431 // Otherwise it's loop-invariant.
14432 return LoopInvariant;
14433 }
14434 case scTruncate:
14435 case scZeroExtend:
14436 case scSignExtend:
14437 case scPtrToAddr:
14438 case scAddExpr:
14439 case scMulExpr:
14440 case scUDivExpr:
14441 case scUMaxExpr:
14442 case scSMaxExpr:
14443 case scUMinExpr:
14444 case scSMinExpr:
14445 case scSequentialUMinExpr: {
14446 bool HasVarying = false;
14447 bool HasUniform = false;
14448 for (SCEVUse Op : S->operands()) {
14450 if (D == LoopVariant)
14451 return LoopVariant;
14452 if (D == LoopComputable)
14453 HasVarying = true;
14454 if (D == LoopUniform)
14455 HasUniform = true;
14456 }
14457 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14458 : (HasUniform ? LoopUniform : LoopInvariant);
14459 }
14460 case scUnknown:
14461 // All non-instruction values are loop invariant. All instructions are loop
14462 // invariant if they are not contained in the specified loop.
14463 // Instructions are never considered invariant in the function body
14464 // (null loop) because they are defined within the "loop".
14466 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14467 return LoopInvariant;
14468 case scCouldNotCompute:
14469 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14470 }
14471 llvm_unreachable("Unknown SCEV kind!");
14472}
14473
14474bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14476 return D == LoopUniform || D == LoopInvariant;
14477}
14478
14480 return getLoopDisposition(S, L) == LoopInvariant;
14481}
14482
14484 return getLoopDisposition(S, L) == LoopComputable;
14485}
14486
14489 auto &Values = BlockDispositions[S];
14490 for (auto &V : Values) {
14491 if (V.getPointer() == BB)
14492 return V.getInt();
14493 }
14494 Values.emplace_back(BB, DoesNotDominateBlock);
14495 BlockDisposition D = computeBlockDisposition(S, BB);
14496 auto &Values2 = BlockDispositions[S];
14497 for (auto &V : llvm::reverse(Values2)) {
14498 if (V.getPointer() == BB) {
14499 V.setInt(D);
14500 break;
14501 }
14502 }
14503 return D;
14504}
14505
14507ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14508 switch (S->getSCEVType()) {
14509 case scConstant:
14510 case scVScale:
14512 case scAddRecExpr: {
14513 // This uses a "dominates" query instead of "properly dominates" query
14514 // to test for proper dominance too, because the instruction which
14515 // produces the addrec's value is a PHI, and a PHI effectively properly
14516 // dominates its entire containing block.
14517 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14518 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14519 return DoesNotDominateBlock;
14520
14521 // Fall through into SCEVNAryExpr handling.
14522 [[fallthrough]];
14523 }
14524 case scTruncate:
14525 case scZeroExtend:
14526 case scSignExtend:
14527 case scPtrToAddr:
14528 case scAddExpr:
14529 case scMulExpr:
14530 case scUDivExpr:
14531 case scUMaxExpr:
14532 case scSMaxExpr:
14533 case scUMinExpr:
14534 case scSMinExpr:
14535 case scSequentialUMinExpr: {
14536 bool Proper = true;
14537 for (const SCEV *NAryOp : S->operands()) {
14539 if (D == DoesNotDominateBlock)
14540 return DoesNotDominateBlock;
14541 if (D == DominatesBlock)
14542 Proper = false;
14543 }
14544 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14545 }
14546 case scUnknown:
14547 if (Instruction *I =
14549 if (I->getParent() == BB)
14550 return DominatesBlock;
14551 if (DT.properlyDominates(I->getParent(), BB))
14553 return DoesNotDominateBlock;
14554 }
14556 case scCouldNotCompute:
14557 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14558 }
14559 llvm_unreachable("Unknown SCEV kind!");
14560}
14561
14562bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14563 return getBlockDisposition(S, BB) >= DominatesBlock;
14564}
14565
14568}
14569
14570bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14571 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14572}
14573
14574void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14575 bool Predicated) {
14576 auto &BECounts =
14577 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14578 auto It = BECounts.find(L);
14579 if (It != BECounts.end()) {
14580 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14581 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14582 if (!isa<SCEVConstant>(S)) {
14583 auto UserIt = BECountUsers.find(S);
14584 assert(UserIt != BECountUsers.end());
14585 UserIt->second.erase({L, Predicated});
14586 }
14587 }
14588 }
14589 BECounts.erase(It);
14590 }
14591}
14592
14593void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14594 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14595 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14596
14597 while (!Worklist.empty()) {
14598 const SCEV *Curr = Worklist.pop_back_val();
14599 auto Users = SCEVUsers.find(Curr);
14600 if (Users != SCEVUsers.end())
14601 for (const auto *User : Users->second)
14602 if (ToForget.insert(User).second)
14603 Worklist.push_back(User);
14604 }
14605
14606 for (const auto *S : ToForget)
14607 forgetMemoizedResultsImpl(S);
14608
14609 PredicatedSCEVRewrites.remove_if(
14610 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14611}
14612
14613void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14614 LoopDispositions.erase(S);
14615 BlockDispositions.erase(S);
14616 UnsignedRanges.erase(S);
14617 SignedRanges.erase(S);
14618 HasRecMap.erase(S);
14619 ConstantMultipleCache.erase(S);
14620
14621 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14622 UnsignedWrapViaInductionTried.erase(AR);
14623 SignedWrapViaInductionTried.erase(AR);
14624 }
14625
14626 auto ExprIt = ExprValueMap.find(S);
14627 if (ExprIt != ExprValueMap.end()) {
14628 for (Value *V : ExprIt->second) {
14629 auto ValueIt = ValueExprMap.find_as(V);
14630 if (ValueIt != ValueExprMap.end())
14631 ValueExprMap.erase(ValueIt);
14632 }
14633 ExprValueMap.erase(ExprIt);
14634 }
14635
14636 auto ScopeIt = ValuesAtScopes.find(S);
14637 if (ScopeIt != ValuesAtScopes.end()) {
14638 for (const auto &Pair : ScopeIt->second)
14639 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14640 llvm::erase(ValuesAtScopesUsers[Pair.second],
14641 std::make_pair(Pair.first, S));
14642 ValuesAtScopes.erase(ScopeIt);
14643 }
14644
14645 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14646 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14647 for (const auto &Pair : ScopeUserIt->second)
14648 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14649 ValuesAtScopesUsers.erase(ScopeUserIt);
14650 }
14651
14652 auto BEUsersIt = BECountUsers.find(S);
14653 if (BEUsersIt != BECountUsers.end()) {
14654 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14655 auto Copy = BEUsersIt->second;
14656 for (const auto &Pair : Copy)
14657 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14658 BECountUsers.erase(BEUsersIt);
14659 }
14660
14661 auto FoldUser = FoldCacheUser.find(S);
14662 if (FoldUser != FoldCacheUser.end())
14663 for (auto &KV : FoldUser->second)
14664 FoldCache.erase(KV);
14665 FoldCacheUser.erase(S);
14666}
14667
14668void
14669ScalarEvolution::getUsedLoops(const SCEV *S,
14670 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14671 struct FindUsedLoops {
14672 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14673 : LoopsUsed(LoopsUsed) {}
14674 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14675 bool follow(const SCEV *S) {
14676 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14677 LoopsUsed.insert(AR->getLoop());
14678 return true;
14679 }
14680
14681 bool isDone() const { return false; }
14682 };
14683
14684 FindUsedLoops F(LoopsUsed);
14685 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14686}
14687
14688void ScalarEvolution::getReachableBlocks(
14691 Worklist.push_back(&F.getEntryBlock());
14692 while (!Worklist.empty()) {
14693 BasicBlock *BB = Worklist.pop_back_val();
14694 if (!Reachable.insert(BB).second)
14695 continue;
14696
14697 Value *Cond;
14698 BasicBlock *TrueBB, *FalseBB;
14699 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14700 m_BasicBlock(FalseBB)))) {
14701 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14702 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14703 continue;
14704 }
14705
14706 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14707 const SCEV *L = getSCEV(Cmp->getOperand(0));
14708 const SCEV *R = getSCEV(Cmp->getOperand(1));
14709 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14710 Worklist.push_back(TrueBB);
14711 continue;
14712 }
14713 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14714 R)) {
14715 Worklist.push_back(FalseBB);
14716 continue;
14717 }
14718 }
14719 }
14720
14721 append_range(Worklist, successors(BB));
14722 }
14723}
14724
14726 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14727 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14728
14729 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14730
14731 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14732 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14733 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14734
14735 const SCEV *visitConstant(const SCEVConstant *Constant) {
14736 return SE.getConstant(Constant->getAPInt());
14737 }
14738
14739 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14740 return SE.getUnknown(Expr->getValue());
14741 }
14742
14743 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14744 return SE.getCouldNotCompute();
14745 }
14746 };
14747
14748 SCEVMapper SCM(SE2);
14749 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14750 SE2.getReachableBlocks(ReachableBlocks, F);
14751
14752 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14753 if (containsUndefs(Old) || containsUndefs(New)) {
14754 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14755 // not propagate undef aggressively). This means we can (and do) fail
14756 // verification in cases where a transform makes a value go from "undef"
14757 // to "undef+1" (say). The transform is fine, since in both cases the
14758 // result is "undef", but SCEV thinks the value increased by 1.
14759 return nullptr;
14760 }
14761
14762 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14763 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14764 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14765 return nullptr;
14766
14767 return Delta;
14768 };
14769
14770 while (!LoopStack.empty()) {
14771 auto *L = LoopStack.pop_back_val();
14772 llvm::append_range(LoopStack, *L);
14773
14774 // Only verify BECounts in reachable loops. For an unreachable loop,
14775 // any BECount is legal.
14776 if (!ReachableBlocks.contains(L->getHeader()))
14777 continue;
14778
14779 // Only verify cached BECounts. Computing new BECounts may change the
14780 // results of subsequent SCEV uses.
14781 auto It = BackedgeTakenCounts.find(L);
14782 if (It == BackedgeTakenCounts.end())
14783 continue;
14784
14785 auto *CurBECount =
14786 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14787 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14788
14789 if (CurBECount == SE2.getCouldNotCompute() ||
14790 NewBECount == SE2.getCouldNotCompute()) {
14791 // NB! This situation is legal, but is very suspicious -- whatever pass
14792 // change the loop to make a trip count go from could not compute to
14793 // computable or vice-versa *should have* invalidated SCEV. However, we
14794 // choose not to assert here (for now) since we don't want false
14795 // positives.
14796 continue;
14797 }
14798
14799 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14800 SE.getTypeSizeInBits(NewBECount->getType()))
14801 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14802 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14803 SE.getTypeSizeInBits(NewBECount->getType()))
14804 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14805
14806 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14807 if (Delta && !Delta->isZero()) {
14808 dbgs() << "Trip Count for " << *L << " Changed!\n";
14809 dbgs() << "Old: " << *CurBECount << "\n";
14810 dbgs() << "New: " << *NewBECount << "\n";
14811 dbgs() << "Delta: " << *Delta << "\n";
14812 std::abort();
14813 }
14814 }
14815
14816 // Collect all valid loops currently in LoopInfo.
14817 SmallPtrSet<Loop *, 32> ValidLoops;
14818 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14819 while (!Worklist.empty()) {
14820 Loop *L = Worklist.pop_back_val();
14821 if (ValidLoops.insert(L).second)
14822 Worklist.append(L->begin(), L->end());
14823 }
14824 for (const auto &KV : ValueExprMap) {
14825#ifndef NDEBUG
14826 // Check for SCEV expressions referencing invalid/deleted loops.
14827 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14828 assert(ValidLoops.contains(AR->getLoop()) &&
14829 "AddRec references invalid loop");
14830 }
14831#endif
14832
14833 // Check that the value is also part of the reverse map.
14834 auto It = ExprValueMap.find(KV.second);
14835 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14836 dbgs() << "Value " << *KV.first
14837 << " is in ValueExprMap but not in ExprValueMap\n";
14838 std::abort();
14839 }
14840
14841 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14842 if (!ReachableBlocks.contains(I->getParent()))
14843 continue;
14844 const SCEV *OldSCEV = SCM.visit(KV.second);
14845 const SCEV *NewSCEV = SE2.getSCEV(I);
14846 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14847 if (Delta && !Delta->isZero()) {
14848 dbgs() << "SCEV for value " << *I << " changed!\n"
14849 << "Old: " << *OldSCEV << "\n"
14850 << "New: " << *NewSCEV << "\n"
14851 << "Delta: " << *Delta << "\n";
14852 std::abort();
14853 }
14854 }
14855 }
14856
14857 for (const auto &KV : ExprValueMap) {
14858 for (Value *V : KV.second) {
14859 const SCEV *S = ValueExprMap.lookup(V);
14860 if (!S) {
14861 dbgs() << "Value " << *V
14862 << " is in ExprValueMap but not in ValueExprMap\n";
14863 std::abort();
14864 }
14865 if (S != KV.first) {
14866 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14867 << *KV.first << "\n";
14868 std::abort();
14869 }
14870 }
14871 }
14872
14873 // Verify integrity of SCEV users.
14874 for (const auto &S : UniqueSCEVs) {
14875 for (SCEVUse Op : S.operands()) {
14876 // We do not store dependencies of constants.
14877 if (isa<SCEVConstant>(Op))
14878 continue;
14879 auto It = SCEVUsers.find(Op);
14880 if (It != SCEVUsers.end() && It->second.count(&S))
14881 continue;
14882 dbgs() << "Use of operand " << *Op << " by user " << S
14883 << " is not being tracked!\n";
14884 std::abort();
14885 }
14886 }
14887
14888 // Verify integrity of ValuesAtScopes users.
14889 for (const auto &ValueAndVec : ValuesAtScopes) {
14890 const SCEV *Value = ValueAndVec.first;
14891 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14892 const Loop *L = LoopAndValueAtScope.first;
14893 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
14894 if (!isa<SCEVConstant>(ValueAtScope)) {
14895 auto It = ValuesAtScopesUsers.find(ValueAtScope);
14896 if (It != ValuesAtScopesUsers.end() &&
14897 is_contained(It->second, std::make_pair(L, Value)))
14898 continue;
14899 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14900 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14901 std::abort();
14902 }
14903 }
14904 }
14905
14906 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14907 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14908 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14909 const Loop *L = LoopAndValue.first;
14910 const SCEV *Value = LoopAndValue.second;
14912 auto It = ValuesAtScopes.find(Value);
14913 if (It != ValuesAtScopes.end() &&
14914 is_contained(It->second, std::make_pair(L, ValueAtScope)))
14915 continue;
14916 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14917 << *ValueAtScope << " missing in ValuesAtScopes\n";
14918 std::abort();
14919 }
14920 }
14921
14922 // Verify integrity of BECountUsers.
14923 auto VerifyBECountUsers = [&](bool Predicated) {
14924 auto &BECounts =
14925 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14926 for (const auto &LoopAndBEInfo : BECounts) {
14927 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14928 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14929 if (!isa<SCEVConstant>(S)) {
14930 auto UserIt = BECountUsers.find(S);
14931 if (UserIt != BECountUsers.end() &&
14932 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14933 continue;
14934 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14935 << " missing from BECountUsers\n";
14936 std::abort();
14937 }
14938 }
14939 }
14940 }
14941 };
14942 VerifyBECountUsers(/* Predicated */ false);
14943 VerifyBECountUsers(/* Predicated */ true);
14944
14945 // Verify intergity of loop disposition cache.
14946 for (auto &[S, Values] : LoopDispositions) {
14947 for (auto [Loop, CachedDisposition] : Values) {
14948 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
14949 if (CachedDisposition != RecomputedDisposition) {
14950 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
14951 << " is incorrect: cached " << CachedDisposition << ", actual "
14952 << RecomputedDisposition << "\n";
14953 std::abort();
14954 }
14955 }
14956 }
14957
14958 // Verify integrity of the block disposition cache.
14959 for (auto &[S, Values] : BlockDispositions) {
14960 for (auto [BB, CachedDisposition] : Values) {
14961 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
14962 if (CachedDisposition != RecomputedDisposition) {
14963 dbgs() << "Cached disposition of " << *S << " for block %"
14964 << BB->getName() << " is incorrect: cached " << CachedDisposition
14965 << ", actual " << RecomputedDisposition << "\n";
14966 std::abort();
14967 }
14968 }
14969 }
14970
14971 // Verify FoldCache/FoldCacheUser caches.
14972 for (auto [FoldID, Expr] : FoldCache) {
14973 auto I = FoldCacheUser.find(Expr);
14974 if (I == FoldCacheUser.end()) {
14975 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
14976 << "!\n";
14977 std::abort();
14978 }
14979 if (!is_contained(I->second, FoldID)) {
14980 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
14981 std::abort();
14982 }
14983 }
14984 for (auto [Expr, IDs] : FoldCacheUser) {
14985 for (auto &FoldID : IDs) {
14986 const SCEV *S = FoldCache.lookup(FoldID);
14987 if (!S) {
14988 dbgs() << "Missing entry in FoldCache for expression " << *Expr
14989 << "!\n";
14990 std::abort();
14991 }
14992 if (S != Expr) {
14993 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
14994 << " != " << *Expr << "!\n";
14995 std::abort();
14996 }
14997 }
14998 }
14999
15000 // Verify that ConstantMultipleCache computations are correct. We check that
15001 // cached multiples and recomputed multiples are multiples of each other to
15002 // verify correctness. It is possible that a recomputed multiple is different
15003 // from the cached multiple due to strengthened no wrap flags or changes in
15004 // KnownBits computations.
15005 for (auto [S, Multiple] : ConstantMultipleCache) {
15006 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15007 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15008 Multiple.urem(RecomputedMultiple) != 0 &&
15009 RecomputedMultiple.urem(Multiple) != 0)) {
15010 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15011 << *S << " : Computed " << RecomputedMultiple
15012 << " but cache contains " << Multiple << "!\n";
15013 std::abort();
15014 }
15015 }
15016}
15017
15019 Function &F, const PreservedAnalyses &PA,
15020 FunctionAnalysisManager::Invalidator &Inv) {
15021 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15022 // of its dependencies is invalidated.
15023 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15024 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15025 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15026 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15027 Inv.invalidate<LoopAnalysis>(F, PA);
15028}
15029
15030AnalysisKey ScalarEvolutionAnalysis::Key;
15031
15034 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15035 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15036 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15037 auto &LI = AM.getResult<LoopAnalysis>(F);
15038 return ScalarEvolution(F, TLI, AC, DT, LI);
15039}
15040
15046
15049 // For compatibility with opt's -analyze feature under legacy pass manager
15050 // which was not ported to NPM. This keeps tests using
15051 // update_analyze_test_checks.py working.
15052 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15053 << F.getName() << "':\n";
15055 return PreservedAnalyses::all();
15056}
15057
15059 "Scalar Evolution Analysis", false, true)
15065 "Scalar Evolution Analysis", false, true)
15066
15067char ScalarEvolutionWrapperPass::ID = 0;
15068
15070
15072 SE.reset(new ScalarEvolution(
15074 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15076 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15077 return false;
15078}
15079
15081
15083 SE->print(OS);
15084}
15085
15087 if (!VerifySCEV)
15088 return;
15089
15090 SE->verify();
15091}
15092
15100
15102 const SCEV *RHS) {
15103 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15104}
15105
15106const SCEVPredicate *
15108 const SCEV *LHS, const SCEV *RHS) {
15110 assert(LHS->getType() == RHS->getType() &&
15111 "Type mismatch between LHS and RHS");
15112 // Unique this node based on the arguments
15113 ID.AddInteger(SCEVPredicate::P_Compare);
15114 ID.AddInteger(Pred);
15115 ID.AddPointer(LHS);
15116 ID.AddPointer(RHS);
15117 void *IP = nullptr;
15118 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15119 return S;
15120 SCEVComparePredicate *Eq = new (SCEVAllocator)
15121 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15122 UniquePreds.InsertNode(Eq, IP);
15123 return Eq;
15124}
15125
15127 const SCEVAddRecExpr *AR,
15130 // Unique this node based on the arguments
15132 ID.AddPointer(AR);
15133 ID.AddInteger(AddedFlags);
15134 void *IP = nullptr;
15135 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15136 return S;
15137 auto *OF = new (SCEVAllocator)
15138 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15139 UniquePreds.InsertNode(OF, IP);
15140 return OF;
15141}
15142
15143namespace {
15144
15145class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15146public:
15147
15148 /// Rewrites \p S in the context of a loop L and the SCEV predication
15149 /// infrastructure.
15150 ///
15151 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15152 /// equivalences present in \p Pred.
15153 ///
15154 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15155 /// \p NewPreds such that the result will be an AddRecExpr.
15156 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15158 const SCEVPredicate *Pred) {
15159 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15160 return Rewriter.visit(S);
15161 }
15162
15163 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15164 if (Pred) {
15165 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15166 for (const auto *Pred : U->getPredicates())
15167 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15168 if (IPred->getLHS() == Expr &&
15169 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15170 return IPred->getRHS();
15171 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15172 if (IPred->getLHS() == Expr &&
15173 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15174 return IPred->getRHS();
15175 }
15176 }
15177 return convertToAddRecWithPreds(Expr);
15178 }
15179
15180 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15181 const SCEV *Operand = visit(Expr->getOperand());
15182 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15183 if (AR && AR->getLoop() == L && AR->isAffine()) {
15184 // This couldn't be folded because the operand didn't have the nuw
15185 // flag. Add the nusw flag as an assumption that we could make.
15186 const SCEV *Step = AR->getStepRecurrence(SE);
15187 Type *Ty = Expr->getType();
15188 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15189 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15190 SE.getSignExtendExpr(Step, Ty), L,
15191 AR->getNoWrapFlags());
15192 }
15193 return SE.getZeroExtendExpr(Operand, Expr->getType());
15194 }
15195
15196 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15197 const SCEV *Operand = visit(Expr->getOperand());
15198 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15199 if (AR && AR->getLoop() == L && AR->isAffine()) {
15200 // This couldn't be folded because the operand didn't have the nsw
15201 // flag. Add the nssw flag as an assumption that we could make.
15202 const SCEV *Step = AR->getStepRecurrence(SE);
15203 Type *Ty = Expr->getType();
15204 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15205 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15206 SE.getSignExtendExpr(Step, Ty), L,
15207 AR->getNoWrapFlags());
15208 }
15209 return SE.getSignExtendExpr(Operand, Expr->getType());
15210 }
15211
15212private:
15213 explicit SCEVPredicateRewriter(
15214 const Loop *L, ScalarEvolution &SE,
15215 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15216 const SCEVPredicate *Pred)
15217 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15218
15219 bool addOverflowAssumption(const SCEVPredicate *P) {
15220 if (!NewPreds) {
15221 // Check if we've already made this assumption.
15222 return Pred && Pred->implies(P, SE);
15223 }
15224 NewPreds->push_back(P);
15225 return true;
15226 }
15227
15228 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15230 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15231 return addOverflowAssumption(A);
15232 }
15233
15234 // If \p Expr represents a PHINode, we try to see if it can be represented
15235 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15236 // to add this predicate as a runtime overflow check, we return the AddRec.
15237 // If \p Expr does not meet these conditions (is not a PHI node, or we
15238 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15239 // return \p Expr.
15240 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15241 if (!isa<PHINode>(Expr->getValue()))
15242 return Expr;
15243 std::optional<
15244 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15245 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15246 if (!PredicatedRewrite)
15247 return Expr;
15248 for (const auto *P : PredicatedRewrite->second){
15249 // Wrap predicates from outer loops are not supported.
15250 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15251 if (L != WP->getExpr()->getLoop())
15252 return Expr;
15253 }
15254 if (!addOverflowAssumption(P))
15255 return Expr;
15256 }
15257 return PredicatedRewrite->first;
15258 }
15259
15260 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15261 const SCEVPredicate *Pred;
15262 const Loop *L;
15263};
15264
15265} // end anonymous namespace
15266
15267const SCEV *
15269 const SCEVPredicate &Preds) {
15270 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15271}
15272
15274 const SCEV *S, const Loop *L,
15277 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15278 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15279
15280 if (!AddRec)
15281 return nullptr;
15282
15283 // Check if any of the transformed predicates is known to be false. In that
15284 // case, it doesn't make sense to convert to a predicated AddRec, as the
15285 // versioned loop will never execute.
15286 for (const SCEVPredicate *Pred : TransformPreds) {
15287 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15288 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15289 continue;
15290
15291 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15292 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15293 if (isa<SCEVCouldNotCompute>(ExitCount))
15294 continue;
15295
15296 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15297 if (!Step->isOne())
15298 continue;
15299
15300 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15301 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15302 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15303 return nullptr;
15304 }
15305
15306 // Since the transformation was successful, we can now transfer the SCEV
15307 // predicates.
15308 Preds.append(TransformPreds.begin(), TransformPreds.end());
15309
15310 return AddRec;
15311}
15312
15313/// SCEV predicates
15317
15319 const ICmpInst::Predicate Pred,
15320 const SCEV *LHS, const SCEV *RHS)
15321 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15322 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15323 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15324}
15325
15327 ScalarEvolution &SE) const {
15328 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15329
15330 if (!Op)
15331 return false;
15332
15333 if (Pred != ICmpInst::ICMP_EQ)
15334 return false;
15335
15336 return Op->LHS == LHS && Op->RHS == RHS;
15337}
15338
15339bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15340
15342 if (Pred == ICmpInst::ICMP_EQ)
15343 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15344 else
15345 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15346 << *RHS << "\n";
15347
15348}
15349
15351 const SCEVAddRecExpr *AR,
15352 IncrementWrapFlags Flags)
15353 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15354
15355const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15356
15358 ScalarEvolution &SE) const {
15359 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15360 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15361 return false;
15362
15363 if (Op->AR == AR)
15364 return true;
15365
15366 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15368 return false;
15369
15370 const SCEV *Start = AR->getStart();
15371 const SCEV *OpStart = Op->AR->getStart();
15372 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15373 return false;
15374
15375 // Reject pointers to different address spaces.
15376 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15377 return false;
15378
15379 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15380 // narrower-type AddRec.
15381 if (SE.getTypeSizeInBits(AR->getType()) >
15382 SE.getTypeSizeInBits(Op->AR->getType()))
15383 return false;
15384
15385 const SCEV *Step = AR->getStepRecurrence(SE);
15386 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15387 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15388 return false;
15389
15390 // If both steps are positive, this implies N, if N's start and step are
15391 // ULE/SLE (for NSUW/NSSW) than this'.
15392 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15393 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15394 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15395
15396 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15397 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15398 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15399 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15400 : SE.getNoopOrSignExtend(Start, WiderTy);
15402 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15403 SE.isKnownPredicate(Pred, OpStart, Start);
15404}
15405
15407 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15408 IncrementWrapFlags IFlags = Flags;
15409
15410 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15411 IFlags = clearFlags(IFlags, IncrementNSSW);
15412
15413 return IFlags == IncrementAnyWrap;
15414}
15415
15416void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15417 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15419 OS << "<nusw>";
15421 OS << "<nssw>";
15422 OS << "\n";
15423}
15424
15427 ScalarEvolution &SE) {
15428 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15429 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15430
15431 // We can safely transfer the NSW flag as NSSW.
15432 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15433 ImpliedFlags = IncrementNSSW;
15434
15435 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15436 // If the increment is positive, the SCEV NUW flag will also imply the
15437 // WrapPredicate NUSW flag.
15438 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15439 if (Step->getValue()->getValue().isNonNegative())
15440 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15441 }
15442
15443 return ImpliedFlags;
15444}
15445
15446/// Union predicates don't get cached so create a dummy set ID for it.
15448 ScalarEvolution &SE)
15449 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15450 for (const auto *P : Preds)
15451 add(P, SE);
15452}
15453
15455 return all_of(Preds,
15456 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15457}
15458
15460 ScalarEvolution &SE) const {
15461 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15462 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15463 return this->implies(I, SE);
15464 });
15465
15466 if (any_of(Preds,
15467 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15468 return true;
15469
15470 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15471 // equal predicates.
15472 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15473 if (!NWrap)
15474 return false;
15475 const Loop *L = NWrap->getExpr()->getLoop();
15476 return any_of(Preds, [&](const SCEVPredicate *I) {
15477 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15478 if (!IWrap)
15479 return false;
15480 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15481 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15482 return RewrittenAR &&
15483 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15484 });
15485}
15486
15488 for (const auto *Pred : Preds)
15489 Pred->print(OS, Depth);
15490}
15491
15492void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15493 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15494 for (const auto *Pred : Set->Preds)
15495 add(Pred, SE);
15496 return;
15497 }
15498
15499 // Implication checks are quadratic in the number of predicates. Stop doing
15500 // them if there are many predicates, as they should be too expensive to use
15501 // anyway at that point.
15502 bool CheckImplies = Preds.size() < 16;
15503
15504 // Only add predicate if it is not already implied by this union predicate.
15505 if (CheckImplies && implies(N, SE))
15506 return;
15507
15508 // Build a new vector containing the current predicates, except the ones that
15509 // are implied by the new predicate N.
15511 for (auto *P : Preds) {
15512 if (CheckImplies && N->implies(P, SE))
15513 continue;
15514 PrunedPreds.push_back(P);
15515 }
15516 Preds = std::move(PrunedPreds);
15517 Preds.push_back(N);
15518}
15519
15521 Loop &L)
15522 : SE(SE), L(L) {
15524 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15525}
15526
15529 for (const auto *Op : Ops)
15530 // We do not expect that forgetting cached data for SCEVConstants will ever
15531 // open any prospects for sharpening or introduce any correctness issues,
15532 // so we don't bother storing their dependencies.
15533 if (!isa<SCEVConstant>(Op))
15534 SCEVUsers[Op].insert(User);
15535}
15536
15538 for (const SCEV *Op : Ops)
15539 // We do not expect that forgetting cached data for SCEVConstants will ever
15540 // open any prospects for sharpening or introduce any correctness issues,
15541 // so we don't bother storing their dependencies.
15542 if (!isa<SCEVConstant>(Op))
15543 SCEVUsers[Op].insert(User);
15544}
15545
15547 const SCEV *Expr = SE.getSCEV(V);
15548 return getPredicatedSCEV(Expr);
15549}
15550
15552 RewriteEntry &Entry = RewriteMap[Expr];
15553
15554 // If we already have an entry and the version matches, return it.
15555 if (Entry.second && Generation == Entry.first)
15556 return Entry.second;
15557
15558 // We found an entry but it's stale. Rewrite the stale entry
15559 // according to the current predicate.
15560 if (Entry.second)
15561 Expr = Entry.second;
15562
15563 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15564 Entry = {Generation, NewSCEV};
15565
15566 return NewSCEV;
15567}
15568
15570 if (!BackedgeCount) {
15572 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15573 for (const auto *P : Preds)
15574 addPredicate(*P);
15575 }
15576 return BackedgeCount;
15577}
15578
15580 if (!SymbolicMaxBackedgeCount) {
15582 SymbolicMaxBackedgeCount =
15583 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15584 for (const auto *P : Preds)
15585 addPredicate(*P);
15586 }
15587 return SymbolicMaxBackedgeCount;
15588}
15589
15591 if (!SmallConstantMaxTripCount) {
15593 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15594 for (const auto *P : Preds)
15595 addPredicate(*P);
15596 }
15597 return *SmallConstantMaxTripCount;
15598}
15599
15601 if (Preds->implies(&Pred, SE))
15602 return;
15603
15604 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15605 NewPreds.push_back(&Pred);
15606 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15607 updateGeneration();
15608}
15609
15612 for (const SCEVPredicate *P : Preds)
15613 addPredicate(*P);
15614}
15615
15617 return *Preds;
15618}
15619
15620void PredicatedScalarEvolution::updateGeneration() {
15621 // If the generation number wrapped recompute everything.
15622 if (++Generation == 0) {
15623 for (auto &II : RewriteMap) {
15624 const SCEV *Rewritten = II.second.second;
15625 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15626 }
15627 }
15628}
15629
15632 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15633 if (!AR)
15634 return false;
15635
15637 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15638
15640}
15641
15644 const SCEV *Expr = this->getSCEV(V);
15646 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15647
15648 if (!New)
15649 return nullptr;
15650
15651 if (ExtraPreds) {
15652 ExtraPreds->append(NewPreds);
15653 return New;
15654 }
15655
15656 addPredicates(NewPreds);
15657
15658 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15659 return New;
15660}
15661
15664 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15665 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15666 SE)),
15667 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15668
15670 // For each block.
15671 for (auto *BB : L.getBlocks())
15672 for (auto &I : *BB) {
15673 if (!SE.isSCEVable(I.getType()))
15674 continue;
15675
15676 auto *Expr = SE.getSCEV(&I);
15677 auto II = RewriteMap.find(Expr);
15678
15679 if (II == RewriteMap.end())
15680 continue;
15681
15682 // Don't print things that are not interesting.
15683 if (II->second.second == Expr)
15684 continue;
15685
15686 OS.indent(Depth) << "[PSE]" << I << ":\n";
15687 OS.indent(Depth + 2) << *Expr << "\n";
15688 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15689 }
15690}
15691
15694 BasicBlock *Header = L->getHeader();
15695 BasicBlock *Pred = L->getLoopPredecessor();
15696 LoopGuards Guards(SE);
15697 if (!Pred)
15698 return Guards;
15700 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15701 return Guards;
15702}
15703
15704void ScalarEvolution::LoopGuards::collectFromPHI(
15708 unsigned Depth) {
15709 if (!SE.isSCEVable(Phi.getType()))
15710 return;
15711
15712 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15713 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15714 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15715 if (!VisitedBlocks.insert(InBlock).second)
15716 return {nullptr, scCouldNotCompute};
15717
15718 // Avoid analyzing unreachable blocks so that we don't get trapped
15719 // traversing cycles with ill-formed dominance or infinite cycles
15720 if (!SE.DT.isReachableFromEntry(InBlock))
15721 return {nullptr, scCouldNotCompute};
15722
15723 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15724 if (Inserted)
15725 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15726 Depth + 1);
15727 auto &RewriteMap = G->second.RewriteMap;
15728 if (RewriteMap.empty())
15729 return {nullptr, scCouldNotCompute};
15730 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15731 if (S == RewriteMap.end())
15732 return {nullptr, scCouldNotCompute};
15733 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15734 if (!SM)
15735 return {nullptr, scCouldNotCompute};
15736 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15737 return {C0, SM->getSCEVType()};
15738 return {nullptr, scCouldNotCompute};
15739 };
15740 auto MergeMinMaxConst = [](MinMaxPattern P1,
15741 MinMaxPattern P2) -> MinMaxPattern {
15742 auto [C1, T1] = P1;
15743 auto [C2, T2] = P2;
15744 if (!C1 || !C2 || T1 != T2)
15745 return {nullptr, scCouldNotCompute};
15746 switch (T1) {
15747 case scUMaxExpr:
15748 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15749 case scSMaxExpr:
15750 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15751 case scUMinExpr:
15752 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15753 case scSMinExpr:
15754 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15755 default:
15756 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15757 }
15758 };
15759 auto P = GetMinMaxConst(0);
15760 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15761 if (!P.first)
15762 break;
15763 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15764 }
15765 if (P.first) {
15766 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15767 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15768 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15769 Guards.RewriteMap.insert({LHS, RHS});
15770 }
15771}
15772
15773// Return a new SCEV that modifies \p Expr to the closest number divides by
15774// \p Divisor and less or equal than Expr. For now, only handle constant
15775// Expr.
15777 const APInt &DivisorVal,
15778 ScalarEvolution &SE) {
15779 const APInt *ExprVal;
15780 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15781 DivisorVal.isNonPositive())
15782 return Expr;
15783 APInt Rem = ExprVal->urem(DivisorVal);
15784 // return the SCEV: Expr - Expr % Divisor
15785 return SE.getConstant(*ExprVal - Rem);
15786}
15787
15788// Return a new SCEV that modifies \p Expr to the closest number divides by
15789// \p Divisor and greater or equal than Expr. For now, only handle constant
15790// Expr.
15791static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15792 const APInt &DivisorVal,
15793 ScalarEvolution &SE) {
15794 const APInt *ExprVal;
15795 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15796 DivisorVal.isNonPositive())
15797 return Expr;
15798 APInt Rem = ExprVal->urem(DivisorVal);
15799 if (Rem.isZero())
15800 return Expr;
15801 // return the SCEV: Expr + Divisor - Expr % Divisor
15802 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15803}
15804
15806 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15809 // If we have LHS == 0, check if LHS is computing a property of some unknown
15810 // SCEV %v which we can rewrite %v to express explicitly.
15812 return false;
15813 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15814 // explicitly express that.
15815 const SCEVUnknown *URemLHS = nullptr;
15816 const SCEV *URemRHS = nullptr;
15817 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15818 return false;
15819
15820 const SCEV *Multiple =
15821 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15822 DivInfo[URemLHS] = Multiple;
15823 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15824 Multiples[URemLHS] = C->getAPInt();
15825 return true;
15826}
15827
15828// Check if the condition is a divisibility guard (A % B == 0).
15829static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15830 ScalarEvolution &SE) {
15831 const SCEV *X, *Y;
15832 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15833}
15834
15835// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15836// recursively. This is done by aligning up/down the constant value to the
15837// Divisor.
15838static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15839 APInt Divisor,
15840 ScalarEvolution &SE) {
15841 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15842 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15843 // the non-constant operand and in \p LHS the constant operand.
15844 auto IsMinMaxSCEVWithNonNegativeConstant =
15845 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15846 const SCEV *&RHS) {
15847 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15848 if (MinMax->getNumOperands() != 2)
15849 return false;
15850 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15851 if (C->getAPInt().isNegative())
15852 return false;
15853 SCTy = MinMax->getSCEVType();
15854 LHS = MinMax->getOperand(0);
15855 RHS = MinMax->getOperand(1);
15856 return true;
15857 }
15858 }
15859 return false;
15860 };
15861
15862 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15863 SCEVTypes SCTy;
15864 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15865 MinMaxRHS))
15866 return MinMaxExpr;
15867 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15868 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15869 auto *DivisibleExpr =
15870 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15871 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15873 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15874 return SE.getMinMaxExpr(SCTy, Ops);
15875}
15876
15877void ScalarEvolution::LoopGuards::collectFromBlock(
15878 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15879 const BasicBlock *Block, const BasicBlock *Pred,
15880 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15881
15883
15884 SmallVector<SCEVUse> ExprsToRewrite;
15885 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15886 const SCEV *RHS,
15887 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15888 const LoopGuards &DivGuards) {
15889 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15890 // replacement SCEV which isn't directly implied by the structure of that
15891 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15892 // legal. See the scoping rules for flags in the header to understand why.
15893
15894 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15895 // and \p FromRewritten are the same (i.e. there has been no rewrite
15896 // registered for \p From), then puts this value in the list of rewritten
15897 // expressions.
15898 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15899 const SCEV *To) {
15900 if (From == FromRewritten)
15901 ExprsToRewrite.push_back(From);
15902 RewriteMap[From] = To;
15903 };
15904
15905 // Checks whether \p S has already been rewritten. In that case returns the
15906 // existing rewrite because we want to chain further rewrites onto the
15907 // already rewritten value. Otherwise returns \p S.
15908 auto GetMaybeRewritten = [&](const SCEV *S) {
15909 return RewriteMap.lookup_or(S, S);
15910 };
15911
15912 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15913 // create this form when combining two checks of the form (X u< C2 + C1) and
15914 // (X >=u C1).
15915 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15916 const SCEV *MatchLHS,
15917 const SCEV *MatchRHS) {
15918 const SCEVConstant *C1;
15919 const SCEVUnknown *LHSUnknown;
15920 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15921 if (!match(MatchLHS,
15922 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15923 !C2)
15924 return false;
15925
15926 auto ExactRegion =
15927 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15928 .sub(C1->getAPInt());
15929
15930 // Tighten the raw range with what we already know about LHSUnknown
15931 // from prior guards recorded in RewriteMap, or from SCEV's own range
15932 // analysis.
15933 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15934 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15936
15937 // Bail if the guard is inconsistent with prior facts, or if the range
15938 // is still not a monotonic non-wrapping interval after tightening.
15939 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15940 ExactRegion.isFullSet())
15941 return false;
15942
15943 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15944 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15945 const SCEV *ClampedLHS =
15946 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15947 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15948 return true;
15949 };
15950 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15951 return;
15952
15953 // Do not apply information for constants or if RHS contains an AddRec.
15955 return;
15956
15957 // If RHS is SCEVUnknown, make sure the information is applied to it.
15959 std::swap(LHS, RHS);
15961 }
15962
15963 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15964 // Apply divisibility information when computing the constant multiple.
15965 const APInt &DividesBy =
15966 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15967
15968 // Collect rewrites for LHS and its transitive operands based on the
15969 // condition.
15970 // For min/max expressions, also apply the guard to its operands:
15971 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15972 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15973 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15974 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15975
15976 // We cannot express strict predicates in SCEV, so instead we replace them
15977 // with non-strict ones against plus or minus one of RHS depending on the
15978 // predicate.
15979 const SCEV *One = SE.getOne(RHS->getType());
15980 switch (Predicate) {
15981 case CmpInst::ICMP_ULT:
15982 if (RHS->getType()->isPointerTy())
15983 return;
15984 RHS = SE.getUMaxExpr(RHS, One);
15985 [[fallthrough]];
15986 case CmpInst::ICMP_SLT: {
15987 RHS = SE.getMinusSCEV(RHS, One);
15988 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15989 break;
15990 }
15991 case CmpInst::ICMP_UGT:
15992 case CmpInst::ICMP_SGT:
15993 RHS = SE.getAddExpr(RHS, One);
15994 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15995 break;
15996 case CmpInst::ICMP_ULE:
15997 case CmpInst::ICMP_SLE:
15998 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
15999 break;
16000 case CmpInst::ICMP_UGE:
16001 case CmpInst::ICMP_SGE:
16002 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16003 break;
16004 default:
16005 break;
16006 }
16007
16008 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16009 SmallPtrSet<const SCEV *, 16> Visited;
16010
16011 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16012 append_range(Worklist, S->operands());
16013 };
16014
16015 while (!Worklist.empty()) {
16016 const SCEV *From = Worklist.pop_back_val();
16017 if (isa<SCEVConstant>(From))
16018 continue;
16019 if (!Visited.insert(From).second)
16020 continue;
16021 const SCEV *FromRewritten = GetMaybeRewritten(From);
16022 const SCEV *To = nullptr;
16023
16024 switch (Predicate) {
16025 case CmpInst::ICMP_ULT:
16026 case CmpInst::ICMP_ULE:
16027 To = SE.getUMinExpr(FromRewritten, RHS);
16028 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16029 EnqueueOperands(UMax);
16030 break;
16031 case CmpInst::ICMP_SLT:
16032 case CmpInst::ICMP_SLE:
16033 To = SE.getSMinExpr(FromRewritten, RHS);
16034 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16035 EnqueueOperands(SMax);
16036 break;
16037 case CmpInst::ICMP_UGT:
16038 case CmpInst::ICMP_UGE:
16039 To = SE.getUMaxExpr(FromRewritten, RHS);
16040 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16041 EnqueueOperands(UMin);
16042 break;
16043 case CmpInst::ICMP_SGT:
16044 case CmpInst::ICMP_SGE:
16045 To = SE.getSMaxExpr(FromRewritten, RHS);
16046 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16047 EnqueueOperands(SMin);
16048 break;
16049 case CmpInst::ICMP_EQ:
16051 To = RHS;
16052 break;
16053 case CmpInst::ICMP_NE:
16054 if (match(RHS, m_scev_Zero())) {
16055 const SCEV *OneAlignedUp =
16056 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16057 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16058 } else {
16059 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16060 // but creating the subtraction eagerly is expensive. Track the
16061 // inequalities in a separate map, and materialize the rewrite lazily
16062 // when encountering a suitable subtraction while re-writing.
16063 if (LHS->getType()->isPointerTy()) {
16064 LHS = SE.getPtrToAddrExpr(LHS);
16065 RHS = SE.getPtrToAddrExpr(RHS);
16067 break;
16068 }
16069 const SCEVConstant *C;
16070 const SCEV *A, *B;
16073 RHS = A;
16074 LHS = B;
16075 }
16076 if (LHS > RHS)
16077 std::swap(LHS, RHS);
16078 Guards.NotEqual.insert({LHS, RHS});
16079 continue;
16080 }
16081 break;
16082 default:
16083 break;
16084 }
16085
16086 if (To)
16087 AddRewrite(From, FromRewritten, To);
16088 }
16089 };
16090
16092 // First, collect information from assumptions dominating the loop.
16093 for (auto &AssumeVH : SE.AC.assumptions()) {
16094 if (!AssumeVH)
16095 continue;
16096 auto *AssumeI = cast<CallInst>(AssumeVH);
16097 if (!SE.DT.dominates(AssumeI, Block))
16098 continue;
16099 Terms.emplace_back(AssumeI->getOperand(0), true);
16100 }
16101
16102 // Second, collect information from llvm.experimental.guards dominating the loop.
16103 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16104 SE.F.getParent(), Intrinsic::experimental_guard);
16105 if (GuardDecl)
16106 for (const auto *GU : GuardDecl->users())
16107 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16108 if (Guard->getFunction() == Block->getParent() &&
16109 SE.DT.dominates(Guard, Block))
16110 Terms.emplace_back(Guard->getArgOperand(0), true);
16111
16112 // Third, collect conditions from dominating branches. Starting at the loop
16113 // predecessor, climb up the predecessor chain, as long as there are
16114 // predecessors that can be found that have unique successors leading to the
16115 // original header.
16116 // TODO: share this logic with isLoopEntryGuardedByCond.
16117 unsigned NumCollectedConditions = 0;
16119 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16120 for (; Pair.first;
16121 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16122 VisitedBlocks.insert(Pair.second);
16123 const CondBrInst *LoopEntryPredicate =
16124 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16125 if (!LoopEntryPredicate)
16126 continue;
16127
16128 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16129 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16130 NumCollectedConditions++;
16131
16132 // If we are recursively collecting guards stop after 2
16133 // conditions to limit compile-time impact for now.
16134 if (Depth > 0 && NumCollectedConditions == 2)
16135 break;
16136 }
16137 // Finally, if we stopped climbing the predecessor chain because
16138 // there wasn't a unique one to continue, try to collect conditions
16139 // for PHINodes by recursively following all of their incoming
16140 // blocks and try to merge the found conditions to build a new one
16141 // for the Phi.
16142 if (Pair.second->hasNPredecessorsOrMore(2) &&
16144 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16145 for (auto &Phi : Pair.second->phis())
16146 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16147 }
16148
16149 // Now apply the information from the collected conditions to
16150 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16151 // earliest conditions is processed first, except guards with divisibility
16152 // information, which are moved to the back. This ensures the SCEVs with the
16153 // shortest dependency chains are constructed first.
16155 GuardsToProcess;
16156 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16157 SmallVector<Value *, 8> Worklist;
16158 SmallPtrSet<Value *, 8> Visited;
16159 Worklist.push_back(Term);
16160 while (!Worklist.empty()) {
16161 Value *Cond = Worklist.pop_back_val();
16162 if (!Visited.insert(Cond).second)
16163 continue;
16164
16165 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16166 auto Predicate =
16167 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16168 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16169 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16170 // If LHS is a constant, apply information to the other expression.
16171 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16172 // can improve results.
16173 if (isa<SCEVConstant>(LHS)) {
16174 std::swap(LHS, RHS);
16176 }
16177 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16178 continue;
16179 }
16180
16181 Value *L, *R;
16182 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16183 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16184 Worklist.push_back(L);
16185 Worklist.push_back(R);
16186 }
16187 }
16188 }
16189
16190 // Process divisibility guards in reverse order to populate DivGuards early.
16191 DenseMap<const SCEV *, APInt> Multiples;
16192 LoopGuards DivGuards(SE);
16193 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16194 if (!isDivisibilityGuard(LHS, RHS, SE))
16195 continue;
16196 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16197 Multiples, SE);
16198 }
16199
16200 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16201 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16202
16203 // Apply divisibility information last. This ensures it is applied to the
16204 // outermost expression after other rewrites for the given value.
16205 for (const auto &[K, Divisor] : Multiples) {
16206 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16207 Guards.RewriteMap[K] =
16209 Guards.rewrite(K), Divisor, SE),
16210 DivisorSCEV),
16211 DivisorSCEV);
16212 ExprsToRewrite.push_back(K);
16213 }
16214
16215 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16216 // the replacement expressions are contained in the ranges of the replaced
16217 // expressions.
16218 Guards.PreserveNUW = true;
16219 Guards.PreserveNSW = true;
16220 for (const SCEV *Expr : ExprsToRewrite) {
16221 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16222 Guards.PreserveNUW &=
16223 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16224 Guards.PreserveNSW &=
16225 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16226 }
16227
16228 // Now that all rewrite information is collect, rewrite the collected
16229 // expressions with the information in the map. This applies information to
16230 // sub-expressions.
16231 if (ExprsToRewrite.size() > 1) {
16232 for (const SCEV *Expr : ExprsToRewrite) {
16233 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16234 Guards.RewriteMap.erase(Expr);
16235 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16236 }
16237 }
16238}
16239
16241 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16242 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16243 /// replacement is loop invariant in the loop of the AddRec.
16244 class SCEVLoopGuardRewriter
16245 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16248
16250
16251 public:
16252 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16253 const ScalarEvolution::LoopGuards &Guards)
16254 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16255 NotEqual(Guards.NotEqual) {
16256 if (Guards.PreserveNUW)
16257 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16258 if (Guards.PreserveNSW)
16259 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16260 }
16261
16262 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16263
16264 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16265 return Map.lookup_or(Expr, Expr);
16266 }
16267
16268 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16269 if (const SCEV *S = Map.lookup(Expr))
16270 return S;
16271
16272 // If we didn't find the extact ZExt expr in the map, check if there's
16273 // an entry for a smaller ZExt we can use instead.
16274 Type *Ty = Expr->getType();
16275 const SCEV *Op = Expr->getOperand(0);
16276 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16277 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16278 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16279 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16280 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16281 if (const SCEV *S = Map.lookup(NarrowExt))
16282 return SE.getZeroExtendExpr(S, Ty);
16283 Bitwidth = Bitwidth / 2;
16284 }
16285
16287 Expr);
16288 }
16289
16290 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16291 if (const SCEV *S = Map.lookup(Expr))
16292 return S;
16294 Expr);
16295 }
16296
16297 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16298 if (const SCEV *S = Map.lookup(Expr))
16299 return S;
16301 }
16302
16303 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16304 if (const SCEV *S = Map.lookup(Expr))
16305 return S;
16307 }
16308
16309 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16310 if (const SCEV *S = Map.lookup(Expr))
16311 return S;
16312
16313 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16314 // return UMax(S, 1).
16315 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16316 SCEVUse LHS, RHS;
16317 if (MatchBinarySub(S, LHS, RHS)) {
16318 if (LHS > RHS)
16319 std::swap(LHS, RHS);
16320 if (NotEqual.contains({LHS, RHS})) {
16321 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16322 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16323 return SE.getUMaxExpr(OneAlignedUp, S);
16324 }
16325 }
16326 return nullptr;
16327 };
16328
16329 // Check if Expr itself is a subtraction pattern with guard info.
16330 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16331 return Rewritten;
16332
16333 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16334 // (Const + A + B). There may be guard info for A + B, and if so, apply
16335 // it.
16336 // TODO: Could more generally apply guards to Add sub-expressions.
16337 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16338 if (Expr->getNumOperands() == 3) {
16339 const SCEV *Add =
16340 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16341 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16342 return SE.getAddExpr(
16343 Expr->getOperand(0), Rewritten,
16344 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16345 if (const SCEV *S = Map.lookup(Add))
16346 return SE.getAddExpr(Expr->getOperand(0), S);
16347 }
16348
16349 // For expressions of the form (Const + A), check if we have guard info
16350 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16351 // sure we don't lose information when rewriting expressions based on
16352 // back-edge taken counts in some cases.
16353 if (Expr->getNumOperands() == 2) {
16354 const SCEV *S = nullptr;
16355 // Handle (-1 + 1 + A) without constructing SCEVs.
16356 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16357 S = Map.lookup(Expr->getOperand(1));
16358 } else {
16359 const SCEV *NewC =
16360 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16361 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16362 }
16363 if (S)
16364 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16365 }
16366 }
16368 bool Changed = false;
16369 for (SCEVUse Op : Expr->operands()) {
16370 Operands.push_back(
16372 Changed |= Op != Operands.back();
16373 }
16374 // We are only replacing operands with equivalent values, so transfer the
16375 // flags from the original expression.
16376 return !Changed ? Expr
16377 : SE.getAddExpr(Operands,
16379 Expr->getNoWrapFlags(), FlagMask));
16380 }
16381
16382 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16384 bool Changed = false;
16385 for (SCEVUse Op : Expr->operands()) {
16386 Operands.push_back(
16388 Changed |= Op != Operands.back();
16389 }
16390 // We are only replacing operands with equivalent values, so transfer the
16391 // flags from the original expression.
16392 return !Changed ? Expr
16393 : SE.getMulExpr(Operands,
16395 Expr->getNoWrapFlags(), FlagMask));
16396 }
16397 };
16398
16399 if (RewriteMap.empty() && NotEqual.empty())
16400 return Expr;
16401
16402 SCEVLoopGuardRewriter Rewriter(SE, *this);
16403 return Rewriter.visit(Expr);
16404}
16405
16406const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16407 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16408}
16409
16411 const LoopGuards &Guards) {
16412 return Guards.rewrite(Expr);
16413}
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 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 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)
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 APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
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 class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:168
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:211
void AddInteger(signed I)
Definition FoldingSet.h:240
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.
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:67
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 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 * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
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 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 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 isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > &Assumptions)
Check that S is a multiple of M.
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
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
Definition SmallPtrSet.h:99
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:578
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
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.
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.
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:
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.