LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
185 cl::init(2));
186
188 "scalar-evolution-max-value-compare-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive value complexity comparisons"),
190 cl::init(2));
191
193 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive arithmetics"),
195 cl::init(32));
196
198 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
200
202 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
203 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
204 cl::init(8));
205
207 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
208 cl::desc("Max coefficients in AddRec during evolving"),
209 cl::init(8));
210
212 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
213 cl::desc("Size of the expression which is considered huge"),
214 cl::init(4096));
215
217 "scev-range-iter-threshold", cl::Hidden,
218 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
219 cl::init(32));
220
222 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
223 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
224
226 "scalar-evolution-max-guard-dom-tree-steps", cl::Hidden,
227 cl::desc("Maximum number of immediate dominator steps taken when "
228 "collecting loop guards"),
229 cl::init(8));
230
231static cl::opt<bool>
232ClassifyExpressions("scalar-evolution-classify-expressions",
233 cl::Hidden, cl::init(true),
234 cl::desc("When printing analysis, include information on every instruction"));
235
237 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
238 cl::init(false),
239 cl::desc("Use more powerful methods of sharpening expression ranges. May "
240 "be costly in terms of compile time"));
241
242static cl::opt<bool>
243 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
244 cl::desc("Handle <= and >= in finite loops"),
245 cl::init(true));
246
248 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
249 cl::desc("Infer nuw/nsw flags using context where suitable"),
250 cl::init(true));
251
252//===----------------------------------------------------------------------===//
253// SCEV class definitions
254//===----------------------------------------------------------------------===//
255
257 // Leaf nodes are always their own canonical.
258 switch (getSCEVType()) {
259 case scConstant:
260 case scVScale:
261 case scUnknown:
262 CanonicalSCEV = this;
263 return;
264 default:
265 break;
266 }
267
268 // For all other expressions, check whether any immediate operand has a
269 // different canonical. Since operands are always created before their parent,
270 // their canonical pointers are already set — no recursion needed.
271 if (all_of(operands(), [](SCEVUse Op) { return Op.isCanonical(); })) {
272 CanonicalSCEV = this;
273 return;
274 }
275
277 map_range(operands(), [](SCEVUse Op) { return Op.getCanonical(); }));
278 // Rebuild the expression from the canonical operands, stripping use flags.
279 CanonicalSCEV = SE.getWithOperands(this, CanonOps);
280}
281
282//===----------------------------------------------------------------------===//
283// Implementation of the SCEV class.
284//
285
286#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
288 print(dbgs());
289 dbgs() << '\n';
290}
291#endif
292
293void SCEV::print(raw_ostream &OS) const {
294 switch (getSCEVType()) {
295 case scConstant:
296 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
297 return;
298 case scVScale:
299 OS << "vscale";
300 return;
301 case scPtrToAddr: {
302 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
303 SCEVUse Op = PtrCast->getOperand();
304 OS << "(ptrtoaddr " << *Op->getType() << " " << Op << " to "
305 << *PtrCast->getType() << ")";
306 return;
307 }
308 case scTruncate: {
309 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
310 SCEVUse Op = Trunc->getOperand();
311 OS << "(trunc " << *Op->getType() << " " << Op << " to "
312 << *Trunc->getType() << ")";
313 return;
314 }
315 case scZeroExtend: {
317 SCEVUse Op = ZExt->getOperand();
318 OS << "(zext " << *Op->getType() << " " << Op << " to " << *ZExt->getType()
319 << ")";
320 return;
321 }
322 case scSignExtend: {
324 SCEVUse Op = SExt->getOperand();
325 OS << "(sext " << *Op->getType() << " " << Op << " to " << *SExt->getType()
326 << ")";
327 return;
328 }
329 case scAddRecExpr: {
330 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
331 OS << "{" << AR->getOperand(0);
332 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
333 OS << ",+," << AR->getOperand(i);
334 OS << "}<";
335 if (AR->hasNoUnsignedWrap())
336 OS << "nuw><";
337 if (AR->hasNoSignedWrap())
338 OS << "nsw><";
339 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
340 !AR->hasNoSignedWrap())
341 OS << "nw><";
342 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
343 OS << ">";
344 return;
345 }
346 case scAddExpr:
347 case scMulExpr:
348 case scUMaxExpr:
349 case scSMaxExpr:
350 case scUMinExpr:
351 case scSMinExpr:
353 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
354 const char *OpStr = nullptr;
355 switch (NAry->getSCEVType()) {
356 case scAddExpr: OpStr = " + "; break;
357 case scMulExpr: OpStr = " * "; break;
358 case scUMaxExpr: OpStr = " umax "; break;
359 case scSMaxExpr: OpStr = " smax "; break;
360 case scUMinExpr:
361 OpStr = " umin ";
362 break;
363 case scSMinExpr:
364 OpStr = " smin ";
365 break;
367 OpStr = " umin_seq ";
368 break;
369 default:
370 llvm_unreachable("There are no other nary expression types.");
371 }
372 OS << "(" << llvm::interleaved(NAry->operands(), OpStr) << ")";
373 switch (NAry->getSCEVType()) {
374 case scAddExpr:
375 case scMulExpr:
376 if (NAry->hasNoUnsignedWrap())
377 OS << "<nuw>";
378 if (NAry->hasNoSignedWrap())
379 OS << "<nsw>";
380 break;
381 default:
382 // Nothing to print for other nary expressions.
383 break;
384 }
385 return;
386 }
387 case scUDivExpr: {
388 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
389 OS << "(" << UDiv->getLHS() << " /u " << UDiv->getRHS() << ")";
390 return;
391 }
392 case scUnknown:
393 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
394 return;
396 OS << "***COULDNOTCOMPUTE***";
397 return;
398 }
399 llvm_unreachable("Unknown SCEV kind!");
400}
401
403 switch (getSCEVType()) {
404 case scConstant:
405 case scVScale:
406 case scUnknown:
407 return {};
408 case scPtrToAddr:
409 case scTruncate:
410 case scZeroExtend:
411 case scSignExtend:
412 return cast<SCEVCastExpr>(this)->operands();
413 case scAddRecExpr:
414 case scAddExpr:
415 case scMulExpr:
416 case scUMaxExpr:
417 case scSMaxExpr:
418 case scUMinExpr:
419 case scSMinExpr:
421 return cast<SCEVNAryExpr>(this)->operands();
422 case scUDivExpr:
423 return cast<SCEVUDivExpr>(this)->operands();
425 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
426 }
427 llvm_unreachable("Unknown SCEV kind!");
428}
429
430bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
431
432bool SCEV::isOne() const { return match(this, m_scev_One()); }
433
434bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
435
438 if (!Mul) return false;
439
440 // If there is a constant factor, it will be first.
441 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
442 if (!SC) return false;
443
444 // Return true if the value is negative, this matches things like (-42 * V).
445 return SC->getAPInt().isNegative();
446}
447
450
452 return S->getSCEVType() == scCouldNotCompute;
453}
454
456 auto &Entry = ConstantSCEVs[V];
457 if (Entry)
458 return Entry;
459
462 ID.AddPointer(V);
464 if (SCEVConstant *S =
465 static_cast<SCEVConstant *>(UniqueSCEVs.lookup(ID, Token)))
466 return Entry = S;
467 SCEVConstant *S =
468 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
469 UniqueSCEVs.insert(S, Token);
470 S->computeAndSetCanonical(*this);
471 return Entry = S;
472}
473
475 return getConstant(ConstantInt::get(getContext(), Val));
476}
477
478const SCEV *
481 // TODO: Avoid implicit trunc?
482 // See https://github.com/llvm/llvm-project/issues/112510.
483 return getConstant(
484 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
485}
486
490 ID.AddPointer(Ty);
492 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
493 return S;
494 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
495 UniqueSCEVs.insert(S, Token);
496 S->computeAndSetCanonical(*this);
497 return S;
498}
499
501 SCEVFlags Flags) {
502 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
503 if (EC.isScalable())
504 Res = getMulExpr(Res, getVScale(Ty), Flags);
505 return Res;
506}
507
509 SCEVUse op, Type *ty)
510 : SCEV(ID, SCEVTy, computeExpressionSize(op), ty), Op(op) {}
511
512SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
513 const SCEV *Op, Type *ITy)
514 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
515 assert(getOperand()->getType()->isPointerTy() && getType()->isIntegerTy() &&
516 "Must be a non-bit-width-changing pointer-to-integer cast!");
517}
518
523
524SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
525 Type *ty)
527 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
528 "Cannot truncate non-integer value!");
529}
530
531SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
532 Type *ty)
534 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
535 "Cannot zero extend non-integer value!");
536}
537
538SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
539 Type *ty)
541 assert(getOperand()->getType()->isIntOrPtrTy() && getType()->isIntOrPtrTy() &&
542 "Cannot sign extend non-integer value!");
543}
544
546 // Clear this SCEVUnknown from various maps.
547 SE->forgetMemoizedResults({this});
548
549 // Remove this SCEVUnknown from the uniquing map.
550 SE->UniqueSCEVs.erase(this);
551
552 // Release the value.
553 setValPtr(nullptr);
554}
555
556void SCEVUnknown::allUsesReplacedWith(Value *New) {
557 // Clear this SCEVUnknown from various maps.
558 SE->forgetMemoizedResults({this});
559
560 // Remove this SCEVUnknown from the uniquing map.
561 SE->UniqueSCEVs.erase(this);
562
563 // Replace the value pointer in case someone is still using this SCEVUnknown.
564 setValPtr(New);
565}
566
567//===----------------------------------------------------------------------===//
568// SCEV Utilities
569//===----------------------------------------------------------------------===//
570
571/// Compare the two values \p LV and \p RV in terms of their "complexity" where
572/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
573/// operands in SCEV expressions.
574static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
575 Value *RV, unsigned Depth) {
577 return 0;
578
579 // Order pointer values after integer values. This helps SCEVExpander form
580 // GEPs.
581 bool LIsPointer = LV->getType()->isPointerTy(),
582 RIsPointer = RV->getType()->isPointerTy();
583 if (LIsPointer != RIsPointer)
584 return (int)LIsPointer - (int)RIsPointer;
585
586 // Compare getValueID values.
587 unsigned LID = LV->getValueID(), RID = RV->getValueID();
588 if (LID != RID)
589 return (int)LID - (int)RID;
590
591 // Sort arguments by their position.
592 if (const auto *LA = dyn_cast<Argument>(LV)) {
593 const auto *RA = cast<Argument>(RV);
594 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
595 return (int)LArgNo - (int)RArgNo;
596 }
597
598 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
599 const auto *RGV = cast<GlobalValue>(RV);
600
601 if (auto L = LGV->getLinkage() - RGV->getLinkage())
602 return L;
603
604 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
605 auto LT = GV->getLinkage();
606 return !(GlobalValue::isPrivateLinkage(LT) ||
608 };
609
610 // Use the names to distinguish the two values, but only if the
611 // names are semantically important.
612 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
613 return LGV->getName().compare(RGV->getName());
614 }
615
616 // For instructions, compare their loop depth, and their operand count. This
617 // is pretty loose.
618 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
619 const auto *RInst = cast<Instruction>(RV);
620
621 // Compare loop depths.
622 const BasicBlock *LParent = LInst->getParent(),
623 *RParent = RInst->getParent();
624 if (LParent != RParent) {
625 unsigned LDepth = LI->getLoopDepth(LParent),
626 RDepth = LI->getLoopDepth(RParent);
627 if (LDepth != RDepth)
628 return (int)LDepth - (int)RDepth;
629 }
630
631 // Compare the number of operands.
632 unsigned LNumOps = LInst->getNumOperands(),
633 RNumOps = RInst->getNumOperands();
634 if (LNumOps != RNumOps)
635 return (int)LNumOps - (int)RNumOps;
636
637 for (unsigned Idx : seq(LNumOps)) {
638 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
639 RInst->getOperand(Idx), Depth + 1);
640 if (Result != 0)
641 return Result;
642 }
643 }
644
645 return 0;
646}
647
648// Return negative, zero, or positive, if LHS is less than, equal to, or greater
649// than RHS, respectively. A three-way result allows recursive comparisons to be
650// more efficient. The result is a total order.
651static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS,
653 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
654 if (LHS == RHS)
655 return 0;
656
657 if (LHS.getPointer() == RHS.getPointer())
658 return (int)LHS.getUseNoWrapFlags() - (int)RHS.getUseNoWrapFlags();
659
660 // Primarily, sort the SCEVs by their getSCEVType().
661 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
662 if (LType != RType)
663 return (int)LType - (int)RType;
664
665 // Aside from the getSCEVType() ordering, the particular ordering
666 // isn't very important except that it's beneficial to be consistent,
667 // so that (a + b) and (b + a) don't end up as different expressions.
668 switch (LType) {
669 case scUnknown: {
670 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
671 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
672
673 if (int X = CompareValueComplexity(LI, LU->getValue(), RU->getValue(),
674 /*Depth=*/0))
675 return X;
676 return LU->getOrderID() < RU->getOrderID() ? -1 : 1;
677 }
678
679 case scConstant: {
682
683 // Compare constant values.
684 const APInt &LA = LC->getAPInt();
685 const APInt &RA = RC->getAPInt();
686 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
687 if (LBitWidth != RBitWidth)
688 return (int)LBitWidth - (int)RBitWidth;
689 return LA.ult(RA) ? -1 : 1;
690 }
691
692 case scVScale: {
693 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
694 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
695 return LTy->getBitWidth() - RTy->getBitWidth();
696 }
697
698 case scAddRecExpr: {
701
702 // There is always a dominance between two recs that are used by one SCEV,
703 // so we can safely sort recs by loop header dominance. We require such
704 // order in getAddExpr.
705 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
706 if (LLoop != RLoop) {
707 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
708 assert(LHead != RHead && "Two loops share the same header?");
709 if (DT.dominates(LHead, RHead))
710 return 1;
711 assert(DT.dominates(RHead, LHead) &&
712 "No dominance between recurrences used by one SCEV?");
713 return -1;
714 }
715
716 [[fallthrough]];
717 }
718
719 case scTruncate:
720 case scZeroExtend:
721 case scSignExtend:
722 case scPtrToAddr:
723 case scAddExpr:
724 case scMulExpr:
725 case scUDivExpr:
726 case scSMaxExpr:
727 case scUMaxExpr:
728 case scSMinExpr:
729 case scUMinExpr:
731 ArrayRef<SCEVUse> LOps = LHS->operands();
732 ArrayRef<SCEVUse> ROps = RHS->operands();
733
734 // Lexicographically compare n-ary-like expressions.
735 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
736 if (LNumOps != RNumOps)
737 return (int)LNumOps - (int)RNumOps;
738
739 for (unsigned i = 0; i != LNumOps; ++i) {
740 auto X = CompareSCEVComplexity(LI, LOps[i], ROps[i], DT);
741 if (X != 0)
742 return X;
743 }
744
745 assert(isa<SCEVCastExpr>(LHS) && "distinct SCEVs compare equal");
746 unsigned LBitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
747 unsigned RBitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
748 assert(LBitWidth != RBitWidth && "distinct SCEVs compare equal");
749 return (int)LBitWidth - (int)RBitWidth;
750 }
751
753 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
754 }
755 llvm_unreachable("Unknown SCEV kind!");
756}
757
758/// Given a list of SCEV objects, order them by their complexity, and group
759/// objects of the same complexity together by value. When this routine is
760/// finished, we know that any duplicates in the vector are consecutive and that
761/// complexity is monotonically increasing.
762///
763/// Note that we go take special precautions to ensure that we get deterministic
764/// results from this routine. In other words, we don't want the results of
765/// this to depend on where the addresses of various SCEV objects happened to
766/// land in memory.
768 DominatorTree &DT) {
769 if (Ops.size() < 2) return; // Noop
770
771 // Whether LHS has provably less complexity than RHS.
772 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
773 return CompareSCEVComplexity(LI, LHS, RHS, DT) < 0;
774 };
775 if (Ops.size() == 2) {
776 // This is the common case, which also happens to be trivially simple.
777 // Special case it.
778 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
779 if (IsLessComplex(RHS, LHS))
780 std::swap(LHS, RHS);
781 return;
782 }
783
784 llvm::sort(Ops, IsLessComplex);
785}
786
787/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
788/// least HugeExprThreshold nodes).
790 return any_of(Ops, [](const SCEV *S) {
792 });
793}
794
795/// Performs a number of common optimizations on the passed \p Ops. If the
796/// whole expression reduces down to a single operand, it will be returned.
797///
798/// The following optimizations are performed:
799/// * Fold constants using the \p Fold function.
800/// * Remove identity constants satisfying \p IsIdentity.
801/// * If a constant satisfies \p IsAbsorber, return it.
802/// * Sort operands by complexity.
803template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
804static const SCEV *
806 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
807 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
808 const SCEVConstant *Folded = nullptr;
809 for (unsigned Idx = 0; Idx < Ops.size();) {
810 const SCEV *Op = Ops[Idx];
811 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
812 if (!Folded)
813 Folded = C;
814 else
815 Folded = cast<SCEVConstant>(
816 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
817 Ops.erase(Ops.begin() + Idx);
818 continue;
819 }
820 ++Idx;
821 }
822
823 if (Ops.empty()) {
824 assert(Folded && "Must have folded value");
825 return Folded;
826 }
827
828 if (Folded && IsAbsorber(Folded->getAPInt()))
829 return Folded;
830
831 GroupByComplexity(Ops, &LI, DT);
832 if (Folded && !IsIdentity(Folded->getAPInt()))
833 Ops.insert(Ops.begin(), Folded);
834
835 return Ops.size() == 1 ? Ops[0] : nullptr;
836}
837
838//===----------------------------------------------------------------------===//
839// Simple SCEV method implementations
840//===----------------------------------------------------------------------===//
841
842/// Compute BC(It, K). The result has width W. Assume, K > 0.
843static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
844 ScalarEvolution &SE,
845 Type *ResultTy) {
846 // Handle the simplest case efficiently.
847 if (K == 1)
848 return SE.getTruncateOrZeroExtend(It, ResultTy);
849
850 // We are using the following formula for BC(It, K):
851 //
852 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
853 //
854 // Suppose, W is the bitwidth of the return value. We must be prepared for
855 // overflow. Hence, we must assure that the result of our computation is
856 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
857 // safe in modular arithmetic.
858 //
859 // However, this code doesn't use exactly that formula; the formula it uses
860 // is something like the following, where T is the number of factors of 2 in
861 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
862 // exponentiation:
863 //
864 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
865 //
866 // This formula is trivially equivalent to the previous formula. However,
867 // this formula can be implemented much more efficiently. The trick is that
868 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
869 // arithmetic. To do exact division in modular arithmetic, all we have
870 // to do is multiply by the inverse. Therefore, this step can be done at
871 // width W.
872 //
873 // The next issue is how to safely do the division by 2^T. The way this
874 // is done is by doing the multiplication step at a width of at least W + T
875 // bits. This way, the bottom W+T bits of the product are accurate. Then,
876 // when we perform the division by 2^T (which is equivalent to a right shift
877 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
878 // truncated out after the division by 2^T.
879 //
880 // In comparison to just directly using the first formula, this technique
881 // is much more efficient; using the first formula requires W * K bits,
882 // but this formula less than W + K bits. Also, the first formula requires
883 // a division step, whereas this formula only requires multiplies and shifts.
884 //
885 // It doesn't matter whether the subtraction step is done in the calculation
886 // width or the input iteration count's width; if the subtraction overflows,
887 // the result must be zero anyway. We prefer here to do it in the width of
888 // the induction variable because it helps a lot for certain cases; CodeGen
889 // isn't smart enough to ignore the overflow, which leads to much less
890 // efficient code if the width of the subtraction is wider than the native
891 // register width.
892 //
893 // (It's possible to not widen at all by pulling out factors of 2 before
894 // the multiplication; for example, K=2 can be calculated as
895 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
896 // extra arithmetic, so it's not an obvious win, and it gets
897 // much more complicated for K > 3.)
898
899 // Protection from insane SCEVs; this bound is conservative,
900 // but it probably doesn't matter.
901 if (K > 1000)
902 return SE.getCouldNotCompute();
903
904 unsigned W = SE.getTypeSizeInBits(ResultTy);
905
906 // Calculate K! / 2^T and T; we divide out the factors of two before
907 // multiplying for calculating K! / 2^T to avoid overflow.
908 // Other overflow doesn't matter because we only care about the bottom
909 // W bits of the result.
910 APInt OddFactorial(W, 1);
911 unsigned T = 1;
912 for (unsigned i = 3; i <= K; ++i) {
913 unsigned TwoFactors = countr_zero(i);
914 T += TwoFactors;
915 OddFactorial *= (i >> TwoFactors);
916 }
917
918 // We need at least W + T bits for the multiplication step
919 unsigned CalculationBits = W + T;
920
921 // Calculate 2^T, at width T+W.
922 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
923
924 // Calculate the multiplicative inverse of K! / 2^T;
925 // this multiplication factor will perform the exact division by
926 // K! / 2^T.
927 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
928
929 // Calculate the product, at width T+W
930 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
931 CalculationBits);
932 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
933 for (unsigned i = 1; i != K; ++i) {
934 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
935 Dividend = SE.getMulExpr(Dividend,
936 SE.getTruncateOrZeroExtend(S, CalculationTy));
937 }
938
939 // Divide by 2^T
940 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
941
942 // Truncate the result, and divide by K! / 2^T.
943
944 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
945 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
946}
947
948/// Return the value of this chain of recurrences at the specified iteration
949/// number. We can evaluate this recurrence by multiplying each element in the
950/// chain by the binomial coefficient corresponding to it. In other words, we
951/// can evaluate {A,+,B,+,C,+,D} as:
952///
953/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
954///
955/// where BC(It, k) stands for binomial coefficient.
957 ScalarEvolution &SE) const {
958 return evaluateAtIteration(operands(), It, SE);
959}
960
962 const SCEV *It, ScalarEvolution &SE,
963 SCEVFlags UseFlags) {
964 assert(Operands.size() > 0);
965 assert((Operands.size() == 2 || UseFlags == SCEV::FlagNone) &&
966 "use-specific flags only supported for affine AddRecs");
967 SCEVUse Result = Operands[0].getPointer();
968 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
969 // The computation is correct in the face of overflow provided that the
970 // multiplication is performed _after_ the evaluation of the binomial
971 // coefficient.
972 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
973 if (isa<SCEVCouldNotCompute>(Coeff))
974 return Coeff;
975
976 SCEVUse Mul = SE.getMulExpr(Operands[i].getPointer(), Coeff,
977 {SCEV::FlagNone, UseFlags});
978 Result = SE.getAddExpr(Result, Mul, {SCEV::FlagNone, UseFlags});
979 }
980 return Result;
981}
982
984 const SCEV *BTC = SE.getBackedgeTakenCount(getLoop());
986 return BTC;
987 // The loop reaches iteration BTC, so the value this recurrence computes there
988 // is the value it had, and that did not wrap.
989 return evaluateAtIteration(operands(), BTC, SE,
992}
993
994//===----------------------------------------------------------------------===//
995// SCEV Expression folder implementations
996//===----------------------------------------------------------------------===//
997
998/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
999/// which computes a pointer-typed value, and rewrites the whole expression
1000/// tree so that *all* the computations are done on integers, and the only
1001/// pointer-typed operands in the expression are SCEVUnknown.
1002/// The CreatePtrCast callback is invoked to create the actual conversion
1003/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1005 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1007 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1008 Type *TargetTy;
1009 ConversionFn CreatePtrCast;
1010
1011public:
1013 ConversionFn CreatePtrCast)
1014 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1015
1016 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1017 Type *TargetTy, ConversionFn CreatePtrCast) {
1018 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1019 return Rewriter.visit(Scev);
1020 }
1021
1022 const SCEV *visit(const SCEV *S) {
1023 Type *STy = S->getType();
1024 // If the expression is not pointer-typed, just keep it as-is.
1025 if (!STy->isPointerTy())
1026 return S;
1027 // Else, recursively sink the cast down into it.
1028 return Base::visit(S);
1029 }
1030
1031 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1032 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1033 // implementation drops.
1035 bool Changed = false;
1036 for (SCEVUse Op : Expr->operands()) {
1037 Operands.push_back(visit(Op.getPointer()));
1038 Changed |= Op.getPointer() != Operands.back();
1039 }
1040 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1041 }
1042
1043 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1044 assert(Expr->getType()->isPointerTy() &&
1045 "Should only reach pointer-typed SCEVUnknown's.");
1046 // Perform some basic constant folding. If the operand of the cast is a
1047 // null pointer, don't create a cast SCEV expression (that will be left
1048 // as-is), but produce a zero constant.
1050 return SE.getZero(TargetTy);
1051 return CreatePtrCast(Expr);
1052 }
1053};
1054
1056 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1057
1058 // Treat pointers with unstable representation conservatively, since the
1059 // address bits may change.
1060 if (DL.hasUnstableRepresentation(Op->getType()))
1061 return getCouldNotCompute();
1062
1063 Type *Ty = DL.getAddressType(Op->getType());
1064
1065 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1066 // The rewriter handles null pointer constant folding.
1068 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1071 ID.AddPointer(U);
1072 ID.AddPointer(Ty);
1074 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1075 return S;
1076 SCEV *S = new (SCEVAllocator)
1077 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1078 UniqueSCEVs.insert(S, Token);
1079 S->computeAndSetCanonical(*this);
1080 registerUser(S, {U});
1081 return static_cast<const SCEV *>(S);
1082 });
1083 assert(IntOp->getType()->isIntegerTy() &&
1084 "We must have succeeded in sinking the cast, "
1085 "and ending up with an integer-typed expression!");
1086 return IntOp;
1087}
1088
1090 unsigned Depth) {
1091 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1092 "This is not a truncating conversion!");
1093 assert(isSCEVable(Ty) &&
1094 "This is not a conversion to a SCEVable type!");
1095 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1096 Ty = getEffectiveSCEVType(Ty);
1097
1100 ID.AddPointer(Op.getOpaqueValue());
1101 ID.AddPointer(Ty);
1103 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1104 return S;
1105
1106 // Fold if the operand is constant.
1107 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1108 return getConstant(
1109 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1110
1111 // trunc(trunc(x)) --> trunc(x)
1113 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1114
1115 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1117 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1118
1119 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1121 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1122
1123 if (Depth > MaxCastDepth) {
1124 SCEV *S =
1125 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1126 UniqueSCEVs.insert(S, Token);
1127 S->computeAndSetCanonical(*this);
1128 registerUser(S, Op);
1129 return S;
1130 }
1131
1132 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1133 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1134 // if after transforming we have at most one truncate, not counting truncates
1135 // that replace other casts.
1137 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1139 unsigned numTruncs = 0;
1140 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1141 ++i) {
1142 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1143 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1145 numTruncs++;
1146 Operands.push_back(S);
1147 }
1148 if (numTruncs < 2) {
1149 if (isa<SCEVAddExpr>(Op))
1150 return getAddExpr(Operands);
1151 if (isa<SCEVMulExpr>(Op))
1152 return getMulExpr(Operands);
1153 llvm_unreachable("Unexpected SCEV type for Op.");
1154 }
1155 // Although we checked in the beginning that ID is not in the cache, it is
1156 // possible that during recursion and different modification ID was inserted
1157 // into the cache. So if we find it, just return it.
1158 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1159 return S;
1160 }
1161
1162 // If the input value is a chrec scev, truncate the chrec's operands.
1163 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1165 for (const SCEV *Op : AddRec->operands())
1166 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1167 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagNone);
1168 }
1169
1170 // Return zero if truncating to known zeros.
1171 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1172 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1173 return getZero(Ty);
1174
1175 // The cast wasn't folded; create an explicit cast node. We can reuse
1176 // the existing insert position since if we get here, we won't have
1177 // made any changes which would invalidate it.
1178 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1179 Op, Ty);
1180 UniqueSCEVs.insert(S, Token);
1181 S->computeAndSetCanonical(*this);
1182 registerUser(S, Op);
1183 return S;
1184}
1185
1186// Get the limit of a recurrence such that incrementing by Step cannot cause
1187// signed overflow as long as the value of the recurrence within the
1188// loop does not exceed this limit before incrementing.
1189static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1190 ICmpInst::Predicate *Pred,
1191 ScalarEvolution *SE) {
1192 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1193 if (SE->isKnownPositive(Step)) {
1194 *Pred = ICmpInst::ICMP_SLT;
1196 SE->getSignedRangeMax(Step));
1197 }
1198 if (SE->isKnownNegative(Step)) {
1199 *Pred = ICmpInst::ICMP_SGT;
1201 SE->getSignedRangeMin(Step));
1202 }
1203 return nullptr;
1204}
1205
1206// Get the limit of a recurrence such that incrementing by Step cannot cause
1207// unsigned overflow as long as the value of the recurrence within the loop does
1208// not exceed this limit before incrementing.
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1213 *Pred = ICmpInst::ICMP_ULT;
1214
1216 SE->getUnsignedRangeMax(Step));
1217}
1218
1219namespace {
1220
1221struct ExtendOpTraitsBase {
1222 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
1223 unsigned);
1224};
1225
1226// Used to make code generic over signed and unsigned overflow.
1227template <typename ExtendOp> struct ExtendOpTraits {
1228 // Members present:
1229 //
1230 // static const SCEVFlags WrapType;
1231 //
1232 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1233 //
1234 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1235 // ICmpInst::Predicate *Pred,
1236 // ScalarEvolution *SE);
1237};
1238
1239template <>
1240struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1241 static const SCEVFlags WrapType = SCEV::FlagNSW;
1242
1243 static const GetExtendExprTy GetExtendExpr;
1244
1245 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1246 ICmpInst::Predicate *Pred,
1247 ScalarEvolution *SE) {
1248 return getSignedOverflowLimitForStep(Step, Pred, SE);
1249 }
1250};
1251
1252const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1254
1255template <>
1256struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1257 static const SCEVFlags WrapType = SCEV::FlagNUW;
1258
1259 static const GetExtendExprTy GetExtendExpr;
1260
1261 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1262 ICmpInst::Predicate *Pred,
1263 ScalarEvolution *SE) {
1264 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1265 }
1266};
1267
1268const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1270
1271} // end anonymous namespace
1272
1273// The recurrence AR has been shown to have no signed/unsigned wrap or something
1274// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1275// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1276// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1277// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1278// expression "Step + sext/zext(PreIncAR)" is congruent with
1279// "sext/zext(PostIncAR)"
1280template <typename ExtendOpTy>
1282 ScalarEvolution *SE, unsigned Depth) {
1283 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1284 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1285
1286 const Loop *L = AR->getLoop();
1287 const SCEV *Start = AR->getStart();
1288 const SCEV *Step = AR->getStepRecurrence(*SE);
1289
1290 // Check for a simple looking step prior to loop entry.
1291 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1292 if (!SA)
1293 return nullptr;
1294
1295 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1296 // subtraction is expensive. For this purpose, perform a quick and dirty
1297 // difference, by checking for Step in the operand list. Note, that
1298 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1299 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1300 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1301 if (*It == Step) {
1302 DiffOps.erase(It);
1303 break;
1304 }
1305
1306 if (DiffOps.size() == SA->getNumOperands())
1307 return nullptr;
1308
1309 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1310 // `Step`:
1311
1312 // 1. NSW/NUW flags on the step increment.
1313 auto PreStartFlags =
1315 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1317 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
1318
1319 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1320 // "S+X does not sign/unsign-overflow".
1321 //
1322
1323 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1324 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1325 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1326 return PreStart;
1327
1328 // 2. Direct overflow check on the step operation's expression.
1329 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1330 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1331 const SCEV *OperandExtendedStart =
1332 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1333 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1334 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1335 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1336 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1337 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1338 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1339 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1340 }
1341 return PreStart;
1342 }
1343
1344 // 3. Loop precondition.
1346 const SCEV *OverflowLimit =
1347 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1348
1349 if (OverflowLimit &&
1350 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1351 return PreStart;
1352
1353 return nullptr;
1354}
1355
1356// Get the normalized zero or sign extended expression for this AddRec's Start.
1357template <typename ExtendOpTy>
1358static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1359 ScalarEvolution *SE,
1360 unsigned Depth) {
1361 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1362
1363 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, SE, Depth);
1364 if (!PreStart)
1365 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1366
1367 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1368 Depth),
1369 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1370}
1371
1372// Try to prove away overflow by looking at "nearby" add recurrences. A
1373// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1374// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1375//
1376// Formally:
1377//
1378// {S,+,X} == {S-T,+,X} + T
1379// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1380//
1381// If ({S-T,+,X} + T) does not overflow ... (1)
1382//
1383// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1384//
1385// If {S-T,+,X} does not overflow ... (2)
1386//
1387// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1388// == {Ext(S-T)+Ext(T),+,Ext(X)}
1389//
1390// If (S-T)+T does not overflow ... (3)
1391//
1392// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1393// == {Ext(S),+,Ext(X)} == LHS
1394//
1395// Thus, if (1), (2) and (3) are true for some T, then
1396// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1397//
1398// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1399// does not overflow" restricted to the 0th iteration. Therefore we only need
1400// to check for (1) and (2).
1401//
1402// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1403// is `Delta` (defined below).
1404template <typename ExtendOpTy>
1405bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1406 const SCEV *Step,
1407 const Loop *L) {
1408 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1409
1410 // We restrict `Start` to a constant to prevent SCEV from spending too much
1411 // time here. It is correct (but more expensive) to continue with a
1412 // non-constant `Start` and do a general SCEV subtraction to compute
1413 // `PreStart` below.
1414 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1415 if (!StartC)
1416 return false;
1417
1418 APInt StartAI = StartC->getAPInt();
1419
1420 for (unsigned Delta : {-2, -1, 1, 2}) {
1421 const SCEV *PreStart = getConstant(StartAI - Delta);
1422 const auto *PreAR = static_cast<SCEVAddRecExpr *>(
1423 findExistingSCEVInCache(scAddRecExpr, {PreStart, Step}, L));
1424
1425 // Give up if we don't already have the add recurrence we need because
1426 // actually constructing an add recurrence is relatively expensive.
1427 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1428 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1430 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1431 DeltaS, &Pred, this);
1432 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1433 return true;
1434 }
1435 }
1436
1437 return false;
1438}
1439
1440// Finds an integer D for an expression (C + x + y + ...) such that the top
1441// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1442// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1443// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1444// the (C + x + y + ...) expression is \p WholeAddExpr.
1446 const SCEVConstant *ConstantTerm,
1447 const SCEVAddExpr *WholeAddExpr) {
1448 const APInt &C = ConstantTerm->getAPInt();
1449 const unsigned BitWidth = C.getBitWidth();
1450 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1451 uint32_t TZ = BitWidth;
1452 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1453 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1454 if (TZ) {
1455 // Set D to be as many least significant bits of C as possible while still
1456 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1457 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1458 }
1459 return APInt(BitWidth, 0);
1460}
1461
1462// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1463// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1464// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1465// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1467 const APInt &ConstantStart,
1468 const SCEV *Step) {
1469 const unsigned BitWidth = ConstantStart.getBitWidth();
1470 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1471 if (TZ)
1472 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1473 : ConstantStart;
1474 return APInt(BitWidth, 0);
1475}
1476
1478 const ScalarEvolution::FoldID &ID, const SCEV *S,
1481 &FoldCacheUser) {
1482 auto I = FoldCache.insert({ID, S});
1483 if (!I.second) {
1484 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1485 // entry.
1486 auto &UserIDs = FoldCacheUser[I.first->second];
1487 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1488 for (unsigned I = 0; I != UserIDs.size(); ++I)
1489 if (UserIDs[I] == ID) {
1490 std::swap(UserIDs[I], UserIDs.back());
1491 break;
1492 }
1493 UserIDs.pop_back();
1494 I.first->second = S;
1495 }
1496 FoldCacheUser[S].push_back(ID);
1497}
1498
1500 unsigned Depth) {
1501 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1502 "This is not an extending conversion!");
1503 assert(isSCEVable(Ty) &&
1504 "This is not a conversion to a SCEVable type!");
1505 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1506 Ty = getEffectiveSCEVType(Ty);
1507
1508 FoldID ID(scZeroExtend, Op, Ty);
1509 if (const SCEV *S = FoldCache.lookup(ID))
1510 return S;
1511
1512 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1514 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1515 return S;
1516}
1517
1519 unsigned Depth) {
1520 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1521 "This is not an extending conversion!");
1522 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1523 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1524
1525 // Fold if the operand is constant.
1526 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1527 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1528
1529 // zext(zext(x)) --> zext(x)
1531 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1532
1533 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1534 // zero-extension distributes over the recurrence.
1535 const SCEV *Start, *Step;
1536 const Loop *L;
1537 if (Depth <= MaxCastDepth &&
1538 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1539 const auto *AR = cast<SCEVAddRecExpr>(Op);
1540 if (AR->hasNoUnsignedWrap()) {
1541 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1542 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1543 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1544 }
1545 }
1546
1547 // Before doing any expensive analysis, check to see if we've already
1548 // computed a SCEV for this Op and Ty.
1551 ID.AddPointer(Op.getOpaqueValue());
1552 ID.AddPointer(Ty);
1554 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1555 return S;
1556 if (Depth > MaxCastDepth) {
1557 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1558 Op, Ty);
1559 UniqueSCEVs.insert(S, Token);
1560 S->computeAndSetCanonical(*this);
1561 registerUser(S, Op);
1562 return S;
1563 }
1564
1565 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1567 // It's possible the bits taken off by the truncate were all zero bits. If
1568 // so, we should be able to simplify this further.
1569 const SCEV *X = ST->getOperand();
1571 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1572 unsigned NewBits = getTypeSizeInBits(Ty);
1573 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1574 CR.zextOrTrunc(NewBits)))
1575 return getTruncateOrZeroExtend(X, Ty, Depth);
1576 }
1577
1578 // If the input value is a chrec scev, and we can prove that the value
1579 // did not overflow the old, smaller, value, we can zero extend all of the
1580 // operands (often constants). This allows analysis of something like
1581 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1582 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1583 const auto *AR = cast<SCEVAddRecExpr>(Op);
1584 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1585
1586 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1587
1588 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1589 // Note that this serves two purposes: It filters out loops that are
1590 // simply not analyzable, and it covers the case where this code is
1591 // being called from within backedge-taken count analysis, such that
1592 // attempting to ask for the backedge-taken count would likely result
1593 // in infinite recursion. In the later case, the analysis code will
1594 // cope with a conservative value, and it will take care to purge
1595 // that value once it has finished.
1596 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1597 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1598 // Manually compute the final value for AR, checking for overflow.
1599
1600 // Check whether the backedge-taken count can be losslessly casted to
1601 // the addrec's type. The count is always unsigned.
1602 const SCEV *CastedMaxBECount =
1603 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1604 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1605 CastedMaxBECount, MaxBECount->getType(), Depth);
1606 if (MaxBECount == RecastedMaxBECount) {
1607 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1608 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1609 const SCEV *ZMul =
1610 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
1611 const SCEV *ZAdd = getZeroExtendExpr(
1612 getAddExpr(Start, ZMul, SCEV::FlagNone, Depth + 1), WideTy,
1613 Depth + 1);
1614 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1615 const SCEV *WideMaxBECount =
1616 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1617 const SCEV *OperandExtendedAdd =
1618 getAddExpr(WideStart,
1619 getMulExpr(WideMaxBECount,
1620 getZeroExtendExpr(Step, WideTy, Depth + 1),
1621 SCEV::FlagNone, Depth + 1),
1622 SCEV::FlagNone, Depth + 1);
1623 if (ZAdd == OperandExtendedAdd) {
1624 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1625 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1626 // Return the expression with the addrec on the outside.
1627 Start =
1629 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1630 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1631 }
1632 // Similar to above, only this time treat the step value as signed.
1633 // This covers loops that count down.
1634 OperandExtendedAdd =
1635 getAddExpr(WideStart,
1636 getMulExpr(WideMaxBECount,
1637 getSignExtendExpr(Step, WideTy, Depth + 1),
1638 SCEV::FlagNone, Depth + 1),
1639 SCEV::FlagNone, Depth + 1);
1640 if (ZAdd == OperandExtendedAdd) {
1641 // Cache knowledge of AR NW, which is propagated to this AddRec.
1642 // Negative step causes unsigned wrap, but it still can't self-wrap.
1643 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1644 // Return the expression with the addrec on the outside.
1645 Start =
1647 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1648 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1649 }
1650 }
1651 }
1652
1653 // Normally, in the cases we can prove no-overflow via a
1654 // backedge guarding condition, we can also compute a backedge
1655 // taken count for the loop. The exceptions are assumptions and
1656 // guards present in the loop -- SCEV is not great at exploiting
1657 // these to compute max backedge taken counts, but can still use
1658 // these to prove lack of overflow. Use this fact to avoid
1659 // doing extra work that may not pay off.
1660 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1661 !AC.assumptions().empty()) {
1662
1663 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1664 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1665 if (AR->hasNoUnsignedWrap()) {
1666 // Same as nuw case above - duplicated here to avoid a compile time
1667 // issue. It's not clear that the order of checks does matter, but
1668 // it's one of two issue possible causes for a change which was
1669 // reverted. Be conservative for the moment.
1670 Start =
1672 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1673 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1674 }
1675
1676 // For a negative step, we can extend the operands iff doing so only
1677 // traverses values in the range zext([0,UINT_MAX]).
1678 if (isKnownNegative(Step)) {
1679 const SCEV *N =
1683 // Cache knowledge of AR NW, which is propagated to this
1684 // AddRec. Negative step causes unsigned wrap, but it
1685 // still can't self-wrap.
1686 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1687 // Return the expression with the addrec on the outside.
1688 Start =
1690 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1691 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1692 }
1693 }
1694 }
1695
1696 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1697 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1698 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1699 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1700 const APInt &C = SC->getAPInt();
1701 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1702 if (D != 0) {
1703 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1704 const SCEV *SResidual =
1705 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1706 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1707 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1708 Depth + 1);
1709 }
1710 }
1711
1712 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1713 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1714 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1715 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1716 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1717 }
1718 }
1719
1720 // zext(A % B) --> zext(A) % zext(B)
1721 {
1722 const SCEV *LHS;
1723 const SCEV *RHS;
1724 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1725 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1726 getZeroExtendExpr(RHS, Ty, Depth + 1));
1727 }
1728
1729 // zext(A / B) --> zext(A) / zext(B).
1730 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1731 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1732 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1733
1734 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1735 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1736 if (SA->hasNoUnsignedWrap()) {
1737 // If the addition does not unsign overflow then we can, by definition,
1738 // commute the zero extension with the addition operation.
1740 for (SCEVUse Op : SA->operands())
1741 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1742 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1743 }
1744
1745 const APInt *C, *C2;
1746 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1747 // Currently the non-negative check is done manually, as isKnownNonNegative
1748 // is too expensive.
1749 if (SA->hasNoSignedWrap() &&
1751 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1752 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1753 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1754 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1755 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1756 SCEV::FlagNSW, Depth + 1);
1757 }
1758
1759 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1760 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1761 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1762 //
1763 // Often address arithmetics contain expressions like
1764 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1765 // This transformation is useful while proving that such expressions are
1766 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1767 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1768 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1769 if (D != 0) {
1770 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1771 const SCEV *SResidual =
1773 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1774 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1775 Depth + 1);
1776 }
1777 }
1778 }
1779
1780 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1781 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1782 if (SM->hasNoUnsignedWrap()) {
1783 // If the multiply does not unsign overflow then we can, by definition,
1784 // commute the zero extension with the multiply operation.
1786 for (SCEVUse Op : SM->operands())
1787 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1788 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1789 }
1790
1791 // zext(2^K * (trunc X to iN)) to iM ->
1792 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1793 //
1794 // Proof:
1795 //
1796 // zext(2^K * (trunc X to iN)) to iM
1797 // = zext((trunc X to iN) << K) to iM
1798 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1799 // (because shl removes the top K bits)
1800 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1801 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1802 //
1803 const APInt *C;
1804 const SCEV *TruncRHS;
1805 if (match(SM,
1806 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1807 C->isPowerOf2()) {
1808 int NewTruncBits =
1809 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1810 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1811 return getMulExpr(
1812 getZeroExtendExpr(SM->getOperand(0), Ty),
1813 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1814 SCEV::FlagNUW, Depth + 1);
1815 }
1816 }
1817
1818 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1819 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1823 for (SCEVUse Operand : MinMax->operands())
1824 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1826 return getUMinExpr(Operands);
1827 return getUMaxExpr(Operands);
1828 }
1829
1830 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1832 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1834 for (SCEVUse Operand : MinMax->operands())
1835 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1836 return getUMinExpr(Operands, /*Sequential*/ true);
1837 }
1838
1839 // The cast wasn't folded; create an explicit cast node.
1840 // Recompute the insert position, as it may have been invalidated.
1841 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1842 return S;
1843 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1844 Op, Ty);
1845 UniqueSCEVs.insert(S, Token);
1846 S->computeAndSetCanonical(*this);
1847 registerUser(S, Op);
1848 return S;
1849}
1850
1852 unsigned Depth) {
1853 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1854 "This is not an extending conversion!");
1855 assert(isSCEVable(Ty) &&
1856 "This is not a conversion to a SCEVable type!");
1857 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1858 Ty = getEffectiveSCEVType(Ty);
1859
1860 FoldID ID(scSignExtend, Op, Ty);
1861 if (const SCEV *S = FoldCache.lookup(ID))
1862 return S;
1863
1864 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
1866 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1867 return S;
1868}
1869
1871 unsigned Depth) {
1872 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1873 "This is not an extending conversion!");
1874 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1875 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1876 Ty = getEffectiveSCEVType(Ty);
1877
1878 // Fold if the operand is constant.
1879 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1880 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
1881
1882 // sext(sext(x)) --> sext(x)
1884 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1885
1886 // sext(zext(x)) --> zext(x)
1888 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1889
1890 // If the operand is an affine AddRec with the no-signed-wrap flag, the
1891 // sign-extension distributes over the recurrence.
1892 const SCEV *Start, *Step;
1893 const Loop *L;
1894 if (Depth <= MaxCastDepth &&
1895 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1896 const auto *AR = cast<SCEVAddRecExpr>(Op);
1897 if (AR->hasNoSignedWrap()) {
1898 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
1899 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1900 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1901 }
1902 }
1903
1904 // Before doing any expensive analysis, check to see if we've already
1905 // computed a SCEV for this Op and Ty.
1908 ID.AddPointer(Op.getOpaqueValue());
1909 ID.AddPointer(Ty);
1911 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
1912 return S;
1913 // Limit recursion depth.
1914 if (Depth > MaxCastDepth) {
1915 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1916 Op, Ty);
1917 UniqueSCEVs.insert(S, Token);
1918 S->computeAndSetCanonical(*this);
1919 registerUser(S, Op);
1920 return S;
1921 }
1922
1923 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1925 // It's possible the bits taken off by the truncate were all sign bits. If
1926 // so, we should be able to simplify this further.
1927 const SCEV *X = ST->getOperand();
1929 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1930 unsigned NewBits = getTypeSizeInBits(Ty);
1931 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1932 CR.sextOrTrunc(NewBits)))
1933 return getTruncateOrSignExtend(X, Ty, Depth);
1934 }
1935
1936 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1937 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1938 if (SA->hasNoSignedWrap()) {
1939 // If the addition does not sign overflow then we can, by definition,
1940 // commute the sign extension with the addition operation.
1942 for (SCEVUse Op : SA->operands())
1943 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
1944 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
1945 }
1946
1947 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
1948 // if D + (C - D + x + y + ...) could be proven to not signed wrap
1949 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1950 //
1951 // For instance, this will bring two seemingly different expressions:
1952 // 1 + sext(5 + 20 * %x + 24 * %y) and
1953 // sext(6 + 20 * %x + 24 * %y)
1954 // to the same form:
1955 // 2 + sext(4 + 20 * %x + 24 * %y)
1956 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1957 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1958 if (D != 0) {
1959 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
1960 const SCEV *SResidual =
1962 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
1963 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1964 Depth + 1);
1965 }
1966 }
1967 }
1968 // If the input value is a chrec scev, and we can prove that the value
1969 // did not overflow the old, smaller, value, we can sign extend all of the
1970 // operands (often constants). This allows analysis of something like
1971 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
1972 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1973 const auto *AR = cast<SCEVAddRecExpr>(Op);
1974 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1975
1976 // The no-signed-wrap case is handled before the uniquing lookup above.
1977
1978 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1979 // Note that this serves two purposes: It filters out loops that are
1980 // simply not analyzable, and it covers the case where this code is
1981 // being called from within backedge-taken count analysis, such that
1982 // attempting to ask for the backedge-taken count would likely result
1983 // in infinite recursion. In the later case, the analysis code will
1984 // cope with a conservative value, and it will take care to purge
1985 // that value once it has finished.
1986 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1987 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1988 // Manually compute the final value for AR, checking for
1989 // overflow.
1990
1991 // Check whether the backedge-taken count can be losslessly casted to
1992 // the addrec's type. The count is always unsigned.
1993 const SCEV *CastedMaxBECount =
1994 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1995 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1996 CastedMaxBECount, MaxBECount->getType(), Depth);
1997 if (MaxBECount == RecastedMaxBECount) {
1998 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1999 // Check whether Start+Step*MaxBECount has no signed overflow.
2000 const SCEV *SMul =
2001 getMulExpr(CastedMaxBECount, Step, SCEV::FlagNone, Depth + 1);
2002 const SCEV *SAdd = getSignExtendExpr(
2003 getAddExpr(Start, SMul, SCEV::FlagNone, Depth + 1), WideTy,
2004 Depth + 1);
2005 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2006 const SCEV *WideMaxBECount =
2007 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2008 const SCEV *OperandExtendedAdd =
2009 getAddExpr(WideStart,
2010 getMulExpr(WideMaxBECount,
2011 getSignExtendExpr(Step, WideTy, Depth + 1),
2012 SCEV::FlagNone, Depth + 1),
2013 SCEV::FlagNone, Depth + 1);
2014 if (SAdd == OperandExtendedAdd) {
2015 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2016 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2017 // Return the expression with the addrec on the outside.
2018 Start =
2020 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2021 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2022 }
2023 // Similar to above, only this time treat the step value as unsigned.
2024 // This covers loops that count up with an unsigned step.
2025 OperandExtendedAdd =
2026 getAddExpr(WideStart,
2027 getMulExpr(WideMaxBECount,
2028 getZeroExtendExpr(Step, WideTy, Depth + 1),
2029 SCEV::FlagNone, Depth + 1),
2030 SCEV::FlagNone, Depth + 1);
2031 if (SAdd == OperandExtendedAdd) {
2032 // If AR wraps around then
2033 //
2034 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2035 // => SAdd != OperandExtendedAdd
2036 //
2037 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2038 // (SAdd == OperandExtendedAdd => AR is NW)
2039
2040 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2041
2042 // Return the expression with the addrec on the outside.
2043 Start =
2045 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2046 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2047 }
2048 }
2049 }
2050
2051 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2052 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2053 if (AR->hasNoSignedWrap()) {
2054 // Same as nsw case above - duplicated here to avoid a compile time
2055 // issue. It's not clear that the order of checks does matter, but
2056 // it's one of two issue possible causes for a change which was
2057 // reverted. Be conservative for the moment.
2058 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2059 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2060 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2061 }
2062
2063 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2064 // if D + (C - D + Step * n) could be proven to not signed wrap
2065 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2066 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2067 const APInt &C = SC->getAPInt();
2068 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2069 if (D != 0) {
2070 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2071 const SCEV *SResidual =
2072 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2073 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2074 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2075 Depth + 1);
2076 }
2077 }
2078
2079 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2080 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2081 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2082 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2083 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2084 }
2085 }
2086
2087 // If the input value is provably positive and we could not simplify
2088 // away the sext build a zext instead.
2090 return getZeroExtendExpr(Op, Ty, Depth + 1);
2091
2092 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2093 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2097 for (SCEVUse Operand : MinMax->operands())
2098 Operands.push_back(getSignExtendExpr(Operand, Ty));
2100 return getSMinExpr(Operands);
2101 return getSMaxExpr(Operands);
2102 }
2103
2104 // The cast wasn't folded; create an explicit cast node.
2105 // Recompute the insert position, as it may have been invalidated.
2106 if (const SCEV *S = UniqueSCEVs.lookup(ID, Token))
2107 return S;
2108 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2109 Op, Ty);
2110 UniqueSCEVs.insert(S, Token);
2111 S->computeAndSetCanonical(*this);
2112 registerUser(S, Op);
2113 return S;
2114}
2115
2117 switch (Kind) {
2118 case scTruncate:
2119 return getTruncateExpr(Op, Ty);
2120 case scZeroExtend:
2121 return getZeroExtendExpr(Op, Ty);
2122 case scSignExtend:
2123 return getSignExtendExpr(Op, Ty);
2124 case scPtrToAddr: {
2125 const SCEV *Expr = getPtrToAddrExpr(Op);
2126 assert(Expr->getType() == Ty && "requested type must match");
2127 return Expr;
2128 }
2129 default:
2130 llvm_unreachable("Not a SCEV cast expression!");
2131 }
2132}
2133
2134/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2135/// unspecified bits out to the given type.
2137 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2138 "This is not an extending conversion!");
2139 assert(isSCEVable(Ty) &&
2140 "This is not a conversion to a SCEVable type!");
2141 Ty = getEffectiveSCEVType(Ty);
2142
2143 // Sign-extend negative constants.
2144 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2145 if (SC->getAPInt().isNegative())
2146 return getSignExtendExpr(Op, Ty);
2147
2148 // Peel off a truncate cast.
2150 const SCEV *NewOp = T->getOperand();
2151 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2152 return getAnyExtendExpr(NewOp, Ty);
2153 return getTruncateOrNoop(NewOp, Ty);
2154 }
2155
2156 // Next try a zext cast. If the cast is folded, use it.
2157 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2158 if (!isa<SCEVZeroExtendExpr>(ZExt))
2159 return ZExt;
2160
2161 // Next try a sext cast. If the cast is folded, use it.
2162 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2163 if (!isa<SCEVSignExtendExpr>(SExt))
2164 return SExt;
2165
2166 // Force the cast to be folded into the operands of an addrec.
2167 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2169 for (const SCEV *Op : AR->operands())
2170 Ops.push_back(getAnyExtendExpr(Op, Ty));
2171 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2172 }
2173
2174 // If the expression is obviously signed, use the sext cast value.
2175 if (isa<SCEVSMaxExpr>(Op))
2176 return SExt;
2177
2178 // Absent any other information, use the zext cast value.
2179 return ZExt;
2180}
2181
2182/// Process the given Ops list, which is a list of operands to be added under
2183/// the given scale, update the given map. This is a helper function for
2184/// getAddRecExpr. As an example of what it does, given a sequence of operands
2185/// that would form an add expression like this:
2186///
2187/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2188///
2189/// where A and B are constants, update the map with these values:
2190///
2191/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2192///
2193/// and add 13 + A*B*29 to AccumulatedConstant.
2194/// This will allow getAddRecExpr to produce this:
2195///
2196/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2197///
2198/// This form often exposes folding opportunities that are hidden in
2199/// the original operand list.
2200///
2201/// Return true iff it appears that any interesting folding opportunities
2202/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2203/// the common case where no interesting opportunities are present, and
2204/// is also used as a check to avoid infinite recursion.
2205static bool
2208 APInt &AccumulatedConstant, ArrayRef<SCEVUse> Ops,
2209 const APInt &Scale, ScalarEvolution &SE) {
2210 bool Interesting = false;
2211
2212 // Iterate over the add operands. They are sorted, with constants first.
2213 unsigned i = 0;
2214 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2215 ++i;
2216 // Pull a buried constant out to the outside.
2217 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2218 Interesting = true;
2219 AccumulatedConstant += Scale * C->getAPInt();
2220 }
2221
2222 // Next comes everything else. We're especially interested in multiplies
2223 // here, but they're in the middle, so just visit the rest with one loop.
2224 for (; i != Ops.size(); ++i) {
2226 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2227 APInt NewScale =
2228 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2229 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2230 // A multiplication of a constant with another add; recurse.
2231 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2232 Interesting |= CollectAddOperandsWithScales(
2233 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2234 } else {
2235 // A multiplication of a constant with some other value. Update
2236 // the map.
2237 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2238 const SCEV *Key = SE.getMulExpr(MulOps)->getCanonical();
2239 auto Pair = M.insert({Key, NewScale});
2240 if (Pair.second) {
2241 NewOps.push_back(Pair.first->first);
2242 } else {
2243 Pair.first->second += NewScale;
2244 // The map already had an entry for this value, which may indicate
2245 // a folding opportunity.
2246 Interesting = true;
2247 }
2248 }
2249 } else {
2250 // An ordinary operand. Update the map.
2251 auto Pair = M.insert({Ops[i]->getCanonical(), Scale});
2252 if (Pair.second) {
2253 NewOps.push_back(Pair.first->first);
2254 } else {
2255 Pair.first->second += Scale;
2256 // The map already had an entry for this value, which may indicate
2257 // a folding opportunity.
2258 Interesting = true;
2259 }
2260 }
2261 }
2262
2263 return Interesting;
2264}
2265
2267 const SCEV *LHS, const SCEV *RHS,
2268 const Instruction *CtxI) {
2269 auto Operation = [this, BinOp](SCEVUse L, SCEVUse R) -> const SCEV * {
2270 switch (BinOp) {
2271 default:
2272 llvm_unreachable("Unsupported binary op");
2273 case Instruction::Add:
2274 return getAddExpr(L, R);
2275 case Instruction::Sub:
2276 return getMinusSCEV(L, R);
2277 case Instruction::Mul:
2278 return getMulExpr(L, R);
2279 }
2280 };
2281
2282 const SCEV *(ScalarEvolution::*Extension)(SCEVUse, Type *, unsigned) =
2285
2286 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2287 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2288 auto *WideTy =
2289 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2290
2291 const SCEV *A = (this->*Extension)(Operation(LHS, RHS), WideTy, 0);
2292 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2293 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2294 const SCEV *B = Operation(LHSB, RHSB);
2295 if (A == B)
2296 return true;
2297 // Can we use context to prove the fact we need?
2298 if (!CtxI)
2299 return false;
2300 // TODO: Support mul.
2301 if (BinOp == Instruction::Mul)
2302 return false;
2303 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2304 // TODO: Lift this limitation.
2305 if (!RHSC)
2306 return false;
2307 APInt C = RHSC->getAPInt();
2308 unsigned NumBits = C.getBitWidth();
2309 bool IsSub = (BinOp == Instruction::Sub);
2310 bool IsNegativeConst = (Signed && C.isNegative());
2311 // Compute the direction and magnitude by which we need to check overflow.
2312 bool OverflowDown = IsSub ^ IsNegativeConst;
2313 APInt Magnitude = C;
2314 if (IsNegativeConst) {
2315 if (C == APInt::getSignedMinValue(NumBits))
2316 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2317 // want to deal with that.
2318 return false;
2319 Magnitude = -C;
2320 }
2321
2323 if (OverflowDown) {
2324 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2325 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2326 : APInt::getMinValue(NumBits);
2327 APInt Limit = Min + Magnitude;
2328 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2329 } else {
2330 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2331 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2332 : APInt::getMaxValue(NumBits);
2333 APInt Limit = Max - Magnitude;
2334 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2335 }
2336}
2337
2339 const OverflowingBinaryOperator *OBO) {
2340 // It cannot be done any better.
2341 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2342 return std::nullopt;
2343
2345
2346 if (OBO->hasNoUnsignedWrap())
2348 if (OBO->hasNoSignedWrap())
2350
2351 bool Deduced = false;
2352
2354 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2355 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2356
2357 bool CanUseNSW = true;
2358 const APInt *ShiftAmt;
2359 // Treat `shl %a, C` as `mul %a, 1 << C`.
2360 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2361 unsigned BitWidth = ShiftAmt->getBitWidth();
2362 if (ShiftAmt->uge(BitWidth))
2363 return std::nullopt;
2364 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2365 // overflows.
2366 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2367 Opcode = Instruction::Mul;
2369 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2370 Opcode != Instruction::Mul) {
2371 return std::nullopt;
2372 }
2373
2374 const Instruction *CtxI =
2376 if (!OBO->hasNoUnsignedWrap() &&
2377 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2379 Deduced = true;
2380 }
2381
2382 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2383 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2385 Deduced = true;
2386 }
2387
2388 if (Deduced)
2389 return Flags;
2390 return std::nullopt;
2391}
2392
2393// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2394// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2395// can't-overflow flags for the operation if possible.
2398 using namespace std::placeholders;
2399
2400 using OBO = OverflowingBinaryOperator;
2401
2402 bool CanAnalyze =
2404 (void)CanAnalyze;
2405 assert(CanAnalyze && "don't call from other places!");
2406
2407 SCEVFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2408 SCEVFlags SignOrUnsignWrap =
2409 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2410
2411 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2412 auto IsKnownNonNegative = [&](SCEVUse U) {
2413 return SE->isKnownNonNegative(U);
2414 };
2415
2416 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2417 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2418
2419 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2420
2421 if (SignOrUnsignWrap != SignOrUnsignMask &&
2422 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2423 isa<SCEVConstant>(Ops[0])) {
2424
2425 auto Opcode = [&] {
2426 switch (Type) {
2427 case scAddExpr:
2428 return Instruction::Add;
2429 case scMulExpr:
2430 return Instruction::Mul;
2431 default:
2432 llvm_unreachable("Unexpected SCEV op.");
2433 }
2434 }();
2435
2436 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2437
2438 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2439 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2440 auto NSWRegion =
2441 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoSignedWrap);
2442 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2444 }
2445
2446 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2447 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2448 auto NUWRegion =
2449 ConstantRange::makeExactNoWrapRegion(Opcode, C, OBO::NoUnsignedWrap);
2450 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2452 }
2453 }
2454
2455 // <0,+,nonnegative><nw> is also nuw
2456 // TODO: Add corresponding nsw case
2458 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2459 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2461
2462 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2464 Ops.size() == 2) {
2465 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2466 if (UDiv->getOperand(1) == Ops[1])
2468 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2469 if (UDiv->getOperand(1) == Ops[0])
2471 }
2472
2473 return Flags;
2474}
2475
2477 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2478}
2479
2480/// Get a canonical add expression, or something simpler if possible.
2482 SCEVFlagsPair Flags, unsigned Depth) {
2483 SCEVFlags ExprFlags = Flags.ExprFlags;
2484 SCEVFlags UseFlags = Flags.UseFlags;
2485 assert(!(ExprFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2486 "only nuw or nsw allowed");
2487 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2488 "only nuw or nsw allowed");
2489 assert(!Ops.empty() && "Cannot get empty add!");
2490 if (Ops.size() == 1) return Ops[0];
2491#ifndef NDEBUG
2492 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2493 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2494 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2495 "SCEVAddExpr operand types don't match!");
2496 unsigned NumPtrs = count_if(
2497 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2498 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2499#endif
2500
2501 const SCEV *Folded = constantFoldAndGroupOps(
2502 *this, LI, DT, Ops,
2503 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2504 [](const APInt &C) { return C.isZero(); }, // identity
2505 [](const APInt &C) { return false; }); // absorber
2506 if (Folded)
2507 return Folded;
2508
2509#ifndef NDEBUG
2510 // Keep track of operands after constant folding, for verification when adding
2511 // use-specific flags.
2512 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
2513#endif
2514
2515 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2516
2517 // Delay expensive flag strengthening until necessary.
2518 auto ComputeFlags = [this, ExprFlags](ArrayRef<SCEVUse> Ops) {
2519 return StrengthenNoWrapFlags(this, scAddExpr, Ops, ExprFlags);
2520 };
2521
2522 // Limit recursion calls depth.
2524 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2525
2526 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2527 // Don't strengthen flags if we have no new information.
2528 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2529 if (Add->getNoWrapFlags(ExprFlags) != ExprFlags)
2530 Add->setNoWrapFlags(ComputeFlags(Ops));
2531 return {S, UseFlags};
2532 }
2533
2534 // Okay, check to see if the same value occurs in the operand list more than
2535 // once. If so, merge them together into an multiply expression. Since we
2536 // sorted the list, these values are required to be adjacent.
2537 Type *Ty = Ops[0]->getType();
2538 bool FoundMatch = false;
2539 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2540 if (SCEVUse Op = SCEVUse::getCommon(Ops[i], Ops[i + 1])) {
2541 // X + Y + Y --> X + Y*2
2542 // Scan ahead to count how many equal operands there are.
2543 unsigned Count = 2;
2544 for (; i + Count != e; ++Count) {
2545 SCEVUse Common = SCEVUse::getCommon(Op, Ops[i + Count]);
2546 if (!Common)
2547 break;
2548 Op = Common;
2549 }
2550 // Merge the values into a multiply.
2551 SCEVUse Scale = getConstant(Ty, Count);
2552 SCEVUse Mul = getMulExpr(Scale, Op, SCEV::FlagNone, Depth + 1);
2553 if (Ops.size() == Count)
2554 return Mul;
2555 Ops[i] = Mul;
2556 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2557 --i; e -= Count - 1;
2558 FoundMatch = true;
2559 }
2560 if (FoundMatch)
2561 return getAddExpr(Ops, ExprFlags, Depth + 1);
2562
2563 // Check for truncates. If all the operands are truncated from the same
2564 // type, see if factoring out the truncate would permit the result to be
2565 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2566 // if the contents of the resulting outer trunc fold to something simple.
2567 auto FindTruncSrcType = [&]() -> Type * {
2568 // We're ultimately looking to fold an addrec of truncs and muls of only
2569 // constants and truncs, so if we find any other types of SCEV
2570 // as operands of the addrec then we bail and return nullptr here.
2571 // Otherwise, we return the type of the operand of a trunc that we find.
2572 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2573 return T->getOperand()->getType();
2574 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2575 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2576 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2577 return T->getOperand()->getType();
2578 }
2579 return nullptr;
2580 };
2581 if (auto *SrcType = FindTruncSrcType()) {
2582 SmallVector<SCEVUse, 8> LargeOps;
2583 bool Ok = true;
2584 // Check all the operands to see if they can be represented in the
2585 // source type of the truncate.
2586 for (const SCEV *Op : Ops) {
2588 if (T->getOperand()->getType() != SrcType) {
2589 Ok = false;
2590 break;
2591 }
2592 LargeOps.push_back(T->getOperand());
2593 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2594 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2595 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2596 SmallVector<SCEVUse, 8> LargeMulOps;
2597 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2598 if (const SCEVTruncateExpr *T =
2599 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2600 if (T->getOperand()->getType() != SrcType) {
2601 Ok = false;
2602 break;
2603 }
2604 LargeMulOps.push_back(T->getOperand());
2605 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2606 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2607 } else {
2608 Ok = false;
2609 break;
2610 }
2611 }
2612 if (Ok)
2613 LargeOps.push_back(
2614 getMulExpr(LargeMulOps, SCEV::FlagNone, Depth + 1));
2615 } else {
2616 Ok = false;
2617 break;
2618 }
2619 }
2620 if (Ok) {
2621 // Evaluate the expression in the larger type.
2622 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagNone, Depth + 1);
2623 // If it folds to something simple, use it. Otherwise, don't.
2624 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2625 return getTruncateExpr(Fold, Ty);
2626 }
2627 }
2628
2629 if (Ops.size() == 2) {
2630 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2631 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2632 // C1).
2633 const SCEV *A = Ops[0];
2634 const SCEV *B = Ops[1];
2635 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2636 auto *C = dyn_cast<SCEVConstant>(A);
2637 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2638 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2639 auto C2 = C->getAPInt();
2640 SCEVFlags PreservedFlags = SCEV::FlagNone;
2641
2642 APInt ConstAdd = C1 + C2;
2643 auto AddFlags = AddExpr->getNoWrapFlags();
2644 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2646 ConstAdd.ule(C1)) {
2647 PreservedFlags =
2649 }
2650
2651 // Adding a constant with the same sign and small magnitude is NSW, if the
2652 // original AddExpr was NSW.
2654 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2655 ConstAdd.abs().ule(C1.abs())) {
2656 PreservedFlags =
2658 }
2659
2660 if (PreservedFlags != SCEV::FlagNone) {
2661 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2662 NewOps[0] = getConstant(ConstAdd);
2663 return getAddExpr(NewOps, PreservedFlags);
2664 }
2665 }
2666
2667 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2668 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2669 const SCEVAddExpr *InnerAdd;
2670 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2671 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2672 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2673 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2674 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2676 SCEV::FlagNUW)) {
2677 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2678 }
2679 }
2680 }
2681
2682 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2683 const SCEV *Y;
2684 if (Ops.size() == 2 &&
2685 match(Ops[0],
2687 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2688 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2689
2690 // Skip past any other cast SCEVs.
2691 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2692 ++Idx;
2693
2694 // If there are add operands they would be next.
2695 if (Idx < Ops.size()) {
2696 bool DeletedAdd = false;
2697 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2698 // common NUW flag for expression after inlining. Other flags cannot be
2699 // preserved, because they may depend on the original order of operations.
2700 SCEVFlags CommonFlags = maskFlags(ExprFlags, SCEV::FlagNUW);
2701 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2702 if (Ops.size() > AddOpsInlineThreshold ||
2703 Add->getNumOperands() > AddOpsInlineThreshold)
2704 break;
2705 // If we have an add, expand the add operands onto the end of the operands
2706 // list.
2707 Ops.erase(Ops.begin()+Idx);
2708 append_range(Ops, Add->operands());
2709 DeletedAdd = true;
2710 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2711 }
2712
2713 // If we deleted at least one add, we added operands to the end of the list,
2714 // and they are not necessarily sorted. Recurse to resort and resimplify
2715 // any operands we just acquired.
2716 if (DeletedAdd)
2717 return getAddExpr(Ops, CommonFlags, Depth + 1);
2718 }
2719
2720 // Skip over the add expression until we get to a multiply.
2721 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2722 ++Idx;
2723
2724 // Check to see if there are any folding opportunities present with
2725 // operands multiplied by constant values.
2726 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2727 uint64_t BitWidth = getTypeSizeInBits(Ty);
2730 APInt AccumulatedConstant(BitWidth, 0);
2731 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2732 Ops, APInt(BitWidth, 1), *this)) {
2733 struct APIntCompare {
2734 bool operator()(const APInt &LHS, const APInt &RHS) const {
2735 return LHS.ult(RHS);
2736 }
2737 };
2738
2739 // Some interesting folding opportunity is present, so its worthwhile to
2740 // re-generate the operands list. Group the operands by constant scale,
2741 // to avoid multiplying by the same constant scale multiple times.
2742 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2743 for (SCEVUse NewOp : NewOps)
2744 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2745 // Re-generate the operands list.
2746 Ops.clear();
2747 if (AccumulatedConstant != 0)
2748 Ops.push_back(getConstant(AccumulatedConstant));
2749 for (auto &MulOp : MulOpLists) {
2750 if (MulOp.first == 1) {
2751 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1));
2752 } else if (MulOp.first != 0) {
2753 Ops.push_back(
2754 getMulExpr(getConstant(MulOp.first),
2755 getAddExpr(MulOp.second, SCEV::FlagNone, Depth + 1),
2756 SCEV::FlagNone, Depth + 1));
2757 }
2758 }
2759 if (Ops.empty())
2760 return getZero(Ty);
2761 if (Ops.size() == 1)
2762 return Ops[0];
2763 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2764 }
2765 }
2766
2767 // Given a SCEVMulExpr and an operand index, return the product of all
2768 // operands except the one at OpIdx.
2769 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2770 if (M->getNumOperands() == 2)
2771 return M->getOperand(OpIdx == 0);
2772 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2773 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2774 return getMulExpr(Remaining, SCEV::FlagNone, Depth + 1);
2775 };
2776
2777 // If we are adding something to a multiply expression, make sure the
2778 // something is not already an operand of the multiply. If so, merge it into
2779 // the multiply.
2780 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2781 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2782 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2783 // Scan all terms to find every occurrence of common factor MulOpSCEV
2784 // and fold them in one shot:
2785 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2786 SCEVUse MulOpSCEV = Mul->getOperand(MulOp);
2787 if (isa<SCEVConstant>(MulOpSCEV))
2788 continue;
2789
2790 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2791 // remaining product for multiply terms containing MulOpSCEV.
2792 SmallVector<SCEVUse, 4> Cofactors;
2793 SmallVector<unsigned, 4> DeadIndices;
2794 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2795 if (SCEVUse Common = SCEVUse::getCommon(MulOpSCEV, Ops[AddOp])) {
2796 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2797 MulOpSCEV = Common;
2798 Cofactors.push_back(getOne(Ty));
2799 DeadIndices.push_back(AddOp);
2800 continue;
2801 }
2802
2803 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2804 continue;
2805
2806 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2807 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2808 ++OMulOp) {
2809 if (SCEVUse Common =
2810 SCEVUse::getCommon(MulOpSCEV, OtherMul->getOperand(OMulOp))) {
2811 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2812 MulOpSCEV = Common;
2813 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2814 DeadIndices.push_back(AddOp);
2815 break;
2816 }
2817 }
2818 }
2819
2820 // Fold all collected cofactors with the anchor multiply's cofactor:
2821 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2822 if (!Cofactors.empty()) {
2823 Cofactors.push_back(StripFactor(Mul, MulOp));
2824
2825 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagNone, Depth + 1);
2826 SCEVUse OuterMul =
2827 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagNone, Depth + 1);
2828
2829 // DeadIndices does not include Idx (the anchor), hence +1.
2830 if (Ops.size() == DeadIndices.size() + 1)
2831 return OuterMul;
2832
2833 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2834 // The -1 adjustment accounts for the shift from removing Idx;
2835 // reverse order means each erasure only shifts later positions,
2836 // which have already been processed.
2837 Ops.erase(Ops.begin() + Idx);
2838 for (unsigned Dead : reverse(DeadIndices))
2839 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2840
2841 Ops.push_back(OuterMul);
2842 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2843 }
2844 }
2845 }
2846
2847 // If there are any add recurrences in the operands list, see if any other
2848 // added values are loop invariant. If so, we can fold them into the
2849 // recurrence.
2850 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2851 ++Idx;
2852
2853 // Scan over all recurrences, trying to fold loop invariants into them.
2854 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2855 // Scan all of the other operands to this add and add them to the vector if
2856 // they are loop invariant w.r.t. the recurrence.
2858 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2859 const Loop *AddRecLoop = AddRec->getLoop();
2860 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2861 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2862 LIOps.push_back(Ops[i]);
2863 Ops.erase(Ops.begin()+i);
2864 --i; --e;
2865 }
2866
2867 // If we found some loop invariants, fold them into the recurrence.
2868 if (!LIOps.empty()) {
2869 // Compute nowrap flags for the addition of the loop-invariant ops and
2870 // the addrec. Temporarily push it as an operand for that purpose. These
2871 // flags are valid in the scope of the addrec only.
2872 LIOps.push_back(AddRec);
2873 SCEVFlags Flags = ComputeFlags(LIOps);
2874 LIOps.pop_back();
2875
2876 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2877 LIOps.push_back(AddRec->getStart());
2878
2879 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2880
2881 // It is not in general safe to propagate flags valid on an add within
2882 // the addrec scope to one outside it. We must prove that the inner
2883 // scope is guaranteed to execute if the outer one does to be able to
2884 // safely propagate. We know the program is undefined if poison is
2885 // produced on the inner scoped addrec. We also know that *for this use*
2886 // the outer scoped add can't overflow (because of the flags we just
2887 // computed for the inner scoped add) without the program being undefined.
2888 // Proving that entry to the outer scope neccesitates entry to the inner
2889 // scope, thus proves the program undefined if the flags would be violated
2890 // in the outer scope.
2891 SCEVFlags AddFlags = Flags;
2892 if (AddFlags != SCEV::FlagNone) {
2893 auto *DefI = getDefiningScopeBound(LIOps);
2894 auto *ReachI = &*AddRecLoop->getHeader()->begin();
2895 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
2896 AddFlags = SCEV::FlagNone;
2897 }
2898 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
2899
2900 // Build the new addrec. Propagate the NUW and NSW flags if both the
2901 // outer add and the inner addrec are guaranteed to have no overflow.
2902 // Always propagate NW.
2903 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2904 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2905
2906 // If all of the other operands were loop invariant, we are done.
2907 if (Ops.size() == 1) return NewRec;
2908
2909 // Otherwise, add the folded AddRec by the non-invariant parts.
2910 for (unsigned i = 0;; ++i)
2911 if (Ops[i] == AddRec) {
2912 Ops[i] = NewRec;
2913 break;
2914 }
2915 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2916 }
2917
2918 // Okay, if there weren't any loop invariants to be folded, check to see if
2919 // there are multiple AddRec's with the same loop induction variable being
2920 // added together. If so, we can fold them.
2921 for (unsigned OtherIdx = Idx+1;
2922 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2923 ++OtherIdx) {
2924 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2925 // so that the 1st found AddRecExpr is dominated by all others.
2926 assert(DT.dominates(
2927 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2928 AddRec->getLoop()->getHeader()) &&
2929 "AddRecExprs are not sorted in reverse dominance order?");
2930 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2931 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2932 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
2933 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2934 ++OtherIdx) {
2935 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2936 if (OtherAddRec->getLoop() == AddRecLoop) {
2937 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2938 i != e; ++i) {
2939 if (i >= AddRecOps.size()) {
2940 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
2941 break;
2942 }
2943 AddRecOps[i] =
2944 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
2945 SCEV::FlagNone, Depth + 1);
2946 }
2947 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2948 }
2949 }
2950 // Step size has changed, so we cannot guarantee no self-wraparound.
2951 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagNone);
2952 return getAddExpr(Ops, SCEV::FlagNone, Depth + 1);
2953 }
2954 }
2955
2956 // Otherwise couldn't fold anything into this recurrence. Move onto the
2957 // next one.
2958 }
2959
2960 // Okay, it looks like we really DO need an add expr. Check to see if we
2961 // already have one, otherwise create a new one.
2962 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
2963 "Tried to add SCEVUse flags after operands changed");
2964 return {getOrCreateAddExpr(Ops, ComputeFlags(Ops)), UseFlags};
2965}
2966
2967const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2968 SCEVFlags Flags) {
2971 for (SCEVUse Op : Ops)
2972 ID.AddPointer(Op.getOpaqueValue());
2974 SCEVAddExpr *S = static_cast<SCEVAddExpr *>(UniqueSCEVs.lookup(ID, Token));
2975 if (!S) {
2976 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
2978 S = new (SCEVAllocator)
2979 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2980 UniqueSCEVs.insert(S, Token);
2981 S->computeAndSetCanonical(*this);
2982 registerUser(S, Ops);
2983 }
2984 S->setNoWrapFlags(Flags);
2985 return S;
2986}
2987
2988const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
2989 const Loop *L,
2990 SCEVFlags Flags) {
2991 FoldingSetNodeID ID;
2992 ID.AddInteger(scAddRecExpr);
2993 for (SCEVUse Op : Ops)
2994 ID.AddPointer(Op.getOpaqueValue());
2995 ID.AddPointer(L);
2996 FoldingSetInsertToken Token;
2997 SCEVAddRecExpr *S =
2998 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.lookup(ID, Token));
2999 if (!S) {
3000 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3002 S = new (SCEVAllocator)
3003 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3004 UniqueSCEVs.insert(S, Token);
3005 S->computeAndSetCanonical(*this);
3006 LoopUsers[L].push_back(S);
3007 registerUser(S, Ops);
3008 }
3009 setNoWrapFlags(S, Flags);
3010 return S;
3011}
3012
3013const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3014 SCEVFlags Flags) {
3015 FoldingSetNodeID ID;
3016 ID.AddInteger(scMulExpr);
3017 for (SCEVUse Op : Ops)
3018 ID.AddPointer(Op.getOpaqueValue());
3019 FoldingSetInsertToken Token;
3020 SCEVMulExpr *S = static_cast<SCEVMulExpr *>(UniqueSCEVs.lookup(ID, Token));
3021 if (!S) {
3022 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3024 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3025 O, Ops.size());
3026 UniqueSCEVs.insert(S, Token);
3027 S->computeAndSetCanonical(*this);
3028 registerUser(S, Ops);
3029 }
3030 S->setNoWrapFlags(Flags);
3031 return S;
3032}
3033
3034const SCEV *ScalarEvolution::getOrCreateUDivExpr(SCEVUse LHS, SCEVUse RHS) {
3035 FoldingSetNodeID ID;
3036 ID.AddInteger(scUDivExpr);
3037 ID.AddPointer(LHS.getOpaqueValue());
3038 ID.AddPointer(RHS.getOpaqueValue());
3039 FoldingSetInsertToken Token;
3040 SCEV *S = UniqueSCEVs.lookup(ID, Token);
3041 if (!S) {
3042 S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), LHS, RHS);
3043 UniqueSCEVs.insert(S, Token);
3044 S->computeAndSetCanonical(*this);
3045 registerUser(S, {LHS, RHS});
3046 }
3047 return S;
3048}
3049
3050static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3051 uint64_t k = i*j;
3052 if (j > 1 && k / j != i) Overflow = true;
3053 return k;
3054}
3055
3056/// Compute the result of "n choose k", the binomial coefficient. If an
3057/// intermediate computation overflows, Overflow will be set and the return will
3058/// be garbage. Overflow is not cleared on absence of overflow.
3059static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3060 // We use the multiplicative formula:
3061 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3062 // At each iteration, we take the n-th term of the numeral and divide by the
3063 // (k-n)th term of the denominator. This division will always produce an
3064 // integral result, and helps reduce the chance of overflow in the
3065 // intermediate computations. However, we can still overflow even when the
3066 // final result would fit.
3067
3068 if (n == 0 || n == k) return 1;
3069 if (k > n) return 0;
3070
3071 if (k > n/2)
3072 k = n-k;
3073
3074 uint64_t r = 1;
3075 for (uint64_t i = 1; i <= k; ++i) {
3076 r = umul_ov(r, n-(i-1), Overflow);
3077 r /= i;
3078 }
3079 return r;
3080}
3081
3082/// Determine if any of the operands in this SCEV are a constant or if
3083/// any of the add or multiply expressions in this SCEV contain a constant.
3084static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3085 struct FindConstantInAddMulChain {
3086 bool FoundConstant = false;
3087
3088 bool follow(const SCEV *S) {
3089 FoundConstant |= isa<SCEVConstant>(S);
3090 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3091 }
3092
3093 bool isDone() const {
3094 return FoundConstant;
3095 }
3096 };
3097
3098 FindConstantInAddMulChain F;
3100 ST.visitAll(StartExpr);
3101 return F.FoundConstant;
3102}
3103
3104/// Get a canonical multiply expression, or something simpler if possible.
3106 SCEVFlagsPair Flags, unsigned Depth) {
3107 SCEVFlags ExprFlags = Flags.ExprFlags;
3108 SCEVFlags UseFlags = Flags.UseFlags;
3109 assert(ExprFlags == maskFlags(ExprFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3110 "only nuw or nsw allowed");
3111 assert(UseFlags == maskFlags(UseFlags, 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#ifndef NDEBUG
3132 // Keep track of operands after constant folding, for verification when adding
3133 // use-specific flags.
3134 const SmallVector<SCEVUse, 8> OrigOps(Ops.begin(), Ops.end());
3135#endif
3136
3137 // Delay expensive flag strengthening until necessary.
3138 auto ComputeFlags = [this, ExprFlags](const ArrayRef<SCEVUse> Ops) {
3139 return StrengthenNoWrapFlags(this, scMulExpr, Ops, ExprFlags);
3140 };
3141
3142 // Limit recursion calls depth.
3144 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3145
3146 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3147 // Don't strengthen flags if we have no new information.
3148 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3149 if (Mul->getNoWrapFlags(ExprFlags) != ExprFlags)
3150 Mul->setNoWrapFlags(ComputeFlags(Ops));
3151 return {S, UseFlags};
3152 }
3153
3154 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3155 if (Ops.size() == 2) {
3156 // C1*(C2+V) -> C1*C2 + C1*V
3157 // If any of Add's ops are Adds or Muls with a constant, apply this
3158 // transformation as well.
3159 //
3160 // TODO: There are some cases where this transformation is not
3161 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3162 // this transformation should be narrowed down.
3163 const SCEV *Op0, *Op1;
3164 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3166 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagNone, Depth + 1);
3167 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagNone, Depth + 1);
3168 return getAddExpr(LHS, RHS, SCEV::FlagNone, Depth + 1);
3169 }
3170
3171 if (Ops[0]->isAllOnesValue()) {
3172 // If we have a mul by -1 of an add, try distributing the -1 among the
3173 // add operands.
3174 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3176 bool AnyFolded = false;
3177 for (const SCEV *AddOp : Add->operands()) {
3178 const SCEV *Mul =
3179 getMulExpr(Ops[0], SCEVUse(AddOp), SCEV::FlagNone, Depth + 1);
3180 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3181 NewOps.push_back(Mul);
3182 }
3183 if (AnyFolded)
3184 return getAddExpr(NewOps, SCEV::FlagNone, Depth + 1);
3185 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3186 // Negation preserves a recurrence's no self-wrap property.
3188 for (const SCEV *AddRecOp : AddRec->operands())
3189 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3190 SCEV::FlagNone, Depth + 1));
3191 // Let M be the minimum representable signed value. AddRec with nsw
3192 // multiplied by -1 can have signed overflow if and only if it takes a
3193 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3194 // maximum signed value. In all other cases signed overflow is
3195 // impossible.
3196 auto FlagsMask = SCEV::FlagNW;
3197 if (AddRec->hasNoSignedWrap()) {
3198 auto MinInt =
3199 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3200 if (getSignedRangeMin(AddRec) != MinInt)
3202 }
3203 return getAddRecExpr(Operands, AddRec->getLoop(),
3204 AddRec->getNoWrapFlags(FlagsMask));
3205 }
3206 }
3207
3208 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3209 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3210 const SCEVAddExpr *InnerAdd;
3211 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3212 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3213 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3214 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3215 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3217 SCEV::FlagNUW)) {
3218 const SCEV *Res =
3219 getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3220 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3221 };
3222 }
3223
3224 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3225 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3226 // of C1, fold to (D /u (C2 /u C1)).
3227 const SCEV *D;
3228 APInt C1V = LHSC->getAPInt();
3229 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3230 // as -1 * 1, as it won't enable additional folds.
3231 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3232 C1V = C1V.abs();
3233 const SCEVConstant *C2;
3234 if (C1V.isPowerOf2() &&
3236 C2->getAPInt().isPowerOf2() &&
3237 C1V.logBase2() <= getMinTrailingZeros(D)) {
3238 const SCEV *NewMul = nullptr;
3239 if (C1V.uge(C2->getAPInt())) {
3240 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3241 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3242 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3243 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3244 }
3245 if (NewMul)
3246 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3247 }
3248 }
3249 }
3250
3251 // Skip over the add expression until we get to a multiply.
3252 unsigned Idx = 0;
3253 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3254 ++Idx;
3255
3256 // If there are mul operands inline them all into this expression.
3257 if (Idx < Ops.size()) {
3258 bool DeletedMul = false;
3259 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3260 if (Ops.size() > MulOpsInlineThreshold)
3261 break;
3262 // If we have an mul, expand the mul operands onto the end of the
3263 // operands list.
3264 Ops.erase(Ops.begin()+Idx);
3265 append_range(Ops, Mul->operands());
3266 DeletedMul = true;
3267 }
3268
3269 // If we deleted at least one mul, we added operands to the end of the
3270 // list, and they are not necessarily sorted. Recurse to resort and
3271 // resimplify any operands we just acquired.
3272 if (DeletedMul)
3273 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3274 }
3275
3276 // If there are any add recurrences in the operands list, see if any other
3277 // added values are loop invariant. If so, we can fold them into the
3278 // recurrence.
3279 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3280 ++Idx;
3281
3282 // Scan over all recurrences, trying to fold loop invariants into them.
3283 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3284 // Scan all of the other operands to this mul and add them to the vector
3285 // if they are loop invariant w.r.t. the recurrence.
3287 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3288 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3289 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3290 LIOps.push_back(Ops[i]);
3291 Ops.erase(Ops.begin()+i);
3292 --i; --e;
3293 }
3294
3295 // If we found some loop invariants, fold them into the recurrence.
3296 if (!LIOps.empty()) {
3297 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3299 NewOps.reserve(AddRec->getNumOperands());
3300 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagNone, Depth + 1);
3301
3302 // If both the mul and addrec are nuw, we can preserve nuw.
3303 // If both the mul and addrec are nsw, we can only preserve nsw if either
3304 // a) they are also nuw, or
3305 // b) all multiplications of addrec operands with scale are nsw.
3306 SCEVFlags Flags = AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3307
3308 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3309 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3310 SCEV::FlagNone, Depth + 1));
3311
3312 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3314 Instruction::Mul, getSignedRange(Scale),
3316 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3317 Flags = clearFlags(Flags, SCEV::FlagNSW);
3318 }
3319 }
3320
3321 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3322
3323 // If all of the other operands were loop invariant, we are done.
3324 if (Ops.size() == 1) return NewRec;
3325
3326 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3327 for (unsigned i = 0;; ++i)
3328 if (Ops[i] == AddRec) {
3329 Ops[i] = NewRec;
3330 break;
3331 }
3332 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3333 }
3334
3335 // Okay, if there weren't any loop invariants to be folded, check to see
3336 // if there are multiple AddRec's with the same loop induction variable
3337 // being multiplied together. If so, we can fold them.
3338
3339 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3340 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3341 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3342 // ]]],+,...up to x=2n}.
3343 // Note that the arguments to choose() are always integers with values
3344 // known at compile time, never SCEV objects.
3345 //
3346 // The implementation avoids pointless extra computations when the two
3347 // addrec's are of different length (mathematically, it's equivalent to
3348 // an infinite stream of zeros on the right).
3349 bool OpsModified = false;
3350 for (unsigned OtherIdx = Idx+1;
3351 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3352 ++OtherIdx) {
3353 const SCEVAddRecExpr *OtherAddRec =
3354 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3355 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3356 continue;
3357
3358 // Limit max number of arguments to avoid creation of unreasonably big
3359 // SCEVAddRecs with very complex operands.
3360 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3361 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3362 continue;
3363
3364 bool Overflow = false;
3365 Type *Ty = AddRec->getType();
3366 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3367 SmallVector<SCEVUse, 7> AddRecOps;
3368 for (int x = 0, xe = AddRec->getNumOperands() +
3369 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3371 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3372 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3373 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3374 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3375 z < ze && !Overflow; ++z) {
3376 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3377 uint64_t Coeff;
3378 if (LargerThan64Bits)
3379 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3380 else
3381 Coeff = Coeff1*Coeff2;
3382 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3383 const SCEV *Term1 = AddRec->getOperand(y-z);
3384 const SCEV *Term2 = OtherAddRec->getOperand(z);
3385 SumOps.push_back(
3386 getMulExpr(CoeffTerm, Term1, Term2, SCEV::FlagNone, Depth + 1));
3387 }
3388 }
3389 if (SumOps.empty())
3390 SumOps.push_back(getZero(Ty));
3391 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagNone, Depth + 1));
3392 }
3393 if (!Overflow) {
3394 const SCEV *NewAddRec =
3395 getAddRecExpr(AddRecOps, AddRec->getLoop(), SCEV::FlagNone);
3396 if (Ops.size() == 2) return NewAddRec;
3397 Ops[Idx] = NewAddRec;
3398 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3399 OpsModified = true;
3400 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3401 if (!AddRec)
3402 break;
3403 }
3404 }
3405 if (OpsModified)
3406 return getMulExpr(Ops, SCEV::FlagNone, Depth + 1);
3407
3408 // Otherwise couldn't fold anything into this recurrence. Move onto the
3409 // next one.
3410 }
3411
3412 // Okay, it looks like we really DO need an mul expr. Check to see if we
3413 // already have one, otherwise create a new one.
3414 assert((UseFlags == SCEV::FlagNone || equal(OrigOps, Ops)) &&
3415 "Tried to add SCEVUse flags after operands changed");
3416 return {getOrCreateMulExpr(Ops, ComputeFlags(Ops)), UseFlags};
3417}
3418
3419/// Represents an unsigned remainder expression based on unsigned division.
3421 assert(getEffectiveSCEVType(LHS->getType()) ==
3422 getEffectiveSCEVType(RHS->getType()) &&
3423 "SCEVURemExpr operand types don't match!");
3424
3425 // Short-circuit easy cases
3426 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3427 // If constant is one, the result is trivial
3428 if (RHSC->getValue()->isOne())
3429 return getZero(LHS->getType()); // X urem 1 --> 0
3430
3431 // If constant is a power of two, fold into a zext(trunc(LHS)).
3432 if (RHSC->getAPInt().isPowerOf2()) {
3433 Type *FullTy = LHS->getType();
3434 Type *TruncTy =
3435 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3436 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3437 }
3438 }
3439
3440 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3441 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3442 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3443 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3444}
3445
3446/// Get a canonical unsigned division expression, or something simpler if
3447/// possible.
3449 assert(!LHS->getType()->isPointerTy() &&
3450 "SCEVUDivExpr operand can't be pointer!");
3451 assert(LHS->getType() == RHS->getType() &&
3452 "SCEVUDivExpr operand types don't match!");
3453
3454 if (SCEV *S = findExistingSCEVInCache(scUDivExpr, {LHS, RHS}))
3455 return S;
3456
3457 // 0 udiv Y == 0
3458 if (match(LHS, m_scev_Zero()))
3459 return LHS;
3460
3461 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3462 if (RHSC->getValue()->isOne())
3463 return LHS; // X udiv 1 --> x
3464 // If the denominator is zero, the result of the udiv is undefined. Don't
3465 // try to analyze it, because the resolution chosen here may differ from
3466 // the resolution chosen in other parts of the compiler.
3467 if (!RHSC->getValue()->isZero()) {
3468 // Determine if the division can be folded into the operands of
3469 // its operands.
3470 // TODO: Generalize this to non-constants by using known-bits information.
3471 Type *Ty = LHS->getType();
3472 unsigned LZ = RHSC->getAPInt().countl_zero();
3473 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3474 // For non-power-of-two values, effectively round the value up to the
3475 // nearest power of two.
3476 if (!RHSC->getAPInt().isPowerOf2())
3477 ++MaxShiftAmt;
3478 IntegerType *ExtTy =
3479 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3480 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3481 if (const SCEVConstant *Step =
3482 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3483 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3484 const APInt &StepInt = Step->getAPInt();
3485 const APInt &DivInt = RHSC->getAPInt();
3486 if (!StepInt.urem(DivInt) &&
3487 getZeroExtendExpr(AR, ExtTy) ==
3488 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3489 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3490 SCEV::FlagNone)) {
3492 for (const SCEV *Op : AR->operands())
3493 Operands.push_back(getUDivExpr(Op, RHS));
3494 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3495 }
3496 /// Get a canonical UDivExpr for a recurrence.
3497 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3498 const APInt *StartRem;
3499 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3500 m_scev_APInt(StartRem))) {
3501 bool NoWrap =
3502 getZeroExtendExpr(AR, ExtTy) ==
3503 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3504 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3506
3507 // With N <= C and both N, C as powers-of-2, the transformation
3508 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3509 // if wrapping occurs, as the division results remain equivalent for
3510 // all offsets in [[(X - X%N), X).
3511 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3512 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3513 // Only fold if the subtraction can be folded in the start
3514 // expression.
3515 const SCEV *NewStart =
3516 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3517 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3518 !isa<SCEVAddExpr>(NewStart)) {
3519 const SCEV *NewLHS =
3520 getAddRecExpr(NewStart, Step, AR->getLoop(),
3521 NoWrap ? SCEV::FlagNW : SCEV::FlagNone);
3522 if (LHS != NewLHS)
3523 return getUDivExpr(NewLHS, RHS);
3524 }
3525 }
3526 }
3527 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3528 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3529 if (M->hasNoUnsignedWrap()) {
3530 // Find an operand that's safely divisible.
3531 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3532 const SCEV *Op = M->getOperand(i);
3533 const SCEV *Div = getUDivExpr(Op, RHSC);
3534 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3535 SmallVector<SCEVUse, 4> Operands(M->operands());
3536 Operands[i] = Div;
3537 return getMulExpr(Operands);
3538 }
3539 }
3540
3541 // Even if it's not divisible, try to remove a common factor.
3542 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3543 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3544 RHSC->getAPInt());
3545 if (!Factor.isIntN(1)) {
3546 SmallVector<SCEVUse, 2> NewOperands;
3547 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3548 append_range(NewOperands, M->operands().drop_front());
3549 const SCEV *NewMul = getMulExpr(NewOperands);
3550 return getUDivExpr(NewMul,
3551 getConstant(RHSC->getAPInt().udiv(Factor)));
3552 }
3553 }
3554 }
3555 }
3556
3557 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3558 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3559 if (auto *DivisorConstant =
3560 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3561 bool Overflow = false;
3562 APInt NewRHS =
3563 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3564 if (Overflow) {
3565 return getConstant(RHSC->getType(), 0, false);
3566 }
3567 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3568 }
3569 }
3570
3571 // (A+B)/C --> (A/C + B/C) if the add does not unsigned wrap and A/C and
3572 // B/C can be folded.
3573 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3574 if (A->hasNoUnsignedWrap()) {
3576 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3577 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3578 if (isa<SCEVUDivExpr>(Op) ||
3579 getMulExpr(Op, RHS) != A->getOperand(i))
3580 break;
3581 Operands.push_back(Op);
3582 }
3583 if (Operands.size() == A->getNumOperands())
3584 return getAddExpr(Operands);
3585 }
3586 }
3587
3588 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3589 // This is an idiom for rounding A up to the next multiple of N, where A
3590 // is aready known to be a multiple of M. In this case, instcombine can
3591 // see that some low bits of the added constant are unused, so can clear
3592 // them, but we want to canonicalise to set the low bits. This makes the
3593 // pattern easier to match, without needing to check for known bits in
3594 // A*M.
3595 const APInt &N = RHSC->getAPInt();
3596 const APInt *NMinusM, *M;
3597 const SCEV *A;
3598 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3599 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3600 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3601 *NMinusM == N - *M) {
3602 return getUDivExpr(
3604 RHS);
3605 }
3606 }
3607
3608 // Fold if both operands are constant.
3609 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3610 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3611 }
3612 }
3613
3614 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3615 const APInt *NegC, *C;
3616 if (match(LHS,
3619 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3620 return getZero(LHS->getType());
3621
3622 // (%a * %b)<nuw> / %b -> %a
3623 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3624 if (Mul && Mul->hasNoUnsignedWrap()) {
3625 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3626 if (Mul->getOperand(i) == RHS) {
3628 append_range(Operands, Mul->operands().take_front(i));
3629 append_range(Operands, Mul->operands().drop_front(i + 1));
3630 return getMulExpr(Operands);
3631 }
3632 }
3633 }
3634
3635 // TODO: Generalize to handle any common factors.
3636 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3637 const SCEV *NewLHS, *NewRHS;
3638 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3639 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3640 return getUDivExpr(NewLHS, NewRHS);
3641
3642 return getOrCreateUDivExpr(LHS, RHS);
3643}
3644
3645/// Get a canonical unsigned division expression, or something simpler if
3646/// possible. There is no representation for an exact udiv in SCEV IR, but we
3647/// can attempt to optimize it prior to construction.
3649 // Currently there is no exact specific logic.
3650
3651 return getUDivExpr(LHS, RHS);
3652}
3653
3654/// Get an add recurrence expression for the specified loop. Simplify the
3655/// expression as much as possible.
3657 const Loop *L, SCEVFlagsPair Flags) {
3659 Operands.push_back(Start);
3660 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3661 if (StepChrec->getLoop() == L) {
3662 append_range(Operands, StepChrec->operands());
3663 // The use flags describe the two-operand recurrence, not the flattened
3664 // one built here, so drop them just like the expression's NUW/NSW.
3665 return getAddRecExpr(Operands, L,
3666 maskFlags(Flags.ExprFlags, SCEV::FlagNW));
3667 }
3668
3669 Operands.push_back(Step);
3670 return getAddRecExpr(Operands, L, Flags);
3671}
3672
3673/// Get an add recurrence expression for the specified loop. Simplify the
3674/// expression as much as possible.
3676 const Loop *L, SCEVFlagsPair NWFlags) {
3677 SCEVFlags ExprFlags = NWFlags.ExprFlags;
3678 SCEVFlags UseFlags = NWFlags.UseFlags;
3679 assert(!(UseFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
3680 "only nuw or nsw allowed");
3681 if (Operands.size() == 1) return Operands[0];
3682#ifndef NDEBUG
3684 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3685 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3686 "SCEVAddRecExpr operand types don't match!");
3687 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3688 }
3689 for (const SCEV *Op : Operands)
3691 "SCEVAddRecExpr operand is not available at loop entry!");
3692
3693 // Keep track of the original operands, for verification when adding
3694 // use-specific flags.
3695 const SmallVector<SCEVUse, 4> OrigOperands(Operands.begin(), Operands.end());
3696#endif
3697
3698 if (Operands.back()->isZero()) {
3699 Operands.pop_back();
3700 return getAddRecExpr(Operands, L, SCEV::FlagNone); // {X,+,0} --> X
3701 }
3702
3703 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3704 // use that information to infer NUW and NSW flags. However, computing a
3705 // BE count requires calling getAddRecExpr, so we may not yet have a
3706 // meaningful BE count at this point (and if we don't, we'd be stuck
3707 // with a SCEVCouldNotCompute as the cached BE count).
3708
3709 ExprFlags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, ExprFlags);
3710
3711 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3712 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3713 const Loop *NestedLoop = NestedAR->getLoop();
3714 if (L->contains(NestedLoop)
3715 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3716 : (!NestedLoop->contains(L) &&
3717 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3718 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3719 Operands[0] = NestedAR->getStart();
3720 // AddRecs require their operands be loop-invariant with respect to their
3721 // loops. Don't perform this transformation if it would break this
3722 // requirement.
3723 bool AllInvariant = all_of(
3724 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3725
3726 if (AllInvariant) {
3727 // Create a recurrence for the outer loop with the same step size.
3728 //
3729 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3730 // inner recurrence has the same property.
3731 SCEVFlags OuterFlags =
3732 maskFlags(ExprFlags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3733
3734 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3735 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3736 return isLoopInvariant(Op, NestedLoop);
3737 });
3738
3739 if (AllInvariant) {
3740 // Ok, both add recurrences are valid after the transformation.
3741 //
3742 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3743 // the outer recurrence has the same property.
3744 SCEVFlags InnerFlags =
3745 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | ExprFlags);
3746 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3747 }
3748 }
3749 // Reset Operands to its original state.
3750 Operands[0] = NestedAR;
3751 }
3752 }
3753
3754 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3755 // already have one, otherwise create a new one.
3756 assert((UseFlags == SCEV::FlagNone || equal(OrigOperands, Operands)) &&
3757 "Tried to add SCEVUse flags after operands changed");
3758 return {getOrCreateAddRecExpr(Operands, L, ExprFlags), UseFlags};
3759}
3760
3762 ArrayRef<SCEVUse> IndexExprs) {
3763 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3764 // getSCEV(Base)->getType() has the same address space as Base->getType()
3765 // because SCEV::getType() preserves the address space.
3766 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3767 if (NW != GEPNoWrapFlags::none()) {
3768 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3769 // but to do that, we have to ensure that said flag is valid in the entire
3770 // defined scope of the SCEV.
3771 // TODO: non-instructions have global scope. We might be able to prove
3772 // some global scope cases
3773 auto *GEPI = dyn_cast<Instruction>(GEP);
3774 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3775 NW = GEPNoWrapFlags::none();
3776 }
3777
3778 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3779}
3780
3782 ArrayRef<SCEVUse> IndexExprs,
3783 Type *SrcElementTy, GEPNoWrapFlags NW) {
3784 SCEVFlags OffsetWrap = SCEV::FlagNone;
3785 if (NW.hasNoUnsignedSignedWrap())
3786 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3787 if (NW.hasNoUnsignedWrap())
3788 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3789
3790 Type *CurTy = BaseExpr->getType();
3791 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3792 bool FirstIter = true;
3794 for (SCEVUse IndexExpr : IndexExprs) {
3795 // Compute the (potentially symbolic) offset in bytes for this index.
3796 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3797 // For a struct, add the member offset.
3798 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3799 unsigned FieldNo = Index->getZExtValue();
3800 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3801 Offsets.push_back(FieldOffset);
3802
3803 // Update CurTy to the type of the field at Index.
3804 CurTy = STy->getTypeAtIndex(Index);
3805 } else {
3806 // Update CurTy to its element type.
3807 if (FirstIter) {
3808 assert(isa<PointerType>(CurTy) &&
3809 "The first index of a GEP indexes a pointer");
3810 CurTy = SrcElementTy;
3811 FirstIter = false;
3812 } else {
3813 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3814 }
3815 // For an array, add the element offset, explicitly scaled.
3816 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3817 // Getelementptr indices are signed.
3818 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3819
3820 // Multiply the index by the element size to compute the element offset.
3821 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3822 Offsets.push_back(LocalOffset);
3823 }
3824 }
3825
3826 // Handle degenerate case of GEP without offsets.
3827 if (Offsets.empty())
3828 return BaseExpr;
3829
3830 // Add the offsets together, assuming nsw if inbounds.
3831 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3832 // Add the base address and the offset. We cannot use the nsw flag, as the
3833 // base address is unsigned. However, if we know that the offset is
3834 // non-negative, we can use nuw.
3835 bool NUW = NW.hasNoUnsignedWrap() ||
3837 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3838 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3839 assert(BaseExpr->getType() == GEPExpr->getType() &&
3840 "GEP should not change type mid-flight.");
3841 return GEPExpr;
3842}
3843
3844SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3846 const Loop *L) {
3847 assert((SCEVType != scAddRecExpr || L) &&
3848 "L must be passed to find existing AddRecs");
3850 ID.AddInteger(SCEVType);
3851 for (SCEVUse Op : Ops)
3852 ID.AddPointer(Op.getOpaqueValue());
3853 if (L)
3854 ID.AddPointer(L);
3856 return UniqueSCEVs.lookup(ID, Token);
3857}
3858
3859const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3860 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3861 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3862}
3863
3866 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3867 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3868 if (Ops.size() == 1) return Ops[0];
3869#ifndef NDEBUG
3870 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3871 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3872 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3873 "Operand types don't match!");
3874 assert(Ops[0]->getType()->isPointerTy() ==
3875 Ops[i]->getType()->isPointerTy() &&
3876 "min/max should be consistently pointerish");
3877 }
3878#endif
3879
3880 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3881 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3882
3883 const SCEV *Folded = constantFoldAndGroupOps(
3884 *this, LI, DT, Ops,
3885 [&](const APInt &C1, const APInt &C2) {
3886 switch (Kind) {
3887 case scSMaxExpr:
3888 return APIntOps::smax(C1, C2);
3889 case scSMinExpr:
3890 return APIntOps::smin(C1, C2);
3891 case scUMaxExpr:
3892 return APIntOps::umax(C1, C2);
3893 case scUMinExpr:
3894 return APIntOps::umin(C1, C2);
3895 default:
3896 llvm_unreachable("Unknown SCEV min/max opcode");
3897 }
3898 },
3899 [&](const APInt &C) {
3900 // identity
3901 if (IsMax)
3902 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3903 else
3904 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3905 },
3906 [&](const APInt &C) {
3907 // absorber
3908 if (IsMax)
3909 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3910 else
3911 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3912 });
3913 if (Folded)
3914 return Folded;
3915
3916 // Check if we have created the same expression before.
3917 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3918 return S;
3919 }
3920
3921 // Find the first operation of the same kind
3922 unsigned Idx = 0;
3923 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3924 ++Idx;
3925
3926 // Check to see if one of the operands is of the same kind. If so, expand its
3927 // operands onto our operand list, and recurse to simplify.
3928 if (Idx < Ops.size()) {
3929 bool DeletedAny = false;
3930 while (Ops[Idx]->getSCEVType() == Kind) {
3931 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3932 Ops.erase(Ops.begin()+Idx);
3933 append_range(Ops, SMME->operands());
3934 DeletedAny = true;
3935 }
3936
3937 if (DeletedAny)
3938 return getMinMaxExpr(Kind, Ops);
3939 }
3940
3941 // Okay, check to see if the same value occurs in the operand list twice. If
3942 // so, delete one. Since we sorted the list, these values are required to
3943 // be adjacent.
3948 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3949 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3950 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3951 if (SCEVUse Common = SCEVUse::getCommon(Ops[i], Ops[i + 1]))
3952 Ops[i] = Ops[i + 1] = Common;
3953 if (Ops[i] == Ops[i + 1] ||
3954 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3955 // X op Y op Y --> X op Y
3956 // X op Y --> X, if we know X, Y are ordered appropriately
3957 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3958 --i;
3959 --e;
3960 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3961 Ops[i + 1])) {
3962 // X op Y --> Y, if we know X, Y are ordered appropriately
3963 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3964 --i;
3965 --e;
3966 }
3967 }
3968
3969 if (Ops.size() == 1) return Ops[0];
3970
3971 assert(!Ops.empty() && "Reduced smax down to nothing!");
3972
3973 // Okay, it looks like we really DO need an expr. Check to see if we
3974 // already have one, otherwise create a new one.
3976 ID.AddInteger(Kind);
3977 for (SCEVUse Op : Ops)
3978 ID.AddPointer(Op.getOpaqueValue());
3980 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3981 if (ExistingSCEV)
3982 return ExistingSCEV;
3983 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3985 SCEV *S = new (SCEVAllocator)
3986 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
3987
3988 UniqueSCEVs.insert(S, Token);
3989 S->computeAndSetCanonical(*this);
3990 registerUser(S, Ops);
3991 return S;
3992}
3993
3994namespace {
3995
3996class SCEVSequentialMinMaxDeduplicatingVisitor final
3997 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
3998 std::optional<const SCEV *>> {
3999 using RetVal = std::optional<const SCEV *>;
4000
4001 ScalarEvolution &SE;
4002 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4003 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4005
4006 bool canRecurseInto(SCEVTypes Kind) const {
4007 // We can only recurse into the SCEV expression of the same effective type
4008 // as the type of our root SCEV expression.
4009 return RootKind == Kind || NonSequentialRootKind == Kind;
4010 };
4011
4012 RetVal visit(const SCEV *S) {
4013 // Has the whole operand been seen already?
4014 if (!SeenOps.insert(S).second)
4015 return std::nullopt;
4017 SCEVTypes Kind = S->getSCEVType();
4018
4019 if (!canRecurseInto(Kind))
4020 return S;
4021
4022 auto *NAry = cast<SCEVNAryExpr>(S);
4023 SmallVector<SCEVUse> NewOps;
4024 bool Changed = visit(Kind, NAry->operands(), NewOps);
4025
4026 if (!Changed)
4027 return S;
4028 if (NewOps.empty())
4029 return std::nullopt;
4030
4032 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4033 : SE.getMinMaxExpr(Kind, NewOps);
4034 }
4035 return S;
4036 }
4037
4038public:
4039 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4040 SCEVTypes RootKind)
4041 : SE(SE), RootKind(RootKind),
4042 NonSequentialRootKind(
4043 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4044 RootKind)) {}
4045
4046 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4047 SmallVectorImpl<SCEVUse> &NewOps) {
4048 bool Changed = false;
4050 Ops.reserve(OrigOps.size());
4051
4052 for (const SCEV *Op : OrigOps) {
4053 RetVal NewOp = visit(Op);
4054 if (NewOp != Op)
4055 Changed = true;
4056 if (NewOp)
4057 Ops.emplace_back(*NewOp);
4058 }
4059
4060 if (Changed)
4061 NewOps = std::move(Ops);
4062 return Changed;
4063 }
4064};
4065
4066} // namespace
4067
4069 switch (Kind) {
4070 case scConstant:
4071 case scVScale:
4072 case scTruncate:
4073 case scZeroExtend:
4074 case scSignExtend:
4075 case scPtrToAddr:
4076 case scAddExpr:
4077 case scMulExpr:
4078 case scUDivExpr:
4079 case scAddRecExpr:
4080 case scUMaxExpr:
4081 case scSMaxExpr:
4082 case scUMinExpr:
4083 case scSMinExpr:
4084 case scUnknown:
4085 // If any operand is poison, the whole expression is poison.
4086 return true;
4088 // FIXME: if the *first* operand is poison, the whole expression is poison.
4089 return false; // Pessimistically, say that it does not propagate poison.
4090 case scCouldNotCompute:
4091 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4092 }
4093 llvm_unreachable("Unknown SCEV kind!");
4094}
4095
4096namespace {
4097// The only way poison may be introduced in a SCEV expression is from a
4098// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4099// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4100// introduce poison -- they encode guaranteed, non-speculated knowledge.
4101//
4102// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4103// with the notable exception of umin_seq, where only poison from the first
4104// operand is (unconditionally) propagated.
4105struct SCEVPoisonCollector {
4106 bool LookThroughMaybePoisonBlocking;
4107 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4108 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4109 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4110
4111 bool follow(const SCEV *S) {
4112 if (!LookThroughMaybePoisonBlocking &&
4114 return false;
4115
4116 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4117 if (!isGuaranteedNotToBePoison(SU->getValue()))
4118 MaybePoison.insert(SU);
4119 }
4120 return true;
4121 }
4122 bool isDone() const { return false; }
4123};
4124} // namespace
4125
4126/// Return true if V is poison given that AssumedPoison is already poison.
4127static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4128 // First collect all SCEVs that might result in AssumedPoison to be poison.
4129 // We need to look through potentially poison-blocking operations here,
4130 // because we want to find all SCEVs that *might* result in poison, not only
4131 // those that are *required* to.
4132 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4133 visitAll(AssumedPoison, PC1);
4134
4135 // AssumedPoison is never poison. As the assumption is false, the implication
4136 // is true. Don't bother walking the other SCEV in this case.
4137 if (PC1.MaybePoison.empty())
4138 return true;
4139
4140 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4141 // as well. We cannot look through potentially poison-blocking operations
4142 // here, as their arguments only *may* make the result poison.
4143 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4144 visitAll(S, PC2);
4145
4146 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4147 // it will also make S poison by being part of PC2.MaybePoison.
4148 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4149}
4150
4152 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4153 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4154 visitAll(S, PC);
4155 for (const SCEVUnknown *SU : PC.MaybePoison)
4156 Result.insert(SU->getValue());
4157}
4158
4160 const SCEV *S, Instruction *I,
4161 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4162 // If the instruction cannot be poison, it's always safe to reuse.
4164 return true;
4165
4166 // Otherwise, it is possible that I is more poisonous that S. Collect the
4167 // poison-contributors of S, and then check whether I has any additional
4168 // poison-contributors. Poison that is contributed through poison-generating
4169 // flags is handled by dropping those flags instead.
4171 getPoisonGeneratingValues(PoisonVals, S);
4172
4173 SmallVector<Value *> Worklist;
4175 Worklist.push_back(I);
4176 unsigned NumVisitedInsts = 0;
4177 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4178 while (!Worklist.empty()) {
4179 Value *V = Worklist.pop_back_val();
4180 if (!Visited.insert(V).second)
4181 continue;
4182
4183 // Either the value can't be poison, or the S would also be poison if it
4184 // is.
4185 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4186 continue;
4187
4188 // Avoid walking large instruction graphs.
4189 if (++NumVisitedInsts > InstLimit)
4190 return false;
4191
4192 auto *I = dyn_cast<Instruction>(V);
4193 if (!I)
4194 return false;
4195
4196 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4197 // can't replace an arbitrary add with disjoint or, even if we drop the
4198 // flag. We would need to convert the or into an add.
4199 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4200 if (PDI->isDisjoint())
4201 return false;
4202
4203 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4204 // because SCEV currently assumes it can't be poison. Remove this special
4205 // case once we proper model when vscale can be poison.
4206 if (auto *II = dyn_cast<IntrinsicInst>(I);
4207 II && II->getIntrinsicID() == Intrinsic::vscale)
4208 continue;
4209
4210 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4211 return false;
4212
4213 // If the instruction can't create poison, we can recurse to its operands.
4214 if (I->hasPoisonGeneratingAnnotations())
4215 DropPoisonGeneratingInsts.push_back(I);
4216
4217 llvm::append_range(Worklist, I->operands());
4218 }
4219 return true;
4220}
4221
4222const SCEV *
4225 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4226 "Not a SCEVSequentialMinMaxExpr!");
4227 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4228 if (Ops.size() == 1)
4229 return Ops[0];
4230#ifndef NDEBUG
4231 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4232 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4233 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4234 "Operand types don't match!");
4235 assert(Ops[0]->getType()->isPointerTy() ==
4236 Ops[i]->getType()->isPointerTy() &&
4237 "min/max should be consistently pointerish");
4238 }
4239#endif
4240
4241 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4242 // so we can *NOT* do any kind of sorting of the expressions!
4243
4244 // Check if we have created the same expression before.
4245 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4246 return S;
4247
4248 // FIXME: there are *some* simplifications that we can do here.
4249
4250 // Keep only the first instance of an operand.
4251 {
4252 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4253 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4254 if (Changed)
4255 return getSequentialMinMaxExpr(Kind, Ops);
4256 }
4257
4258 // Check to see if one of the operands is of the same kind. If so, expand its
4259 // operands onto our operand list, and recurse to simplify.
4260 {
4261 unsigned Idx = 0;
4262 bool DeletedAny = false;
4263 while (Idx < Ops.size()) {
4264 if (Ops[Idx]->getSCEVType() != Kind) {
4265 ++Idx;
4266 continue;
4267 }
4268 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4269 Ops.erase(Ops.begin() + Idx);
4270 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4271 SMME->operands().end());
4272 DeletedAny = true;
4273 }
4274
4275 if (DeletedAny)
4276 return getSequentialMinMaxExpr(Kind, Ops);
4277 }
4278
4279 const SCEV *SaturationPoint;
4281 switch (Kind) {
4283 SaturationPoint = getZero(Ops[0]->getType());
4284 Pred = ICmpInst::ICMP_ULE;
4285 break;
4286 default:
4287 llvm_unreachable("Not a sequential min/max type.");
4288 }
4289
4290 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4291 if (!isGuaranteedNotToCauseUB(Ops[i]))
4292 continue;
4293 // We can replace %x umin_seq %y with %x umin %y if either:
4294 // * %y being poison implies %x is also poison.
4295 // * %x cannot be the saturating value (e.g. zero for umin).
4296 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4297 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4298 SaturationPoint)) {
4299 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4300 Ops[i - 1] = getMinMaxExpr(
4302 SeqOps);
4303 Ops.erase(Ops.begin() + i);
4304 return getSequentialMinMaxExpr(Kind, Ops);
4305 }
4306 // Fold %x umin_seq %y to %x if %x ule %y.
4307 // TODO: We might be able to prove the predicate for a later operand.
4308 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4309 Ops.erase(Ops.begin() + i);
4310 return getSequentialMinMaxExpr(Kind, Ops);
4311 }
4312 }
4313
4314 // Okay, it looks like we really DO need an expr. Check to see if we
4315 // already have one, otherwise create a new one.
4317 ID.AddInteger(Kind);
4318 for (SCEVUse Op : Ops)
4319 ID.AddPointer(Op.getOpaqueValue());
4321 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4322 if (ExistingSCEV)
4323 return ExistingSCEV;
4324
4325 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4327 SCEV *S = new (SCEVAllocator)
4328 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4329
4330 UniqueSCEVs.insert(S, Token);
4331 S->computeAndSetCanonical(*this);
4332 registerUser(S, Ops);
4333 return S;
4334}
4335
4340
4344
4349
4353
4358
4362
4364 bool Sequential) {
4365 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4366 return getUMinExpr(Ops, Sequential);
4367}
4368
4374
4375const SCEV *
4377 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4378 if (Size.isScalable())
4379 Res = getMulExpr(Res, getVScale(IntTy));
4380 return Res;
4381}
4382
4384 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4385}
4386
4388 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4389}
4390
4392 StructType *STy,
4393 unsigned FieldNo) {
4394 // We can bypass creating a target-independent constant expression and then
4395 // folding it back into a ConstantInt. This is just a compile-time
4396 // optimization.
4397 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4398 assert(!SL->getSizeInBits().isScalable() &&
4399 "Cannot get offset for structure containing scalable vector types");
4400 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4401}
4402
4404 // Don't attempt to do anything other than create a SCEVUnknown object
4405 // here. createSCEV only calls getUnknown after checking for all other
4406 // interesting possibilities, and any other code that calls getUnknown
4407 // is doing so in order to hide a value from SCEV canonicalization.
4408
4411 ID.AddPointer(V);
4413 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4414 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4415 "Stale SCEVUnknown in uniquing map!");
4416 return S;
4417 }
4418 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4419 FirstUnknown, NextUnknownOrderID++);
4420 FirstUnknown = cast<SCEVUnknown>(S);
4421 UniqueSCEVs.insert(S, Token);
4422 S->computeAndSetCanonical(*this);
4423 return S;
4424}
4425
4426//===----------------------------------------------------------------------===//
4427// Basic SCEV Analysis and PHI Idiom Recognition Code
4428//
4429
4430/// Test if values of the given type are analyzable within the SCEV
4431/// framework. This primarily includes integer types, and it can optionally
4432/// include pointer types if the ScalarEvolution class has access to
4433/// target-specific information.
4435 // Integers and pointers are always SCEVable.
4436 return Ty->isIntOrPtrTy();
4437}
4438
4439/// Return the size in bits of the specified type, for which isSCEVable must
4440/// return true.
4442 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4443 if (Ty->isPointerTy())
4445 return getDataLayout().getTypeSizeInBits(Ty);
4446}
4447
4448/// Return a type with the same bitwidth as the given type and which represents
4449/// how SCEV will treat the given type, for which isSCEVable must return
4450/// true. For pointer types, this is the pointer index sized integer type.
4452 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4453
4454 if (Ty->isIntegerTy())
4455 return Ty;
4456
4457 // The only other support type is pointer.
4458 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4459 return getDataLayout().getIndexType(Ty);
4460}
4461
4463 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4464}
4465
4467 const SCEV *B) {
4468 /// For a valid use point to exist, the defining scope of one operand
4469 /// must dominate the other.
4470 bool PreciseA, PreciseB;
4471 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4472 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4473 if (!PreciseA || !PreciseB)
4474 // Can't tell.
4475 return false;
4476 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4477 DT.dominates(ScopeB, ScopeA);
4478}
4479
4481 return CouldNotCompute.get();
4482}
4483
4484bool ScalarEvolution::checkValidity(const SCEV *S) const {
4485 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4486 auto *SU = dyn_cast<SCEVUnknown>(S);
4487 return SU && SU->getValue() == nullptr;
4488 });
4489
4490 return !ContainsNulls;
4491}
4492
4494 HasRecMapType::iterator I = HasRecMap.find(S);
4495 if (I != HasRecMap.end())
4496 return I->second;
4497
4498 bool FoundAddRec =
4499 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4500 HasRecMap.insert({S, FoundAddRec});
4501 return FoundAddRec;
4502}
4503
4504/// Return the ValueOffsetPair set for \p S. \p S can be represented
4505/// by the value and offset from any ValueOffsetPair in the set.
4506ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4507 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4508 if (SI == ExprValueMap.end())
4509 return {};
4510 return SI->second;
4511}
4512
4513/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4514/// cannot be used separately. eraseValueFromMap should be used to remove
4515/// V from ValueExprMap and ExprValueMap at the same time.
4516void ScalarEvolution::eraseValueFromMap(Value *V) {
4517 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4518 if (I != ValueExprMap.end()) {
4519 auto EVIt = ExprValueMap.find(I->second);
4520 assert(is_contained(EVIt->second, V) && "Value not in ExprValueMap?");
4521 llvm::erase(EVIt->second, V);
4522 ValueExprMap.erase(I);
4523 }
4524}
4525
4526void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4527 // A recursive query may have already computed the SCEV. It should be
4528 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4529 // inferred nowrap flags.
4530 if (ValueExprMap.insert({SCEVCallbackVH(V, this), S}).second)
4531 ExprValueMap[S].push_back(V);
4532}
4533
4534/// Return an existing SCEV if it exists, otherwise analyze the expression and
4535/// create a new one.
4537 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4538
4539 if (const SCEV *S = getExistingSCEV(V))
4540 return S;
4541 return createSCEVIter(V);
4542}
4543
4545 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4546
4547 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4548 if (I != ValueExprMap.end()) {
4549 const SCEV *S = I->second;
4550 assert(checkValidity(S) &&
4551 "existing SCEV has not been properly invalidated");
4552 return S;
4553 }
4554 return nullptr;
4555}
4556
4557/// Return a SCEV corresponding to -V = -1*V
4559 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4560 return getConstant(
4561 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4562
4563 Type *Ty = V->getType();
4564 Ty = getEffectiveSCEVType(Ty);
4565 return getMulExpr(V, getMinusOne(Ty), Flags);
4566}
4567
4568/// If Expr computes ~A, return A else return nullptr
4569static const SCEV *MatchNotExpr(const SCEV *Expr) {
4570 const SCEV *MulOp;
4571 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4572 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4573 return MulOp;
4574 return nullptr;
4575}
4576
4577/// Return a SCEV corresponding to ~V = -1-V
4579 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4580
4581 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4582 return getConstant(
4583 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4584
4585 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4586 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4587 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4588 SmallVector<SCEVUse, 2> MatchedOperands;
4589 for (const SCEV *Operand : MME->operands()) {
4590 const SCEV *Matched = MatchNotExpr(Operand);
4591 if (!Matched)
4592 return (const SCEV *)nullptr;
4593 MatchedOperands.push_back(Matched);
4594 }
4595 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4596 MatchedOperands);
4597 };
4598 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4599 return Replaced;
4600 }
4601
4602 Type *Ty = V->getType();
4603 Ty = getEffectiveSCEVType(Ty);
4604 return getMinusSCEV(getMinusOne(Ty), V);
4605}
4606
4608 assert(P->getType()->isPointerTy());
4609
4610 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4611 // The base of an AddRec is the first operand.
4612 SmallVector<SCEVUse> Ops{AddRec->operands()};
4613 Ops[0] = removePointerBase(Ops[0]);
4614 // Don't try to transfer nowrap flags for now. We could in some cases
4615 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4616 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4617 }
4618 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4619 // The base of an Add is the pointer operand.
4620 SmallVector<SCEVUse> Ops{Add->operands()};
4621 SCEVUse *PtrOp = nullptr;
4622 for (SCEVUse &AddOp : Ops) {
4623 if (AddOp->getType()->isPointerTy()) {
4624 assert(!PtrOp && "Cannot have multiple pointer ops");
4625 PtrOp = &AddOp;
4626 }
4627 }
4628 *PtrOp = removePointerBase(*PtrOp);
4629 // Don't try to transfer nowrap flags for now. We could in some cases
4630 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4631 return getAddExpr(Ops);
4632 }
4633 // Any other expression must be a pointer base.
4634 return getZero(P->getType());
4635}
4636
4638 SCEVFlags Flags, unsigned Depth) {
4639 // Fast path: X - X --> 0.
4640 if (SCEVUse::getCommon(LHS, RHS))
4641 return getZero(LHS->getType());
4642
4643 // If we subtract two pointers with different pointer bases, bail.
4644 // Eventually, we're going to add an assertion to getMulExpr that we
4645 // can't multiply by a pointer.
4646 if (RHS->getType()->isPointerTy()) {
4647 if (!LHS->getType()->isPointerTy() ||
4648 getPointerBase(LHS) != getPointerBase(RHS))
4649 return getCouldNotCompute();
4650 LHS = removePointerBase(LHS);
4651 RHS = removePointerBase(RHS);
4652 }
4653
4654 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4655 // makes it so that we cannot make much use of NUW.
4656 auto AddFlags = SCEV::FlagNone;
4657 const bool RHSIsNotMinSigned =
4659 if (hasFlags(Flags, SCEV::FlagNSW)) {
4660 // Let M be the minimum representable signed value. Then (-1)*RHS
4661 // signed-wraps if and only if RHS is M. That can happen even for
4662 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4663 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4664 // (-1)*RHS, we need to prove that RHS != M.
4665 //
4666 // If LHS is non-negative and we know that LHS - RHS does not
4667 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4668 // either by proving that RHS > M or that LHS >= 0.
4669 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4670 AddFlags = SCEV::FlagNSW;
4671 }
4672 }
4673
4674 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4675 // RHS is NSW and LHS >= 0.
4676 //
4677 // The difficulty here is that the NSW flag may have been proven
4678 // relative to a loop that is to be found in a recurrence in LHS and
4679 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4680 // larger scope than intended.
4681 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4682
4683 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4684}
4685
4687 unsigned Depth) {
4688 Type *SrcTy = V->getType();
4689 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4690 "Cannot truncate or zero extend with non-integer arguments!");
4691 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4692 return V; // No conversion
4693 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4694 return getTruncateExpr(V, Ty, Depth);
4695 return getZeroExtendExpr(V, Ty, Depth);
4696}
4697
4699 unsigned Depth) {
4700 Type *SrcTy = V->getType();
4701 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4702 "Cannot truncate or zero extend with non-integer arguments!");
4703 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4704 return V; // No conversion
4705 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4706 return getTruncateExpr(V, Ty, Depth);
4707 return getSignExtendExpr(V, Ty, Depth);
4708}
4709
4711 Type *SrcTy = V->getType();
4712 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4713 "Cannot noop or zero extend with non-integer arguments!");
4715 "getNoopOrZeroExtend cannot truncate!");
4716 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4717 return V; // No conversion
4718 return getZeroExtendExpr(V, Ty);
4719}
4720
4722 Type *SrcTy = V->getType();
4723 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4724 "Cannot noop or sign extend with non-integer arguments!");
4726 "getNoopOrSignExtend cannot truncate!");
4727 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4728 return V; // No conversion
4729 return getSignExtendExpr(V, Ty);
4730}
4731
4733 Type *SrcTy = V->getType();
4734 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4735 "Cannot noop or any extend with non-integer arguments!");
4737 "getNoopOrAnyExtend cannot truncate!");
4738 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4739 return V; // No conversion
4740 return getAnyExtendExpr(V, Ty);
4741}
4742
4744 Type *SrcTy = V->getType();
4745 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4746 "Cannot truncate or noop with non-integer arguments!");
4748 "getTruncateOrNoop cannot extend!");
4749 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4750 return V; // No conversion
4751 return getTruncateExpr(V, Ty);
4752}
4753
4755 const SCEV *RHS) {
4756 const SCEV *PromotedLHS = LHS;
4757 const SCEV *PromotedRHS = RHS;
4758
4759 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4760 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4761 else
4762 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4763
4764 return getUMaxExpr(PromotedLHS, PromotedRHS);
4765}
4766
4768 const SCEV *RHS,
4769 bool Sequential) {
4770 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4771 return getUMinFromMismatchedTypes(Ops, Sequential);
4772}
4773
4774const SCEV *
4776 bool Sequential) {
4777 assert(!Ops.empty() && "At least one operand must be!");
4778 // Trivial case.
4779 if (Ops.size() == 1)
4780 return Ops[0];
4781
4782 // Find the max type first.
4783 Type *MaxType = nullptr;
4784 for (SCEVUse S : Ops)
4785 if (MaxType)
4786 MaxType = getWiderType(MaxType, S->getType());
4787 else
4788 MaxType = S->getType();
4789 assert(MaxType && "Failed to find maximum type!");
4790
4791 // Extend all ops to max type.
4792 SmallVector<SCEVUse, 2> PromotedOps;
4793 for (SCEVUse S : Ops)
4794 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4795
4796 // Generate umin.
4797 return getUMinExpr(PromotedOps, Sequential);
4798}
4799
4801 // A pointer operand may evaluate to a nonpointer expression, such as null.
4802 if (!V->getType()->isPointerTy())
4803 return V;
4804
4805 while (true) {
4806 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4807 V = AddRec->getStart();
4808 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4809 const SCEV *PtrOp = nullptr;
4810 for (const SCEV *AddOp : Add->operands()) {
4811 if (AddOp->getType()->isPointerTy()) {
4812 assert(!PtrOp && "Cannot have multiple pointer ops");
4813 PtrOp = AddOp;
4814 }
4815 }
4816 assert(PtrOp && "Must have pointer op");
4817 V = PtrOp;
4818 } else // Not something we can look further into.
4819 return V;
4820 }
4821}
4822
4823/// Push users of the given Instruction onto the given Worklist.
4827 // Push the def-use children onto the Worklist stack.
4828 for (User *U : I->users()) {
4829 auto *UserInsn = cast<Instruction>(U);
4830 if (Visited.insert(UserInsn).second)
4831 Worklist.push_back(UserInsn);
4832 }
4833}
4834
4835namespace {
4836
4837/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4838/// expression in case its Loop is L. If it is not L then
4839/// if IgnoreOtherLoops is true then use AddRec itself
4840/// otherwise rewrite cannot be done.
4841/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4842class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4843public:
4844 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4845 bool IgnoreOtherLoops = true) {
4846 SCEVInitRewriter Rewriter(L, SE);
4847 const SCEV *Result = Rewriter.visit(S);
4848 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4849 return SE.getCouldNotCompute();
4850 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4851 ? SE.getCouldNotCompute()
4852 : Result;
4853 }
4854
4855 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4856 if (!SE.isLoopInvariant(Expr, L))
4857 SeenLoopVariantSCEVUnknown = true;
4858 return Expr;
4859 }
4860
4861 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4862 // Only re-write AddRecExprs for this loop.
4863 if (Expr->getLoop() == L)
4864 return Expr->getStart();
4865 SeenOtherLoops = true;
4866 return Expr;
4867 }
4868
4869 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4870
4871 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4872
4873private:
4874 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4875 : SCEVRewriteVisitor(SE), L(L) {}
4876
4877 const Loop *L;
4878 bool SeenLoopVariantSCEVUnknown = false;
4879 bool SeenOtherLoops = false;
4880};
4881
4882/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4883/// increment expression in case its Loop is L. If it is not L then
4884/// use AddRec itself.
4885/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4886class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4887public:
4888 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4889 SCEVPostIncRewriter Rewriter(L, SE);
4890 const SCEV *Result = Rewriter.visit(S);
4891 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4892 ? SE.getCouldNotCompute()
4893 : Result;
4894 }
4895
4896 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4897 if (!SE.isLoopInvariant(Expr, L))
4898 SeenLoopVariantSCEVUnknown = true;
4899 return Expr;
4900 }
4901
4902 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4903 // Only re-write AddRecExprs for this loop.
4904 if (Expr->getLoop() == L)
4905 return Expr->getPostIncExpr(SE);
4906 SeenOtherLoops = true;
4907 return Expr;
4908 }
4909
4910 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4911
4912 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4913
4914private:
4915 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4916 : SCEVRewriteVisitor(SE), L(L) {}
4917
4918 const Loop *L;
4919 bool SeenLoopVariantSCEVUnknown = false;
4920 bool SeenOtherLoops = false;
4921};
4922
4923/// This class evaluates the compare condition by matching it against the
4924/// condition of loop latch. If there is a match we assume a true value
4925/// for the condition while building SCEV nodes.
4926class SCEVBackedgeConditionFolder
4927 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4928public:
4929 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4930 ScalarEvolution &SE) {
4931 bool IsPosBECond = false;
4932 Value *BECond = nullptr;
4933 if (BasicBlock *Latch = L->getLoopLatch()) {
4934 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4935 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4936 "Both outgoing branches should not target same header!");
4937 BECond = BI->getCondition();
4938 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4939 } else {
4940 return S;
4941 }
4942 }
4943 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4944 return Rewriter.visit(S);
4945 }
4946
4947 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4948 const SCEV *Result = Expr;
4949 bool InvariantF = SE.isLoopInvariant(Expr, L);
4950
4951 if (!InvariantF) {
4953 switch (I->getOpcode()) {
4954 case Instruction::Select: {
4955 SelectInst *SI = cast<SelectInst>(I);
4956 std::optional<const SCEV *> Res =
4957 compareWithBackedgeCondition(SI->getCondition());
4958 if (Res) {
4959 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4960 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4961 }
4962 break;
4963 }
4964 default: {
4965 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4966 if (Res)
4967 Result = *Res;
4968 break;
4969 }
4970 }
4971 }
4972 return Result;
4973 }
4974
4975private:
4976 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4977 bool IsPosBECond, ScalarEvolution &SE)
4978 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4979 IsPositiveBECond(IsPosBECond) {}
4980
4981 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4982
4983 const Loop *L;
4984 /// Loop back condition.
4985 Value *BackedgeCond = nullptr;
4986 /// Set to true if loop back is on positive branch condition.
4987 bool IsPositiveBECond;
4988};
4989
4990std::optional<const SCEV *>
4991SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4992
4993 // If value matches the backedge condition for loop latch,
4994 // then return a constant evolution node based on loopback
4995 // branch taken.
4996 if (BackedgeCond == IC)
4997 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4999 return std::nullopt;
5000}
5001
5002class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5003public:
5004 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5005 ScalarEvolution &SE) {
5006 SCEVShiftRewriter Rewriter(L, SE);
5007 const SCEV *Result = Rewriter.visit(S);
5008 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5009 }
5010
5011 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5012 // Only allow AddRecExprs for this loop.
5013 if (!SE.isLoopInvariant(Expr, L))
5014 Valid = false;
5015 return Expr;
5016 }
5017
5018 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5019 if (Expr->getLoop() == L && Expr->isAffine())
5020 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5021 Valid = false;
5022 return Expr;
5023 }
5024
5025 bool isValid() { return Valid; }
5026
5027private:
5028 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5029 : SCEVRewriteVisitor(SE), L(L) {}
5030
5031 const Loop *L;
5032 bool Valid = true;
5033};
5034
5035} // end anonymous namespace
5036
5037void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5038 if (!AR->isAffine())
5039 return;
5040
5041 // Force computation of ranges, which will also perform range-based flag
5042 // inference.
5043 if (!AR->hasNoSignedWrap())
5044 (void)getSignedRange(AR);
5045
5046 if (!AR->hasNoUnsignedWrap())
5047 (void)getUnsignedRange(AR);
5048
5049 if (!AR->hasNoSelfWrap()) {
5050 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5051 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5052 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5053 const APInt &BECountAP = BECountMax->getAPInt();
5054 unsigned NoOverflowBitWidth =
5055 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5056 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5057 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5058 }
5059 }
5060}
5061
5063ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5065
5066 if (AR->hasNoSignedWrap())
5067 return Result;
5068
5069 if (!AR->isAffine())
5070 return Result;
5071
5072 // This function can be expensive, only try to prove NSW once per AddRec.
5073 if (!SignedWrapViaInductionTried.insert(AR).second)
5074 return Result;
5075
5076 const SCEV *Step = AR->getStepRecurrence(*this);
5077 const Loop *L = AR->getLoop();
5078
5079 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5080 // Note that this serves two purposes: It filters out loops that are
5081 // simply not analyzable, and it covers the case where this code is
5082 // being called from within backedge-taken count analysis, such that
5083 // attempting to ask for the backedge-taken count would likely result
5084 // in infinite recursion. In the later case, the analysis code will
5085 // cope with a conservative value, and it will take care to purge
5086 // that value once it has finished.
5087 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5088
5089 // Normally, in the cases we can prove no-overflow via a
5090 // backedge guarding condition, we can also compute a backedge
5091 // taken count for the loop. The exceptions are assumptions and
5092 // guards present in the loop -- SCEV is not great at exploiting
5093 // these to compute max backedge taken counts, but can still use
5094 // these to prove lack of overflow. Use this fact to avoid
5095 // doing extra work that may not pay off.
5096
5097 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5098 AC.assumptions().empty())
5099 return Result;
5100
5101 // If the backedge is guarded by a comparison with the pre-inc value the
5102 // addrec is safe. Also, if the entry is guarded by a comparison with the
5103 // start value and the backedge is guarded by a comparison with the post-inc
5104 // value, the addrec is safe.
5106 const SCEV *OverflowLimit =
5107 getSignedOverflowLimitForStep(Step, &Pred, this);
5108 if (OverflowLimit &&
5109 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5110 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5111 Result = setFlags(Result, SCEV::FlagNSW);
5112 }
5113 return Result;
5114}
5116ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5118
5119 if (AR->hasNoUnsignedWrap())
5120 return Result;
5121
5122 if (!AR->isAffine())
5123 return Result;
5124
5125 // This function can be expensive, only try to prove NUW once per AddRec.
5126 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5127 return Result;
5128
5129 const SCEV *Step = AR->getStepRecurrence(*this);
5130 const Loop *L = AR->getLoop();
5131
5132 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5133 // Note that this serves two purposes: It filters out loops that are
5134 // simply not analyzable, and it covers the case where this code is
5135 // being called from within backedge-taken count analysis, such that
5136 // attempting to ask for the backedge-taken count would likely result
5137 // in infinite recursion. In the later case, the analysis code will
5138 // cope with a conservative value, and it will take care to purge
5139 // that value once it has finished.
5140 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5141
5142 // Normally, in the cases we can prove no-overflow via a
5143 // backedge guarding condition, we can also compute a backedge
5144 // taken count for the loop. The exceptions are assumptions and
5145 // guards present in the loop -- SCEV is not great at exploiting
5146 // these to compute max backedge taken counts, but can still use
5147 // these to prove lack of overflow. Use this fact to avoid
5148 // doing extra work that may not pay off.
5149
5150 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5151 AC.assumptions().empty())
5152 return Result;
5153
5154 // If the backedge is guarded by a comparison with the pre-inc value the
5155 // addrec is safe. Also, if the entry is guarded by a comparison with the
5156 // start value and the backedge is guarded by a comparison with the post-inc
5157 // value, the addrec is safe.
5158 if (isKnownPositive(Step)) {
5160 const SCEV *OverflowLimit =
5161 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5162 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5163 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5164 Result = setFlags(Result, SCEV::FlagNUW);
5165 }
5166 return Result;
5167}
5168
5169namespace {
5170
5171/// Represents an abstract binary operation. This may exist as a
5172/// normal instruction or constant expression, or may have been
5173/// derived from an expression tree.
5174struct BinaryOp {
5175 unsigned Opcode;
5176 Value *LHS;
5177 Value *RHS;
5178 bool IsNSW = false;
5179 bool IsNUW = false;
5180
5181 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5182 /// constant expression.
5183 Operator *Op = nullptr;
5184
5185 explicit BinaryOp(Operator *Op)
5186 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5187 Op(Op) {
5188 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5189 IsNSW = OBO->hasNoSignedWrap();
5190 IsNUW = OBO->hasNoUnsignedWrap();
5191 }
5192 }
5193
5194 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5195 bool IsNUW = false)
5196 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5197};
5198
5199} // end anonymous namespace
5200
5201/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5202static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5203 AssumptionCache &AC,
5204 const DominatorTree &DT,
5205 const Instruction *CtxI) {
5206 auto *Op = dyn_cast<Operator>(V);
5207 if (!Op)
5208 return std::nullopt;
5209
5210 // Implementation detail: all the cleverness here should happen without
5211 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5212 // SCEV expressions when possible, and we should not break that.
5213
5214 switch (Op->getOpcode()) {
5215 case Instruction::Add:
5216 case Instruction::Sub:
5217 case Instruction::Mul:
5218 case Instruction::UDiv:
5219 case Instruction::URem:
5220 case Instruction::And:
5221 case Instruction::AShr:
5222 case Instruction::Shl:
5223 return BinaryOp(Op);
5224
5225 case Instruction::Or: {
5226 // Convert or disjoint into add nuw nsw.
5227 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5228 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5229 /*IsNSW=*/true, /*IsNUW=*/true);
5230 // Keep the reference to the original instruction so that we can later
5231 // check whether it can produce poison value or not.
5232 BinOp.Op = Op;
5233 return BinOp;
5234 }
5235 return BinaryOp(Op);
5236 }
5237
5238 case Instruction::Xor:
5239 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5240 // If the RHS of the xor is a signmask, then this is just an add.
5241 // Instcombine turns add of signmask into xor as a strength reduction step.
5242 if (RHSC->getValue().isSignMask())
5243 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5244 // Binary `xor` is a bit-wise `add`.
5245 if (V->getType()->isIntegerTy(1))
5246 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5247 return BinaryOp(Op);
5248
5249 case Instruction::LShr:
5250 // Turn logical shift right of a constant into a unsigned divide.
5251 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5252 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5253
5254 // If the shift count is not less than the bitwidth, the result of
5255 // the shift is undefined. Don't try to analyze it, because the
5256 // resolution chosen here may differ from the resolution chosen in
5257 // other parts of the compiler.
5258 if (SA->getValue().ult(BitWidth)) {
5259 Constant *X =
5260 ConstantInt::get(SA->getContext(),
5261 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5262 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5263 }
5264 }
5265 return BinaryOp(Op);
5266
5267 case Instruction::ExtractValue: {
5268 auto *EVI = cast<ExtractValueInst>(Op);
5269 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5270 break;
5271
5272 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5273 if (!WO)
5274 break;
5275
5276 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5277 bool Signed = WO->isSigned();
5278 // TODO: Should add nuw/nsw flags for mul as well.
5279 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5280 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5281
5282 // Now that we know that all uses of the arithmetic-result component of
5283 // CI are guarded by the overflow check, we can go ahead and pretend
5284 // that the arithmetic is non-overflowing.
5285 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5286 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5287 }
5288
5289 default:
5290 break;
5291 }
5292
5293 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5294 // semantics as a Sub, return a binary sub expression.
5295 if (auto *II = dyn_cast<IntrinsicInst>(V))
5296 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5297 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5298
5299 return std::nullopt;
5300}
5301
5302/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5303/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5304/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5305/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5306/// follows one of the following patterns:
5307/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5308/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5309/// If the SCEV expression of \p Op conforms with one of the expected patterns
5310/// we return the type of the truncation operation, and indicate whether the
5311/// truncated type should be treated as signed/unsigned by setting
5312/// \p Signed to true/false, respectively.
5313static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5314 bool &Signed, ScalarEvolution &SE) {
5315 // The case where Op == SymbolicPHI (that is, with no type conversions on
5316 // the way) is handled by the regular add recurrence creating logic and
5317 // would have already been triggered in createAddRecForPHI. Reaching it here
5318 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5319 // because one of the other operands of the SCEVAddExpr updating this PHI is
5320 // not invariant).
5321 //
5322 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5323 // this case predicates that allow us to prove that Op == SymbolicPHI will
5324 // be added.
5325 if (Op == SymbolicPHI)
5326 return nullptr;
5327
5328 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5329 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5330 if (SourceBits != NewBits)
5331 return nullptr;
5332
5333 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5334 Signed = true;
5335 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5336 }
5337 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5338 Signed = false;
5339 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5340 }
5341 return nullptr;
5342}
5343
5344static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5345 if (!PN->getType()->isIntegerTy())
5346 return nullptr;
5347 const Loop *L = LI.getLoopFor(PN->getParent());
5348 if (!L || L->getHeader() != PN->getParent())
5349 return nullptr;
5350 return L;
5351}
5352
5353// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5354// computation that updates the phi follows the following pattern:
5355// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5356// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5357// If so, try to see if it can be rewritten as an AddRecExpr under some
5358// Predicates. If successful, return them as a pair. Also cache the results
5359// of the analysis.
5360//
5361// Example usage scenario:
5362// Say the Rewriter is called for the following SCEV:
5363// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5364// where:
5365// %X = phi i64 (%Start, %BEValue)
5366// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5367// and call this function with %SymbolicPHI = %X.
5368//
5369// The analysis will find that the value coming around the backedge has
5370// the following SCEV:
5371// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5372// Upon concluding that this matches the desired pattern, the function
5373// will return the pair {NewAddRec, SmallPredsVec} where:
5374// NewAddRec = {%Start,+,%Step}
5375// SmallPredsVec = {P1, P2, P3} as follows:
5376// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5377// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5378// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5379// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5380// under the predicates {P1,P2,P3}.
5381// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5382// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5383//
5384// TODO's:
5385//
5386// 1) Extend the Induction descriptor to also support inductions that involve
5387// casts: When needed (namely, when we are called in the context of the
5388// vectorizer induction analysis), a Set of cast instructions will be
5389// populated by this method, and provided back to isInductionPHI. This is
5390// needed to allow the vectorizer to properly record them to be ignored by
5391// the cost model and to avoid vectorizing them (otherwise these casts,
5392// which are redundant under the runtime overflow checks, will be
5393// vectorized, which can be costly).
5394//
5395// 2) Support additional induction/PHISCEV patterns: We also want to support
5396// inductions where the sext-trunc / zext-trunc operations (partly) occur
5397// after the induction update operation (the induction increment):
5398//
5399// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5400// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5401//
5402// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5403// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5404//
5405// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5406std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5407ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5409
5410 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5411 // return an AddRec expression under some predicate.
5412
5413 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5414 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5415 assert(L && "Expecting an integer loop header phi");
5416
5417 // The loop may have multiple entrances or multiple exits; we can analyze
5418 // this phi as an addrec if it has a unique entry value and a unique
5419 // backedge value.
5420 Value *BEValueV = nullptr, *StartValueV = nullptr;
5421 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5422 Value *V = PN->getIncomingValue(i);
5423 if (L->contains(PN->getIncomingBlock(i))) {
5424 if (!BEValueV) {
5425 BEValueV = V;
5426 } else if (BEValueV != V) {
5427 BEValueV = nullptr;
5428 break;
5429 }
5430 } else if (!StartValueV) {
5431 StartValueV = V;
5432 } else if (StartValueV != V) {
5433 StartValueV = nullptr;
5434 break;
5435 }
5436 }
5437 if (!BEValueV || !StartValueV)
5438 return std::nullopt;
5439
5440 const SCEV *BEValue = getSCEV(BEValueV);
5441
5442 // If the value coming around the backedge is an add with the symbolic
5443 // value we just inserted, possibly with casts that we can ignore under
5444 // an appropriate runtime guard, then we found a simple induction variable!
5445 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5446 if (!Add)
5447 return std::nullopt;
5448
5449 // If there is a single occurrence of the symbolic value, possibly
5450 // casted, replace it with a recurrence.
5451 unsigned FoundIndex = Add->getNumOperands();
5452 Type *TruncTy = nullptr;
5453 bool Signed;
5454 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5455 if ((TruncTy =
5456 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5457 if (FoundIndex == e) {
5458 FoundIndex = i;
5459 break;
5460 }
5461
5462 if (FoundIndex == Add->getNumOperands())
5463 return std::nullopt;
5464
5465 // Create an add with everything but the specified operand.
5467 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5468 if (i != FoundIndex)
5469 Ops.push_back(Add->getOperand(i));
5470 const SCEV *Accum = getAddExpr(Ops);
5471
5472 // The runtime checks will not be valid if the step amount is
5473 // varying inside the loop.
5474 if (!isLoopInvariant(Accum, L))
5475 return std::nullopt;
5476
5477 // *** Part2: Create the predicates
5478
5479 // Analysis was successful: we have a phi-with-cast pattern for which we
5480 // can return an AddRec expression under the following predicates:
5481 //
5482 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5483 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5484 // P2: An Equal predicate that guarantees that
5485 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5486 // P3: An Equal predicate that guarantees that
5487 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5488 //
5489 // As we next prove, the above predicates guarantee that:
5490 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5491 //
5492 //
5493 // More formally, we want to prove that:
5494 // Expr(i+1) = Start + (i+1) * Accum
5495 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5496 //
5497 // Given that:
5498 // 1) Expr(0) = Start
5499 // 2) Expr(1) = Start + Accum
5500 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5501 // 3) Induction hypothesis (step i):
5502 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5503 //
5504 // Proof:
5505 // Expr(i+1) =
5506 // = Start + (i+1)*Accum
5507 // = (Start + i*Accum) + Accum
5508 // = Expr(i) + Accum
5509 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5510 // :: from step i
5511 //
5512 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5513 //
5514 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5515 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5516 // + Accum :: from P3
5517 //
5518 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5519 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5520 //
5521 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5522 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5523 //
5524 // By induction, the same applies to all iterations 1<=i<n:
5525 //
5526
5527 // Create a truncated addrec for which we will add a no overflow check (P1).
5528 const SCEV *StartVal = getSCEV(StartValueV);
5529 const SCEV *PHISCEV =
5530 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5531 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5532
5533 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5534 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5535 // will be constant.
5536 //
5537 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5538 // add P1.
5539 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5543 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5544 Predicates.push_back(AddRecPred);
5545 }
5546
5547 // Create the Equal Predicates P2,P3:
5548
5549 // It is possible that the predicates P2 and/or P3 are computable at
5550 // compile time due to StartVal and/or Accum being constants.
5551 // If either one is, then we can check that now and escape if either P2
5552 // or P3 is false.
5553
5554 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5555 // for each of StartVal and Accum
5556 auto getExtendedExpr = [&](const SCEV *Expr,
5557 bool CreateSignExtend) -> const SCEV * {
5558 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5559 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5560 const SCEV *ExtendedExpr =
5561 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5562 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5563 return ExtendedExpr;
5564 };
5565
5566 // Given:
5567 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5568 // = getExtendedExpr(Expr)
5569 // Determine whether the predicate P: Expr == ExtendedExpr
5570 // is known to be false at compile time
5571 auto PredIsKnownFalse = [&](const SCEV *Expr,
5572 const SCEV *ExtendedExpr) -> bool {
5573 return Expr != ExtendedExpr &&
5574 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5575 };
5576
5577 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5578 if (PredIsKnownFalse(StartVal, StartExtended)) {
5579 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5580 return std::nullopt;
5581 }
5582
5583 // The Step is always Signed (because the overflow checks are either
5584 // NSSW or NUSW)
5585 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5586 if (PredIsKnownFalse(Accum, AccumExtended)) {
5587 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5588 return std::nullopt;
5589 }
5590
5591 auto AppendPredicate = [&](const SCEV *Expr,
5592 const SCEV *ExtendedExpr) -> void {
5593 if (Expr != ExtendedExpr &&
5594 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5595 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5596 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5597 Predicates.push_back(Pred);
5598 }
5599 };
5600
5601 AppendPredicate(StartVal, StartExtended);
5602 AppendPredicate(Accum, AccumExtended);
5603
5604 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5605 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5606 // into NewAR if it will also add the runtime overflow checks specified in
5607 // Predicates.
5608 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5609
5610 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5611 std::make_pair(NewAR, Predicates);
5612 // Remember the result of the analysis for this SCEV at this locayyytion.
5613 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5614 return PredRewrite;
5615}
5616
5617std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5619 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5620 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5621 if (!L)
5622 return std::nullopt;
5623
5624 // Check to see if we already analyzed this PHI.
5625 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5626 if (I != PredicatedSCEVRewrites.end()) {
5627 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5628 I->second;
5629 // Analysis was done before and failed to create an AddRec:
5630 if (Rewrite.first == SymbolicPHI)
5631 return std::nullopt;
5632 // Analysis was done before and succeeded to create an AddRec under
5633 // a predicate:
5634 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5635 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5636 return Rewrite;
5637 }
5638
5639 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5640 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5641
5642 // Record in the cache that the analysis failed
5643 if (!Rewrite) {
5645 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5646 return std::nullopt;
5647 }
5648
5649 return Rewrite;
5650}
5651
5652// FIXME: This utility is currently required because the Rewriter currently
5653// does not rewrite this expression:
5654// {0, +, (sext ix (trunc iy to ix) to iy)}
5655// into {0, +, %step},
5656// even when the following Equal predicate exists:
5657// "%step == (sext ix (trunc iy to ix) to iy)".
5659 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5660 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5661 if (AR1 == AR2)
5662 return true;
5663
5664 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5665 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5666 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5667 if (Expr1 != Expr2 &&
5668 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5669 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5670 return false;
5671 return true;
5672 };
5673
5674 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5675 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5676 return false;
5677 return true;
5678}
5679
5681 ScalarEvolution &SE) {
5682 SCEVFlags Flags = SCEV::FlagNone;
5683 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5684 // If the increment has any nowrap flags, then we know the address
5685 // space cannot be wrapped around.
5686 if (NW != GEPNoWrapFlags::none())
5688 // If the GEP is nuw or nusw with non-negative offset, we know that
5689 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5690 // offset is treated as signed, while the base is unsigned.
5691 if (NW.hasNoUnsignedWrap() ||
5692 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5694
5695 return Flags;
5696}
5697
5698/// A helper function for createAddRecFromPHI to handle simple cases.
5699///
5700/// This function tries to find an AddRec expression for the simplest (yet most
5701/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5702/// If it fails, createAddRecFromPHI will use a more general, but slow,
5703/// technique for finding the AddRec expression.
5704const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5705 Value *BEValueV,
5706 Value *StartValueV) {
5707 const Loop *L = LI.getLoopFor(PN->getParent());
5708 assert(L && L->getHeader() == PN->getParent());
5709 assert(BEValueV && StartValueV);
5710
5711 const SCEV *Accum = nullptr;
5713 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5714 if (BO->Opcode != Instruction::Add)
5715 return nullptr;
5716
5717 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5718 Accum = getSCEV(BO->RHS);
5719 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5720 Accum = getSCEV(BO->LHS);
5721
5722 if (!Accum)
5723 return nullptr;
5724
5725 if (BO->IsNUW)
5726 Flags = setFlags(Flags, SCEV::FlagNUW);
5727 if (BO->IsNSW)
5728 Flags = setFlags(Flags, SCEV::FlagNSW);
5729 } else {
5730 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5731 // LoopInvariant).
5732 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5733 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5734 return nullptr;
5735 Value *Idx = *GEP->idx_begin();
5736 if (!L->isLoopInvariant(Idx))
5737 return nullptr;
5738
5739 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5740 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5741 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5742 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5743 }
5744
5745 const SCEV *StartVal = getSCEV(StartValueV);
5746 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5747 insertValueToMap(PN, PHISCEV);
5748
5749 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5750 inferNoWrapViaConstantRanges(AR);
5751
5752 // We can add Flags to the post-inc expression only if we
5753 // know that it is *undefined behavior* for BEValueV to
5754 // overflow.
5755 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5756 assert(isLoopInvariant(Accum, L) &&
5757 "Accum is defined outside L, but is not invariant?");
5758 if (isAddRecNeverPoison(BEInst, L))
5759 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5760 }
5761
5762 return PHISCEV;
5763}
5764
5765const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5766 const Loop *L = LI.getLoopFor(PN->getParent());
5767 if (!L || L->getHeader() != PN->getParent())
5768 return nullptr;
5769
5770 // The loop may have multiple entrances or multiple exits; we can analyze
5771 // this phi as an addrec if it has a unique entry value and a unique
5772 // backedge value.
5773 Value *BEValueV = nullptr, *StartValueV = nullptr;
5774 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5775 Value *V = PN->getIncomingValue(i);
5776 if (L->contains(PN->getIncomingBlock(i))) {
5777 if (!BEValueV) {
5778 BEValueV = V;
5779 } else if (BEValueV != V) {
5780 BEValueV = nullptr;
5781 break;
5782 }
5783 } else if (!StartValueV) {
5784 StartValueV = V;
5785 } else if (StartValueV != V) {
5786 StartValueV = nullptr;
5787 break;
5788 }
5789 }
5790 if (!BEValueV || !StartValueV)
5791 return nullptr;
5792
5793 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5794 "PHI node already processed?");
5795
5796 // First, try to find AddRec expression without creating a fictituos symbolic
5797 // value for PN.
5798 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5799 return S;
5800
5801 // Handle PHI node value symbolically.
5802 const SCEV *SymbolicName = getUnknown(PN);
5803 insertValueToMap(PN, SymbolicName);
5804
5805 // Using this symbolic name for the PHI, analyze the value coming around
5806 // the back-edge.
5807 const SCEV *BEValue = getSCEV(BEValueV);
5808
5809 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5810 // has a special value for the first iteration of the loop.
5811
5812 // If the value coming around the backedge is an add with the symbolic
5813 // value we just inserted, then we found a simple induction variable!
5814 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5815 // If there is a single occurrence of the symbolic value, replace it
5816 // with a recurrence.
5817 unsigned FoundIndex = Add->getNumOperands();
5818 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5819 if (Add->getOperand(i) == SymbolicName)
5820 if (FoundIndex == e) {
5821 FoundIndex = i;
5822 break;
5823 }
5824
5825 if (FoundIndex != Add->getNumOperands()) {
5826 // Create an add with everything but the specified operand.
5828 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5829 if (i != FoundIndex)
5830 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5831 L, *this));
5832 const SCEV *Accum = getAddExpr(Ops);
5833
5834 // This is not a valid addrec if the step amount is varying each
5835 // loop iteration, but is not itself an addrec in this loop.
5836 if (isLoopInvariant(Accum, L) ||
5837 (isa<SCEVAddRecExpr>(Accum) &&
5838 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5840
5841 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
5842 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5843 if (BO->IsNUW)
5844 Flags = setFlags(Flags, SCEV::FlagNUW);
5845 if (BO->IsNSW)
5846 Flags = setFlags(Flags, SCEV::FlagNSW);
5847 }
5848 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5849 if (GEP->getOperand(0) == PN)
5850 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5851
5852 // We cannot transfer nuw and nsw flags from subtraction
5853 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5854 // for instance.
5855 }
5856
5857 const SCEV *StartVal = getSCEV(StartValueV);
5858 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5859
5860 // Okay, for the entire analysis of this edge we assumed the PHI
5861 // to be symbolic. We now need to go back and purge all of the
5862 // entries for the scalars that use the symbolic expression.
5863 forgetMemoizedResults({SymbolicName});
5864 insertValueToMap(PN, PHISCEV);
5865
5866 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5867 inferNoWrapViaConstantRanges(AR);
5868
5869 // We can add Flags to the post-inc expression only if we
5870 // know that it is *undefined behavior* for BEValueV to
5871 // overflow.
5872 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5873 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5874 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5875
5876 return PHISCEV;
5877 }
5878 }
5879 } else {
5880 // Otherwise, this could be a loop like this:
5881 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5882 // In this case, j = {1,+,1} and BEValue is j.
5883 // Because the other in-value of i (0) fits the evolution of BEValue
5884 // i really is an addrec evolution.
5885 //
5886 // We can generalize this saying that i is the shifted value of BEValue
5887 // by one iteration:
5888 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5889
5890 // Do not allow refinement in rewriting of BEValue.
5891 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5892 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5893 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5894 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5895 const SCEV *StartVal = getSCEV(StartValueV);
5896 if (Start == StartVal) {
5897 // Okay, for the entire analysis of this edge we assumed the PHI
5898 // to be symbolic. We now need to go back and purge all of the
5899 // entries for the scalars that use the symbolic expression.
5900 forgetMemoizedResults({SymbolicName});
5901 insertValueToMap(PN, Shifted);
5902 return Shifted;
5903 }
5904 }
5905 }
5906
5907 // Remove the temporary PHI node SCEV that has been inserted while intending
5908 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5909 // as it will prevent later (possibly simpler) SCEV expressions to be added
5910 // to the ValueExprMap.
5911 eraseValueFromMap(PN);
5912
5913 return nullptr;
5914}
5915
5916// Try to match a control flow sequence that branches out at BI and merges back
5917// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5918// match.
5920 Value *&C, Value *&LHS, Value *&RHS) {
5921 C = BI->getCondition();
5922
5923 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5924 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5925
5926 Use &LeftUse = Merge->getOperandUse(0);
5927 Use &RightUse = Merge->getOperandUse(1);
5928
5929 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5930 LHS = LeftUse;
5931 RHS = RightUse;
5932 return true;
5933 }
5934
5935 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5936 LHS = RightUse;
5937 RHS = LeftUse;
5938 return true;
5939 }
5940
5941 return false;
5942}
5943
5945 Value *&Cond, Value *&LHS,
5946 Value *&RHS) {
5947 auto IsReachable =
5948 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5949 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5950 // Try to match
5951 //
5952 // br %cond, label %left, label %right
5953 // left:
5954 // br label %merge
5955 // right:
5956 // br label %merge
5957 // merge:
5958 // V = phi [ %x, %left ], [ %y, %right ]
5959 //
5960 // as "select %cond, %x, %y"
5961
5962 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5963 assert(IDom && "At least the entry block should dominate PN");
5964
5965 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5966 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5967 }
5968 return false;
5969}
5970
5971const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5972 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5973 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5976 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5977
5978 return nullptr;
5979}
5980
5982 BinaryOperator *CommonInst = nullptr;
5983 // Check if instructions are identical.
5984 for (Value *Incoming : PN->incoming_values()) {
5985 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
5986 if (!IncomingInst)
5987 return nullptr;
5988 if (CommonInst) {
5989 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
5990 return nullptr; // Not identical, give up
5991 } else {
5992 // Remember binary operator
5993 CommonInst = IncomingInst;
5994 }
5995 }
5996 return CommonInst;
5997}
5998
5999/// Returns SCEV for the first operand of a phi if all phi operands have
6000/// identical opcodes and operands
6001/// eg.
6002/// a: %add = %a + %b
6003/// br %c
6004/// b: %add1 = %a + %b
6005/// br %c
6006/// c: %phi = phi [%add, a], [%add1, b]
6007/// scev(%phi) => scev(%add)
6008const SCEV *
6009ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6010 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6011 if (!CommonInst)
6012 return nullptr;
6013
6014 // Check if SCEV exprs for instructions are identical.
6015 const SCEV *CommonSCEV = getSCEV(CommonInst);
6016 bool SCEVExprsIdentical =
6018 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6019 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6020}
6021
6022const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6023 if (const SCEV *S = createAddRecFromPHI(PN))
6024 return S;
6025
6026 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6027 // phi node for X.
6028 if (Value *V = simplifyInstruction(
6029 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6030 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6031 return getSCEV(V);
6032
6033 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6034 return S;
6035
6036 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6037 return S;
6038
6039 // If it's not a loop phi, we can't handle it yet.
6040 return getUnknown(PN);
6041}
6042
6043bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6044 SCEVTypes RootKind) {
6045 struct FindClosure {
6046 const SCEV *OperandToFind;
6047 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6048 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6049
6050 bool Found = false;
6051
6052 bool canRecurseInto(SCEVTypes Kind) const {
6053 // We can only recurse into the SCEV expression of the same effective type
6054 // as the type of our root SCEV expression, and into zero-extensions.
6055 return RootKind == Kind || NonSequentialRootKind == Kind ||
6056 scZeroExtend == Kind;
6057 };
6058
6059 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6060 : OperandToFind(OperandToFind), RootKind(RootKind),
6061 NonSequentialRootKind(
6063 RootKind)) {}
6064
6065 bool follow(const SCEV *S) {
6066 Found = S == OperandToFind;
6067
6068 return !isDone() && canRecurseInto(S->getSCEVType());
6069 }
6070
6071 bool isDone() const { return Found; }
6072 };
6073
6074 FindClosure FC(OperandToFind, RootKind);
6075 visitAll(Root, FC);
6076 return FC.Found;
6077}
6078
6079std::optional<const SCEV *>
6080ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6081 ICmpInst *Cond,
6082 Value *TrueVal,
6083 Value *FalseVal) {
6084 // Try to match some simple smax or umax patterns.
6085 auto *ICI = Cond;
6086
6087 Value *LHS = ICI->getOperand(0);
6088 Value *RHS = ICI->getOperand(1);
6089
6090 switch (ICI->getPredicate()) {
6091 case ICmpInst::ICMP_SLT:
6092 case ICmpInst::ICMP_SLE:
6093 case ICmpInst::ICMP_ULT:
6094 case ICmpInst::ICMP_ULE:
6095 std::swap(LHS, RHS);
6096 [[fallthrough]];
6097 case ICmpInst::ICMP_SGT:
6098 case ICmpInst::ICMP_SGE:
6099 case ICmpInst::ICMP_UGT:
6100 case ICmpInst::ICMP_UGE:
6101 // a > b ? a+x : b+x -> max(a, b)+x
6102 // a > b ? b+x : a+x -> min(a, b)+x
6104 bool Signed = ICI->isSigned();
6105 const SCEV *LA = getSCEV(TrueVal);
6106 const SCEV *RA = getSCEV(FalseVal);
6107 const SCEV *LS = getSCEV(LHS);
6108 const SCEV *RS = getSCEV(RHS);
6109 if (LA->getType()->isPointerTy()) {
6110 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6111 // Need to make sure we can't produce weird expressions involving
6112 // negated pointers.
6113 if (LA == LS && RA == RS)
6114 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6115 if (LA == RS && RA == LS)
6116 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6117 }
6118 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6119 if (Op->getType()->isPointerTy()) {
6122 return Op;
6123 }
6124 if (Signed)
6125 Op = getNoopOrSignExtend(Op, Ty);
6126 else
6127 Op = getNoopOrZeroExtend(Op, Ty);
6128 return Op;
6129 };
6130 LS = CoerceOperand(LS);
6131 RS = CoerceOperand(RS);
6133 break;
6134 const SCEV *LDiff = getMinusSCEV(LA, LS);
6135 const SCEV *RDiff = getMinusSCEV(RA, RS);
6136 if (LDiff == RDiff)
6137 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6138 LDiff);
6139 LDiff = getMinusSCEV(LA, RS);
6140 RDiff = getMinusSCEV(RA, LS);
6141 if (LDiff == RDiff)
6142 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6143 LDiff);
6144 }
6145 break;
6146 case ICmpInst::ICMP_NE:
6147 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6148 std::swap(TrueVal, FalseVal);
6149 [[fallthrough]];
6150 case ICmpInst::ICMP_EQ:
6151 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6154 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6155 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6156 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6157 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6158 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6159 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6160 return getAddExpr(getUMaxExpr(X, C), Y);
6161 }
6162 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6163 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6164 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6165 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6167 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6168 const SCEV *X = getSCEV(LHS);
6169 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6170 X = ZExt->getOperand();
6171 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6172 const SCEV *FalseValExpr = getSCEV(FalseVal);
6173 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6174 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6175 /*Sequential=*/true);
6176 }
6177 }
6178 break;
6179 default:
6180 break;
6181 }
6182
6183 return std::nullopt;
6184}
6185
6186static std::optional<const SCEV *>
6188 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6189 assert(CondExpr->getType()->isIntegerTy(1) &&
6190 TrueExpr->getType() == FalseExpr->getType() &&
6191 TrueExpr->getType()->isIntegerTy(1) &&
6192 "Unexpected operands of a select.");
6193
6194 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6195 // --> C + (umin_seq cond, x - C)
6196 //
6197 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6198 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6199 // --> C + (umin_seq ~cond, x - C)
6200
6201 // FIXME: while we can't legally model the case where both of the hands
6202 // are fully variable, we only require that the *difference* is constant.
6203 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6204 return std::nullopt;
6205
6206 const SCEV *X, *C;
6207 if (isa<SCEVConstant>(TrueExpr)) {
6208 CondExpr = SE->getNotSCEV(CondExpr);
6209 X = FalseExpr;
6210 C = TrueExpr;
6211 } else {
6212 X = TrueExpr;
6213 C = FalseExpr;
6214 }
6215 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6216 /*Sequential=*/true));
6217}
6218
6219static std::optional<const SCEV *>
6221 Value *FalseVal) {
6222 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6223 return std::nullopt;
6224
6225 const auto *SECond = SE->getSCEV(Cond);
6226 const auto *SETrue = SE->getSCEV(TrueVal);
6227 const auto *SEFalse = SE->getSCEV(FalseVal);
6228 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6229}
6230
6231const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6232 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6233 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6234 assert(TrueVal->getType() == FalseVal->getType() &&
6235 V->getType() == TrueVal->getType() &&
6236 "Types of select hands and of the result must match.");
6237
6238 // For now, only deal with i1-typed `select`s.
6239 if (!V->getType()->isIntegerTy(1))
6240 return getUnknown(V);
6241
6242 if (std::optional<const SCEV *> S =
6243 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6244 return *S;
6245
6246 return getUnknown(V);
6247}
6248
6249const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6250 Value *TrueVal,
6251 Value *FalseVal) {
6252 // Handle "constant" branch or select. This can occur for instance when a
6253 // loop pass transforms an inner loop and moves on to process the outer loop.
6254 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6255 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6256
6257 if (auto *I = dyn_cast<Instruction>(V)) {
6258 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6259 if (std::optional<const SCEV *> S =
6260 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6261 TrueVal, FalseVal))
6262 return *S;
6263 }
6264 }
6265
6266 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6267}
6268
6269/// Expand GEP instructions into add and multiply operations. This allows them
6270/// to be analyzed by regular SCEV code.
6271const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6272 assert(GEP->getSourceElementType()->isSized() &&
6273 "GEP source element type must be sized");
6274
6275 SmallVector<SCEVUse, 4> IndexExprs;
6276 for (Value *Index : GEP->indices())
6277 IndexExprs.push_back(getSCEV(Index));
6278 return getGEPExpr(GEP, IndexExprs);
6279}
6280
6281APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6282 const Instruction *CtxI) {
6284 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6285 return TrailingZeros >= BitWidth
6287 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6288 };
6289 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6290 // The result is GCD of all operands results.
6291 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6292 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6294 Res, getConstantMultiple(N->getOperand(I), CtxI));
6295 return Res;
6296 };
6297
6298 switch (S->getSCEVType()) {
6299 case scConstant:
6300 return cast<SCEVConstant>(S)->getAPInt();
6301 case scPtrToAddr:
6302 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6303 case scUDivExpr:
6304 case scVScale:
6305 return APInt(BitWidth, 1);
6306 case scTruncate: {
6307 // Only multiples that are a power of 2 will hold after truncation.
6308 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6309 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6310 return GetShiftedByZeros(TZ);
6311 }
6312 case scZeroExtend: {
6313 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6314 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6315 }
6316 case scSignExtend: {
6317 // Only multiples that are a power of 2 will hold after sext.
6318 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6319 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6320 return GetShiftedByZeros(TZ);
6321 }
6322 case scMulExpr: {
6323 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6324 if (M->hasNoUnsignedWrap()) {
6325 // The result is the product of all operand results.
6326 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6327 for (const SCEV *Operand : M->operands().drop_front())
6328 Res = Res * getConstantMultiple(Operand, CtxI);
6329 return Res;
6330 }
6331
6332 // If there are no wrap guarentees, find the trailing zeros, which is the
6333 // sum of trailing zeros for all its operands.
6334 uint32_t TZ = 0;
6335 for (const SCEV *Operand : M->operands())
6336 TZ += getMinTrailingZeros(Operand, CtxI);
6337 return GetShiftedByZeros(TZ);
6338 }
6339 case scAddExpr:
6340 case scAddRecExpr: {
6341 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6342 if (N->hasNoUnsignedWrap())
6343 return GetGCDMultiple(N);
6344 // Find the trailing bits, which is the minimum of its operands.
6345 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6346 for (const SCEV *Operand : N->operands().drop_front())
6347 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6348 return GetShiftedByZeros(TZ);
6349 }
6350 case scUMaxExpr:
6351 case scSMaxExpr:
6352 case scUMinExpr:
6353 case scSMinExpr:
6355 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6356 case scUnknown: {
6357 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6358 // the point their underlying IR instruction has been defined. If CtxI was
6359 // not provided, use:
6360 // * the first instruction in the entry block if it is an argument
6361 // * the instruction itself otherwise.
6362 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6363 if (!CtxI) {
6364 if (isa<Argument>(U->getValue()))
6365 CtxI = &*F.getEntryBlock().begin();
6366 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6367 CtxI = I;
6368 }
6369 unsigned Known =
6370 computeKnownBits(U->getValue(),
6371 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6372 .allowEphemerals(true))
6373 .countMinTrailingZeros();
6374 return GetShiftedByZeros(Known);
6375 }
6376 case scCouldNotCompute:
6377 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6378 }
6379 llvm_unreachable("Unknown SCEV kind!");
6380}
6381
6383 const Instruction *CtxI) {
6384 // Skip looking up and updating the cache if there is a context instruction,
6385 // as the result will only be valid in the specified context.
6386 if (CtxI)
6387 return getConstantMultipleImpl(S, CtxI);
6388
6389 auto I = ConstantMultipleCache.find(S);
6390 if (I != ConstantMultipleCache.end())
6391 return I->second;
6392
6393 APInt Result = getConstantMultipleImpl(S, CtxI);
6394 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6395 assert(InsertPair.second && "Should insert a new key");
6396 return InsertPair.first->second;
6397}
6398
6400 APInt Multiple = getConstantMultiple(S);
6401 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6402}
6403
6405 const Instruction *CtxI) {
6406 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6407 (unsigned)getTypeSizeInBits(S->getType()));
6408}
6409
6410/// Helper method to assign a range to V from metadata present in the IR.
6411static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6413 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6414 return getConstantRangeFromMetadata(*MD);
6415 if (const auto *CB = dyn_cast<CallBase>(V))
6416 if (std::optional<ConstantRange> Range = CB->getRange())
6417 return Range;
6418 }
6419 if (auto *A = dyn_cast<Argument>(V))
6420 if (std::optional<ConstantRange> Range = A->getRange())
6421 return Range;
6422
6423 return std::nullopt;
6424}
6425
6427 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6428 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6429 AddRec->setNoWrapFlags(NWFlags);
6430 UnsignedRanges.erase(AddRec);
6431 SignedRanges.erase(AddRec);
6432 ConstantMultipleCache.erase(AddRec);
6433 }
6434}
6435
6436ConstantRange ScalarEvolution::
6437getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6438 const DataLayout &DL = getDataLayout();
6439
6440 unsigned BitWidth = getTypeSizeInBits(U->getType());
6441 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6442
6443 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6444 // use information about the trip count to improve our available range. Note
6445 // that the trip count independent cases are already handled by known bits.
6446 // WARNING: The definition of recurrence used here is subtly different than
6447 // the one used by AddRec (and thus most of this file). Step is allowed to
6448 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6449 // and other addrecs in the same loop (for non-affine addrecs). The code
6450 // below intentionally handles the case where step is not loop invariant.
6451 auto *P = dyn_cast<PHINode>(U->getValue());
6452 if (!P)
6453 return FullSet;
6454
6455 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6456 // even the values that are not available in these blocks may come from them,
6457 // and this leads to false-positive recurrence test.
6458 for (auto *Pred : predecessors(P->getParent()))
6459 if (!DT.isReachableFromEntry(Pred))
6460 return FullSet;
6461
6462 BinaryOperator *BO;
6463 Value *Start, *Step;
6464 if (!matchSimpleRecurrence(P, BO, Start, Step))
6465 return FullSet;
6466
6467 // If we found a recurrence in reachable code, we must be in a loop. Note
6468 // that BO might be in some subloop of L, and that's completely okay.
6469 auto *L = LI.getLoopFor(P->getParent());
6470 assert(L && L->getHeader() == P->getParent());
6471 if (!L->contains(BO->getParent()))
6472 // NOTE: This bailout should be an assert instead. However, asserting
6473 // the condition here exposes a case where LoopFusion is querying SCEV
6474 // with malformed loop information during the midst of the transform.
6475 // There doesn't appear to be an obvious fix, so for the moment bailout
6476 // until the caller issue can be fixed. PR49566 tracks the bug.
6477 return FullSet;
6478
6479 // TODO: Extend to other opcodes such as mul, and div
6480 switch (BO->getOpcode()) {
6481 default:
6482 return FullSet;
6483 case Instruction::AShr:
6484 case Instruction::LShr:
6485 case Instruction::Shl:
6486 break;
6487 };
6488
6489 if (BO->getOperand(0) != P)
6490 // TODO: Handle the power function forms some day.
6491 return FullSet;
6492
6493 unsigned TC = getSmallConstantMaxTripCount(L);
6494 if (!TC || TC >= BitWidth)
6495 return FullSet;
6496
6497 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6498 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6499 assert(KnownStart.getBitWidth() == BitWidth &&
6500 KnownStep.getBitWidth() == BitWidth);
6501
6502 // Compute total shift amount, being careful of overflow and bitwidths.
6503 auto MaxShiftAmt = KnownStep.getMaxValue();
6504 APInt TCAP(BitWidth, TC-1);
6505 bool Overflow = false;
6506 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6507 if (Overflow)
6508 return FullSet;
6509
6510 switch (BO->getOpcode()) {
6511 default:
6512 llvm_unreachable("filtered out above");
6513 case Instruction::AShr: {
6514 // For each ashr, three cases:
6515 // shift = 0 => unchanged value
6516 // saturation => 0 or -1
6517 // other => a value closer to zero (of the same sign)
6518 // Thus, the end value is closer to zero than the start.
6519 auto KnownEnd = KnownBits::ashr(KnownStart,
6520 KnownBits::makeConstant(TotalShift));
6521 if (KnownStart.isNonNegative())
6522 // Analogous to lshr (simply not yet canonicalized)
6523 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6524 KnownStart.getMaxValue() + 1);
6525 if (KnownStart.isNegative())
6526 // End >=u Start && End <=s Start
6527 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6528 KnownEnd.getMaxValue() + 1);
6529 break;
6530 }
6531 case Instruction::LShr: {
6532 // For each lshr, three cases:
6533 // shift = 0 => unchanged value
6534 // saturation => 0
6535 // other => a smaller positive number
6536 // Thus, the low end of the unsigned range is the last value produced.
6537 auto KnownEnd = KnownBits::lshr(KnownStart,
6538 KnownBits::makeConstant(TotalShift));
6539 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6540 KnownStart.getMaxValue() + 1);
6541 }
6542 case Instruction::Shl: {
6543 // Iff no bits are shifted out, value increases on every shift.
6544 auto KnownEnd = KnownBits::shl(KnownStart,
6545 KnownBits::makeConstant(TotalShift));
6546 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6547 return ConstantRange(KnownStart.getMinValue(),
6548 KnownEnd.getMaxValue() + 1);
6549 break;
6550 }
6551 };
6552 return FullSet;
6553}
6554
6555// The goal of this function is to check if recursively visiting the operands
6556// of this PHI might lead to an infinite loop. If we do see such a loop,
6557// there's no good way to break it, so we avoid analyzing such cases.
6558//
6559// getRangeRef previously used a visited set to avoid infinite loops, but this
6560// caused other issues: the result was dependent on the order of getRangeRef
6561// calls, and the interaction with createSCEVIter could cause a stack overflow
6562// in some cases (see issue #148253).
6563//
6564// FIXME: The way this is implemented is overly conservative; this checks
6565// for a few obviously safe patterns, but anything that doesn't lead to
6566// recursion is fine.
6568 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6570 return true;
6571
6572 if (all_of(PHI->operands(),
6573 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6574 return true;
6575
6576 return false;
6577}
6578
6579const ConstantRange &
6580ScalarEvolution::getRangeRefIter(const SCEV *S,
6581 ScalarEvolution::RangeSignHint SignHint) {
6582 DenseMap<const SCEV *, ConstantRange> &Cache =
6583 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6584 : SignedRanges;
6585 SmallVector<SCEVUse> WorkList;
6586 SmallPtrSet<const SCEV *, 8> Seen;
6587
6588 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6589 // SCEVUnknown PHI node.
6590 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6591 if (!Seen.insert(Expr).second)
6592 return;
6593 if (Cache.contains(Expr))
6594 return;
6595 switch (Expr->getSCEVType()) {
6596 case scUnknown:
6598 break;
6599 [[fallthrough]];
6600 case scConstant:
6601 case scVScale:
6602 case scTruncate:
6603 case scZeroExtend:
6604 case scSignExtend:
6605 case scPtrToAddr:
6606 case scAddExpr:
6607 case scMulExpr:
6608 case scUDivExpr:
6609 case scAddRecExpr:
6610 case scUMaxExpr:
6611 case scSMaxExpr:
6612 case scUMinExpr:
6613 case scSMinExpr:
6615 WorkList.push_back(Expr);
6616 break;
6617 case scCouldNotCompute:
6618 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6619 }
6620 };
6621 AddToWorklist(S);
6622
6623 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6624 for (unsigned I = 0; I != WorkList.size(); ++I) {
6625 const SCEV *P = WorkList[I];
6626 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6627 // If it is not a `SCEVUnknown`, just recurse into operands.
6628 if (!UnknownS) {
6629 for (const SCEV *Op : P->operands())
6630 AddToWorklist(Op);
6631 continue;
6632 }
6633 // `SCEVUnknown`'s require special treatment.
6634 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6635 if (!RangeRefPHIAllowedOperands(DT, P))
6636 continue;
6637 for (auto &Op : reverse(P->operands()))
6638 AddToWorklist(getSCEV(Op));
6639 }
6640 }
6641
6642 if (!WorkList.empty()) {
6643 // Use getRangeRef to compute ranges for items in the worklist in reverse
6644 // order. This will force ranges for earlier operands to be computed before
6645 // their users in most cases.
6646 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6647 getRangeRef(P, SignHint);
6648 }
6649 }
6650
6651 return getRangeRef(S, SignHint, 0);
6652}
6653
6654const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6655 if (const auto *C = dyn_cast<SCEVConstant>(S))
6656 return &C->getAPInt();
6657 return nullptr;
6658}
6659
6660/// Determine the range for a particular SCEV. If SignHint is
6661/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6662/// with a "cleaner" unsigned (resp. signed) representation.
6663const ConstantRange &ScalarEvolution::getRangeRef(
6664 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6665 DenseMap<const SCEV *, ConstantRange> &Cache =
6666 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6667 : SignedRanges;
6669 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6671
6672 // See if we've computed this range already.
6673 auto I = Cache.find(S);
6674 if (I != Cache.end())
6675 return I->second;
6676
6677 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6678 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6679
6680 // Switch to iteratively computing the range for S, if it is part of a deeply
6681 // nested expression.
6683 return getRangeRefIter(S, SignHint);
6684
6685 unsigned BitWidth = getTypeSizeInBits(S->getType());
6686 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6687 using OBO = OverflowingBinaryOperator;
6688
6689 // If the value has known zeros, the maximum value will have those known zeros
6690 // as well.
6691 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6692 APInt Multiple = getNonZeroConstantMultiple(S);
6693 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6694 if (!Remainder.isZero())
6695 ConservativeResult =
6696 ConstantRange(APInt::getMinValue(BitWidth),
6697 APInt::getMaxValue(BitWidth) - Remainder + 1);
6698 }
6699 else {
6700 uint32_t TZ = getMinTrailingZeros(S);
6701 if (TZ != 0) {
6702 ConservativeResult = ConstantRange(
6704 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6705 }
6706 }
6707
6708 switch (S->getSCEVType()) {
6709 case scConstant:
6710 llvm_unreachable("Already handled above.");
6711 case scVScale:
6712 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6713 case scTruncate: {
6714 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6715 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6716 return setRange(
6717 Trunc, SignHint,
6718 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6719 }
6720 case scZeroExtend: {
6721 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6722 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6723 return setRange(
6724 ZExt, SignHint,
6725 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6726 }
6727 case scSignExtend: {
6728 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6729 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6730 return setRange(
6731 SExt, SignHint,
6732 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6733 }
6734 case scPtrToAddr: {
6735 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6736 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6737 return setRange(Cast, SignHint, X);
6738 }
6739 case scAddExpr: {
6740 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6741 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6742 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6743 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6744 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6745 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6746 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6747 ConservativeResult =
6748 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6749 }
6750 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6751 unsigned WrapType = OBO::AnyWrap;
6752 if (Add->hasNoSignedWrap())
6753 WrapType |= OBO::NoSignedWrap;
6754 if (Add->hasNoUnsignedWrap())
6755 WrapType |= OBO::NoUnsignedWrap;
6756 for (const SCEV *Op : drop_begin(Add->operands()))
6757 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6758 RangeType);
6759 return setRange(Add, SignHint,
6760 ConservativeResult.intersectWith(X, RangeType));
6761 }
6762 case scMulExpr: {
6763 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6764 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6765 for (const SCEV *Op : drop_begin(Mul->operands()))
6766 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6767 return setRange(Mul, SignHint,
6768 ConservativeResult.intersectWith(X, RangeType));
6769 }
6770 case scUDivExpr: {
6771 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6772 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6773 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6774 return setRange(UDiv, SignHint,
6775 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6776 }
6777 case scAddRecExpr: {
6778 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6779 // If there's no unsigned wrap, the value will never be less than its
6780 // initial value.
6781 if (AddRec->hasNoUnsignedWrap()) {
6782 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6783 if (!UnsignedMinValue.isZero())
6784 ConservativeResult = ConservativeResult.intersectWith(
6785 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6786 }
6787
6788 // If there's no signed wrap, and all the operands except initial value have
6789 // the same sign or zero, the value won't ever be:
6790 // 1: smaller than initial value if operands are non negative,
6791 // 2: bigger than initial value if operands are non positive.
6792 // For both cases, value can not cross signed min/max boundary.
6793 if (AddRec->hasNoSignedWrap()) {
6794 bool AllNonNeg = true;
6795 bool AllNonPos = true;
6796 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6797 if (!isKnownNonNegative(AddRec->getOperand(i)))
6798 AllNonNeg = false;
6799 if (!isKnownNonPositive(AddRec->getOperand(i)))
6800 AllNonPos = false;
6801 }
6802 if (AllNonNeg)
6803 ConservativeResult = ConservativeResult.intersectWith(
6806 RangeType);
6807 else if (AllNonPos)
6808 ConservativeResult = ConservativeResult.intersectWith(
6810 getSignedRangeMax(AddRec->getStart()) +
6811 1),
6812 RangeType);
6813 }
6814
6815 // TODO: non-affine addrec
6816 if (AddRec->isAffine()) {
6817 const SCEV *MaxBEScev =
6819 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6820 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6821
6822 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6823 // MaxBECount's active bits are all <= AddRec's bit width.
6824 if (MaxBECount.getBitWidth() > BitWidth &&
6825 MaxBECount.getActiveBits() <= BitWidth)
6826 MaxBECount = MaxBECount.trunc(BitWidth);
6827 else if (MaxBECount.getBitWidth() < BitWidth)
6828 MaxBECount = MaxBECount.zext(BitWidth);
6829
6830 if (MaxBECount.getBitWidth() == BitWidth) {
6831 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6832 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6833 ConservativeResult =
6834 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6835 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6836
6837 auto RangeFromFactoring = getRangeViaFactoring(
6838 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6839 ConservativeResult =
6840 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6841 }
6842 }
6843
6844 // Now try symbolic BE count and more powerful methods.
6846 const SCEV *SymbolicMaxBECount =
6848 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6849 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6850 AddRec->hasNoSelfWrap()) {
6851 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6852 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6853 ConservativeResult =
6854 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6855 }
6856 }
6857 }
6858
6859 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6860 }
6861 case scUMaxExpr:
6862 case scSMaxExpr:
6863 case scUMinExpr:
6864 case scSMinExpr:
6865 case scSequentialUMinExpr: {
6867 switch (S->getSCEVType()) {
6868 case scUMaxExpr:
6869 ID = Intrinsic::umax;
6870 break;
6871 case scSMaxExpr:
6872 ID = Intrinsic::smax;
6873 break;
6874 case scUMinExpr:
6876 ID = Intrinsic::umin;
6877 break;
6878 case scSMinExpr:
6879 ID = Intrinsic::smin;
6880 break;
6881 default:
6882 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6883 }
6884
6885 const auto *NAry = cast<SCEVNAryExpr>(S);
6886 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6887 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6888 X = X.intrinsic(
6889 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6890 return setRange(S, SignHint,
6891 ConservativeResult.intersectWith(X, RangeType));
6892 }
6893 case scUnknown: {
6894 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6895 Value *V = U->getValue();
6896
6897 // Check if the IR explicitly contains !range metadata.
6898 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6899 if (MDRange)
6900 ConservativeResult =
6901 ConservativeResult.intersectWith(*MDRange, RangeType);
6902
6903 // Use facts about recurrences in the underlying IR. Note that add
6904 // recurrences are AddRecExprs and thus don't hit this path. This
6905 // primarily handles shift recurrences.
6906 auto CR = getRangeForUnknownRecurrence(U);
6907 ConservativeResult = ConservativeResult.intersectWith(CR);
6908
6909 // See if ValueTracking can give us a useful range.
6910 const DataLayout &DL = getDataLayout();
6911 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6912 if (Known.getBitWidth() != BitWidth)
6913 Known = Known.zextOrTrunc(BitWidth);
6914
6915 // ValueTracking may be able to compute a tighter result for the number of
6916 // sign bits than for the value of those sign bits.
6917 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6918 if (U->getType()->isPointerTy()) {
6919 // NS counts the sign bits of the whole pointer; drop those above the
6920 // index bits.
6921 unsigned PtrIdxDiff =
6922 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6923 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6924 }
6925
6926 if (NS > 1) {
6927 // If we know any of the sign bits, we know all of the sign bits.
6928 if (!Known.Zero.getHiBits(NS).isZero())
6929 Known.Zero.setHighBits(NS);
6930 if (!Known.One.getHiBits(NS).isZero())
6931 Known.One.setHighBits(NS);
6932 }
6933
6934 if (Known.getMinValue() != Known.getMaxValue() + 1)
6935 ConservativeResult = ConservativeResult.intersectWith(
6936 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6937 RangeType);
6938 if (NS > 1)
6939 ConservativeResult = ConservativeResult.intersectWith(
6940 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6941 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6942 RangeType);
6943
6944 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6945 // Strengthen the range if the underlying IR value is a
6946 // global/alloca/heap allocation using the size of the object.
6947 bool CanBeNull;
6948 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6949 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6950 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6951 // The highest address the object can start is DerefBytes bytes before
6952 // the end (unsigned max value). If this value is not a multiple of the
6953 // alignment, the last possible start value is the next lowest multiple
6954 // of the alignment. Note: The computations below cannot overflow,
6955 // because if they would there's no possible start address for the
6956 // object.
6957 APInt MaxVal =
6958 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6959 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6960 uint64_t Rem = MaxVal.urem(Align);
6961 MaxVal -= APInt(BitWidth, Rem);
6962 APInt MinVal = APInt::getZero(BitWidth);
6963 if (llvm::isKnownNonZero(V, DL))
6964 MinVal = Align;
6965 ConservativeResult = ConservativeResult.intersectWith(
6966 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6967 }
6968 }
6969
6970 // A range of Phi is a subset of union of all ranges of its input.
6971 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6972 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6973 // AddRecs; return the range for the corresponding AddRec.
6974 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6975 return getRangeRef(AR, SignHint, Depth + 1);
6976
6977 // Make sure that we do not run over cycled Phis.
6978 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6979 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6980
6981 for (const auto &Op : Phi->operands()) {
6982 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6983 RangeFromOps = RangeFromOps.unionWith(OpRange);
6984 // No point to continue if we already have a full set.
6985 if (RangeFromOps.isFullSet())
6986 break;
6987 }
6988 ConservativeResult =
6989 ConservativeResult.intersectWith(RangeFromOps, RangeType);
6990 }
6991 }
6992
6993 // vscale can't be equal to zero
6994 if (const auto *II = dyn_cast<IntrinsicInst>(V))
6995 if (II->getIntrinsicID() == Intrinsic::vscale) {
6996 ConstantRange Disallowed = APInt::getZero(BitWidth);
6997 ConservativeResult = ConservativeResult.difference(Disallowed);
6998 }
6999
7000 return setRange(U, SignHint, std::move(ConservativeResult));
7001 }
7002 case scCouldNotCompute:
7003 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7004 }
7005
7006 return setRange(S, SignHint, std::move(ConservativeResult));
7007}
7008
7009// Given a StartRange, Step and MaxBECount for an expression compute a range of
7010// values that the expression can take. Initially, the expression has a value
7011// from StartRange and then is changed by Step up to MaxBECount times. Signed
7012// argument defines if we treat Step as signed or unsigned. The second return
7013// value indicates that no wrapping occurred.
7014static std::pair<ConstantRange, bool>
7016 const APInt &MaxBECount, bool Signed) {
7017 unsigned BitWidth = Step.getBitWidth();
7018 assert(BitWidth == StartRange.getBitWidth() &&
7019 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7020 // If either Step or MaxBECount is 0, then the expression won't change, and we
7021 // just need to return the initial range.
7022 if (Step == 0 || MaxBECount == 0)
7023 return {StartRange, true};
7024
7025 // If we don't know anything about the initial value (i.e. StartRange is
7026 // FullRange), then we don't know anything about the final range either.
7027 // Return FullRange.
7028 if (StartRange.isFullSet())
7029 return {ConstantRange::getFull(BitWidth), false};
7030
7031 // If Step is signed and negative, then we use its absolute value, but we also
7032 // note that we're moving in the opposite direction.
7033 bool Descending = Signed && Step.isNegative();
7034
7035 if (Signed)
7036 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7037 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7038 // This equations hold true due to the well-defined wrap-around behavior of
7039 // APInt.
7040 Step = Step.abs();
7041
7042 // Check if Offset is more than full span of BitWidth. If it is, the
7043 // expression is guaranteed to overflow.
7044 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7045 return {ConstantRange::getFull(BitWidth), false};
7046
7047 // Offset is by how much the expression can change. Checks above guarantee no
7048 // overflow here.
7049 APInt Offset = Step * MaxBECount;
7050
7051 // Minimum value of the final range will match the minimal value of StartRange
7052 // if the expression is increasing and will be decreased by Offset otherwise.
7053 // Maximum value of the final range will match the maximal value of StartRange
7054 // if the expression is decreasing and will be increased by Offset otherwise.
7055 APInt StartLower = StartRange.getLower();
7056 APInt StartUpper = StartRange.getUpper() - 1;
7057 bool Overflow;
7058 APInt MovedBoundary;
7059 if (Signed) {
7060 // This does not use sadd_ov, as we want to check overflow for a signed
7061 // start with an unsigned offset.
7062 if (Descending) {
7063 MovedBoundary = StartLower - std::move(Offset);
7064 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7065 } else {
7066 MovedBoundary = StartUpper + std::move(Offset);
7067 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7068 }
7069 } else {
7070 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7071 Overflow |= StartRange.isWrappedSet();
7072 }
7073
7074 // It's possible that the new minimum/maximum value will fall into the initial
7075 // range (due to wrap around). This means that the expression can take any
7076 // value in this bitwidth, and we have to return full range.
7077 if (StartRange.contains(MovedBoundary))
7078 return {ConstantRange::getFull(BitWidth), false};
7079
7080 APInt NewLower =
7081 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7082 APInt NewUpper =
7083 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7084 NewUpper += 1;
7085
7086 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7087 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7088 !Overflow};
7089}
7090
7091std::pair<ConstantRange, SCEVFlags>
7092ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7093 const APInt &MaxBECount) {
7094 assert(getTypeSizeInBits(Start->getType()) ==
7095 getTypeSizeInBits(Step->getType()) &&
7096 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7097 "mismatched bit widths");
7098
7099 // First, consider step signed.
7100 ConstantRange StartSRange = getSignedRange(Start);
7101 ConstantRange StepSRange = getSignedRange(Step);
7102
7103 // If Step can be both positive and negative, we need to find ranges for the
7104 // maximum absolute step values in both directions and union them.
7105 auto [SR, NSW] = getRangeForAffineARHelper(
7106 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7107 // A singleton step has identical signed bounds, so the second computation
7108 // would produce the same range and no-wrap result.
7109 if (!StepSRange.isSingleElement()) {
7110 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
7111 StepSRange.getSignedMax(), StartSRange, MaxBECount, /*Signed=*/true);
7112 SR = SR.unionWith(SRMax);
7113 NSW &= NSWMax;
7114 }
7115
7116 // Next, consider step unsigned.
7117 auto [UR, NUW] = getRangeForAffineARHelper(
7118 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7119 /*Signed=*/false);
7120
7122 if (NUW)
7124 if (NSW)
7126
7127 // Finally, intersect signed and unsigned ranges.
7128 return {SR.intersectWith(UR, ConstantRange::Smallest), Flags};
7129}
7130
7131ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7132 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7133 ScalarEvolution::RangeSignHint SignHint) {
7134 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7135 assert(AddRec->hasNoSelfWrap() &&
7136 "This only works for non-self-wrapping AddRecs!");
7137 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7138 const SCEV *Step = AddRec->getStepRecurrence(*this);
7139 // Only deal with constant step to save compile time.
7140 if (!isa<SCEVConstant>(Step))
7141 return ConstantRange::getFull(BitWidth);
7142 // Let's make sure that we can prove that we do not self-wrap during
7143 // MaxBECount iterations. We need this because MaxBECount is a maximum
7144 // iteration count estimate, and we might infer nw from some exit for which we
7145 // do not know max exit count (or any other side reasoning).
7146 // TODO: Turn into assert at some point.
7147 if (getTypeSizeInBits(MaxBECount->getType()) >
7148 getTypeSizeInBits(AddRec->getType()))
7149 return ConstantRange::getFull(BitWidth);
7150 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7151 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7152 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7153 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7154 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7155 MaxItersWithoutWrap))
7156 return ConstantRange::getFull(BitWidth);
7157
7158 ICmpInst::Predicate LEPred =
7160 ICmpInst::Predicate GEPred =
7162 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7163
7164 // We know that there is no self-wrap. Let's take Start and End values and
7165 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7166 // the iteration. They either lie inside the range [Min(Start, End),
7167 // Max(Start, End)] or outside it:
7168 //
7169 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7170 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7171 //
7172 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7173 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7174 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7175 // Start <= End and step is positive, or Start >= End and step is negative.
7176 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7177 ConstantRange StartRange = getRangeRef(Start, SignHint);
7178 ConstantRange EndRange = getRangeRef(End, SignHint);
7179 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7180 // If they already cover full iteration space, we will know nothing useful
7181 // even if we prove what we want to prove.
7182 if (RangeBetween.isFullSet())
7183 return RangeBetween;
7184 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7185 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7186 : RangeBetween.isWrappedSet();
7187 if (IsWrappedSet)
7188 return ConstantRange::getFull(BitWidth);
7189
7190 if (isKnownPositive(Step) &&
7191 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7192 return RangeBetween;
7193 if (isKnownNegative(Step) &&
7194 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7195 return RangeBetween;
7196 return ConstantRange::getFull(BitWidth);
7197}
7198
7199ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7200 const SCEV *Step,
7201 const APInt &MaxBECount) {
7202 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7203 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7204
7205 unsigned BitWidth = MaxBECount.getBitWidth();
7206 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7207 getTypeSizeInBits(Step->getType()) == BitWidth &&
7208 "mismatched bit widths");
7209
7210 struct SelectPattern {
7211 Value *Condition = nullptr;
7212 APInt TrueValue;
7213 APInt FalseValue;
7214
7215 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7216 const SCEV *S) {
7217 std::optional<unsigned> CastOp;
7218 APInt Offset(BitWidth, 0);
7219
7221 "Should be!");
7222
7223 // Peel off a constant offset. In the future we could consider being
7224 // smarter here and handle {Start+Step,+,Step} too.
7225 const APInt *Off;
7226 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7227 Offset = *Off;
7228
7229 // Peel off a cast operation
7230 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7231 CastOp = SCast->getSCEVType();
7232 S = SCast->getOperand();
7233 }
7234
7235 using namespace llvm::PatternMatch;
7236
7237 auto *SU = dyn_cast<SCEVUnknown>(S);
7238 const APInt *TrueVal, *FalseVal;
7239 if (!SU ||
7240 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7241 m_APInt(FalseVal)))) {
7242 Condition = nullptr;
7243 return;
7244 }
7245
7246 TrueValue = *TrueVal;
7247 FalseValue = *FalseVal;
7248
7249 // Re-apply the cast we peeled off earlier
7250 if (CastOp)
7251 switch (*CastOp) {
7252 default:
7253 llvm_unreachable("Unknown SCEV cast type!");
7254
7255 case scTruncate:
7256 TrueValue = TrueValue.trunc(BitWidth);
7257 FalseValue = FalseValue.trunc(BitWidth);
7258 break;
7259 case scZeroExtend:
7260 TrueValue = TrueValue.zext(BitWidth);
7261 FalseValue = FalseValue.zext(BitWidth);
7262 break;
7263 case scSignExtend:
7264 TrueValue = TrueValue.sext(BitWidth);
7265 FalseValue = FalseValue.sext(BitWidth);
7266 break;
7267 }
7268
7269 // Re-apply the constant offset we peeled off earlier
7270 TrueValue += Offset;
7271 FalseValue += Offset;
7272 }
7273
7274 bool isRecognized() { return Condition != nullptr; }
7275 };
7276
7277 SelectPattern StartPattern(*this, BitWidth, Start);
7278 if (!StartPattern.isRecognized())
7279 return ConstantRange::getFull(BitWidth);
7280
7281 SelectPattern StepPattern(*this, BitWidth, Step);
7282 if (!StepPattern.isRecognized())
7283 return ConstantRange::getFull(BitWidth);
7284
7285 if (StartPattern.Condition != StepPattern.Condition) {
7286 // We don't handle this case today; but we could, by considering four
7287 // possibilities below instead of two. I'm not sure if there are cases where
7288 // that will help over what getRange already does, though.
7289 return ConstantRange::getFull(BitWidth);
7290 }
7291
7292 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7293 // construct arbitrary general SCEV expressions here. This function is called
7294 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7295 // say) can end up caching a suboptimal value.
7296
7297 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7298 // C2352 and C2512 (otherwise it isn't needed).
7299
7300 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7301 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7302 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7303 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7304
7305 ConstantRange TrueRange =
7306 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7307 ConstantRange FalseRange =
7308 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7309
7310 return TrueRange.unionWith(FalseRange);
7311}
7312
7313SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7314 if (isa<ConstantExpr>(V))
7315 return SCEV::FlagNone;
7316 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7317
7318 // Return early if there are no flags to propagate to the SCEV.
7320 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7321 PDI && PDI->isDisjoint()) {
7323 } else {
7324 if (BinOp->hasNoUnsignedWrap())
7326 if (BinOp->hasNoSignedWrap())
7328 }
7329 if (Flags == SCEV::FlagNone)
7330 return SCEV::FlagNone;
7331
7332 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7333}
7334
7335const Instruction *
7336ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7337 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7338 return &*AddRec->getLoop()->getHeader()->begin();
7339 if (auto *U = dyn_cast<SCEVUnknown>(S))
7340 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7341 return I;
7342 return nullptr;
7343}
7344
7345const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7346 bool &Precise) {
7347 Precise = true;
7348 // Do a bounded search of the def relation of the requested SCEVs.
7349 SmallPtrSet<const SCEV *, 16> Visited;
7350 SmallVector<SCEVUse> Worklist;
7351 auto pushOp = [&](const SCEV *S) {
7352 if (!Visited.insert(S).second)
7353 return;
7354 // Threshold of 30 here is arbitrary.
7355 if (Visited.size() > 30) {
7356 Precise = false;
7357 return;
7358 }
7359 Worklist.push_back(S);
7360 };
7361
7362 for (SCEVUse S : Ops)
7363 pushOp(S);
7364
7365 const Instruction *Bound = nullptr;
7366 while (!Worklist.empty()) {
7367 SCEVUse S = Worklist.pop_back_val();
7368 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7369 if (!Bound || DT.dominates(Bound, DefI))
7370 Bound = DefI;
7371 } else {
7372 for (SCEVUse Op : S->operands())
7373 pushOp(Op);
7374 }
7375 }
7376 return Bound ? Bound : &*F.getEntryBlock().begin();
7377}
7378
7379const Instruction *
7380ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7381 bool Discard;
7382 return getDefiningScopeBound(Ops, Discard);
7383}
7384
7385bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7386 const Instruction *B) {
7387 if (A->getParent() == B->getParent() &&
7389 B->getIterator()))
7390 return true;
7391
7392 auto *BLoop = LI.getLoopFor(B->getParent());
7393 if (BLoop && BLoop->getHeader() == B->getParent() &&
7394 BLoop->getLoopPreheader() == A->getParent() &&
7396 A->getParent()->end()) &&
7397 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7398 B->getIterator()))
7399 return true;
7400 return false;
7401}
7402
7404 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7405 visitAll(Op, PC);
7406 return PC.MaybePoison.empty();
7407}
7408
7409bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7410 return !SCEVExprContains(Op, [this](const SCEV *S) {
7411 const SCEV *Op1;
7412 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7413 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7414 // is a non-zero constant, we have to assume the UDiv may be UB.
7415 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7416 });
7417}
7418
7419bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7420 // Only proceed if we can prove that I does not yield poison.
7422 return false;
7423
7424 // At this point we know that if I is executed, then it does not wrap
7425 // according to at least one of NSW or NUW. If I is not executed, then we do
7426 // not know if the calculation that I represents would wrap. Multiple
7427 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7428 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7429 // derived from other instructions that map to the same SCEV. We cannot make
7430 // that guarantee for cases where I is not executed. So we need to find a
7431 // upper bound on the defining scope for the SCEV, and prove that I is
7432 // executed every time we enter that scope. When the bounding scope is a
7433 // loop (the common case), this is equivalent to proving I executes on every
7434 // iteration of that loop.
7435 SmallVector<SCEVUse> SCEVOps;
7436 for (const Use &Op : I->operands()) {
7437 // I could be an extractvalue from a call to an overflow intrinsic.
7438 // TODO: We can do better here in some cases.
7439 if (isSCEVable(Op->getType()))
7440 SCEVOps.push_back(getSCEV(Op));
7441 }
7442 auto *DefI = getDefiningScopeBound(SCEVOps);
7443 return isGuaranteedToTransferExecutionTo(DefI, I);
7444}
7445
7446bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7447 // If we know that \c I can never be poison period, then that's enough.
7448 if (isSCEVExprNeverPoison(I))
7449 return true;
7450
7451 // If the loop only has one exit, then we know that, if the loop is entered,
7452 // any instruction dominating that exit will be executed. If any such
7453 // instruction would result in UB, the addrec cannot be poison.
7454 //
7455 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7456 // also handles uses outside the loop header (they just need to dominate the
7457 // single exit).
7458
7459 auto *ExitingBB = L->getExitingBlock();
7460 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7461 return false;
7462
7463 SmallPtrSet<const Value *, 16> KnownPoison;
7465
7466 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7467 // things that are known to be poison under that assumption go on the
7468 // Worklist.
7469 KnownPoison.insert(I);
7470 Worklist.push_back(I);
7471
7472 while (!Worklist.empty()) {
7473 const Instruction *Poison = Worklist.pop_back_val();
7474
7475 for (const Use &U : Poison->uses()) {
7476 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7477 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7478 DT.dominates(PoisonUser->getParent(), ExitingBB))
7479 return true;
7480
7481 if (propagatesPoison(U) && L->contains(PoisonUser))
7482 if (KnownPoison.insert(PoisonUser).second)
7483 Worklist.push_back(PoisonUser);
7484 }
7485 }
7486
7487 return false;
7488}
7489
7490ScalarEvolution::LoopProperties
7491ScalarEvolution::getLoopProperties(const Loop *L) {
7492 using LoopProperties = ScalarEvolution::LoopProperties;
7493
7494 auto Itr = LoopPropertiesCache.find(L);
7495 if (Itr == LoopPropertiesCache.end()) {
7496 auto HasSideEffects = [](Instruction *I) {
7497 if (auto *SI = dyn_cast<StoreInst>(I))
7498 return !SI->isSimple();
7499
7500 if (I->mayThrow())
7501 return true;
7502
7503 // Non-volatile memset / memcpy do not count as side-effect for forward
7504 // progress.
7505 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7506 return false;
7507
7508 // Droppable intrinsics only model a memory write; they are not progress.
7509 if (I->isDroppable())
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 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7868 if (Flags != SCEV::FlagNone) {
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 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7906 if (Flags != SCEV::FlagNone) {
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 const SCEV *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::FlagNone;
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 // An exit with an uncomputable exit count makes the result 1.
8415 if (ExitingBlocks.empty() ||
8416 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8417 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8418 }))
8419 return 1;
8420
8421 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8422 unsigned Res = 0;
8423 for (BasicBlock *ExitingBB : ExitingBlocks)
8424 Res = std::gcd(
8425 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8426 return Res;
8427}
8428
8429unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8430 LoopGuards &Guards) {
8431 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8432
8433 // Get the trip count
8434 const SCEV *TCExpr =
8435 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8436
8437 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8438 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8439 // the greatest power of 2 divisor less than 2^32.
8440 return Multiple.getActiveBits() > 32
8441 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8442 : (unsigned)Multiple.getZExtValue();
8443}
8444
8446 const SCEV *ExitCount) {
8447 if (isa<SCEVCouldNotCompute>(ExitCount))
8448 return 1;
8449
8450 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8451 return getSmallConstantTripMultiple(ExitCount, Guards);
8452}
8453
8454/// Returns the largest constant divisor of the trip count of this loop as a
8455/// normal unsigned value, if possible. This means that the actual trip count is
8456/// always a multiple of the returned value (don't forget the trip count could
8457/// very well be zero as well!).
8458///
8459/// Returns 1 if the trip count is unknown or not guaranteed to be the
8460/// multiple of a constant (which is also the case if the trip count is simply
8461/// constant, use getSmallConstantTripCount for that case), Will also return 1
8462/// if the trip count is very large (>= 2^32).
8463///
8464/// As explained in the comments for getSmallConstantTripCount, this assumes
8465/// that control exits the loop via ExitingBlock.
8466unsigned
8468 const BasicBlock *ExitingBlock) {
8469 assert(ExitingBlock && "Must pass a non-null exiting block!");
8470 assert(L->isLoopExiting(ExitingBlock) &&
8471 "Exiting block must actually branch out of the loop!");
8472 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8473 return getSmallConstantTripMultiple(L, ExitCount);
8474}
8475
8477 const BasicBlock *ExitingBlock,
8478 ExitCountKind Kind) {
8479 switch (Kind) {
8480 case Exact:
8481 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8482 case SymbolicMaximum:
8483 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8484 case ConstantMaximum:
8485 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8486 };
8487 llvm_unreachable("Invalid ExitCountKind!");
8488}
8489
8491 const Loop *L, const BasicBlock *ExitingBlock,
8493 switch (Kind) {
8494 case Exact:
8495 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8496 Predicates);
8497 case SymbolicMaximum:
8498 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8499 Predicates);
8500 case ConstantMaximum:
8501 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8502 Predicates);
8503 };
8504 llvm_unreachable("Invalid ExitCountKind!");
8505}
8506
8509 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8510}
8511
8513 ExitCountKind Kind) {
8514 switch (Kind) {
8515 case Exact:
8516 return getBackedgeTakenInfo(L).getExact(L, this);
8517 case ConstantMaximum:
8518 return getBackedgeTakenInfo(L).getConstantMax(this);
8519 case SymbolicMaximum:
8520 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8521 };
8522 llvm_unreachable("Invalid ExitCountKind!");
8523}
8524
8527 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8528}
8529
8532 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8533}
8534
8536 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8537}
8538
8539/// Push PHI nodes in the header of the given loop onto the given Worklist.
8540static void PushLoopPHIs(const Loop *L,
8543 BasicBlock *Header = L->getHeader();
8544
8545 // Push all Loop-header PHIs onto the Worklist stack.
8546 for (PHINode &PN : Header->phis())
8547 if (Visited.insert(&PN).second)
8548 Worklist.push_back(&PN);
8549}
8550
8551ScalarEvolution::BackedgeTakenInfo &
8552ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8553 auto &BTI = getBackedgeTakenInfo(L);
8554 if (BTI.hasFullInfo())
8555 return BTI;
8556
8557 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8558
8559 if (!Pair.second)
8560 return Pair.first->second;
8561
8562 BackedgeTakenInfo Result =
8563 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8564
8565 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8566}
8567
8568ScalarEvolution::BackedgeTakenInfo &
8569ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8570 // Initially insert an invalid entry for this loop. If the insertion
8571 // succeeds, proceed to actually compute a backedge-taken count and
8572 // update the value. The temporary CouldNotCompute value tells SCEV
8573 // code elsewhere that it shouldn't attempt to request a new
8574 // backedge-taken count, which could result in infinite recursion.
8575 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8576 BackedgeTakenCounts.try_emplace(L);
8577 if (!Pair.second)
8578 return Pair.first->second;
8579
8580 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8581 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8582 // must be cleared in this scope.
8583 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8584
8585 // Now that we know more about the trip count for this loop, forget any
8586 // existing SCEV values for PHI nodes in this loop since they are only
8587 // conservative estimates made without the benefit of trip count
8588 // information. This invalidation is not necessary for correctness, and is
8589 // only done to produce more precise results.
8590 if (Result.hasAnyInfo()) {
8591 // Invalidate any expression using an addrec in this loop.
8592 SmallVector<SCEVUse, 8> ToForget;
8593 auto LoopUsersIt = LoopUsers.find(L);
8594 if (LoopUsersIt != LoopUsers.end())
8595 append_range(ToForget, LoopUsersIt->second);
8596 forgetMemoizedResults(ToForget);
8597
8598 // Invalidate constant-evolved loop header phis.
8599 for (PHINode &PN : L->getHeader()->phis())
8600 ConstantEvolutionLoopExitValue.erase(&PN);
8601 }
8602
8603 // Re-lookup the insert position, since the call to
8604 // computeBackedgeTakenCount above could result in a
8605 // recusive call to getBackedgeTakenInfo (on a different
8606 // loop), which would invalidate the iterator computed
8607 // earlier.
8608 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8609}
8610
8612 // This method is intended to forget all info about loops. It should
8613 // invalidate caches as if the following happened:
8614 // - The trip counts of all loops have changed arbitrarily
8615 // - Every llvm::Value has been updated in place to produce a different
8616 // result.
8617 BackedgeTakenCounts.clear();
8618 PredicatedBackedgeTakenCounts.clear();
8619 BECountUsers.clear();
8620 LoopPropertiesCache.clear();
8621 ConstantEvolutionLoopExitValue.clear();
8622 ValueExprMap.clear();
8623 ValuesAtScopes.clear();
8624 ValuesAtScopesUsers.clear();
8625 LoopDispositions.clear();
8626 BlockDispositions.clear();
8627 UnsignedRanges.clear();
8628 SignedRanges.clear();
8629 ExprValueMap.clear();
8630 HasRecMap.clear();
8631 ConstantMultipleCache.clear();
8632 PredicatedSCEVRewrites.clear();
8633 FoldCache.clear();
8634 FoldCacheUser.clear();
8635}
8636void ScalarEvolution::visitAndClearUsers(
8639 SmallVectorImpl<SCEVUse> &ToForget) {
8640 // Nothing can be invalidated if no value has a SCEV yet.
8641 if (ValueExprMap.empty()) {
8642 Worklist.clear();
8643 return;
8644 }
8645 while (!Worklist.empty()) {
8646 Instruction *I = Worklist.pop_back_val();
8647 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8648 continue;
8649
8651 ValueExprMap.find_as(static_cast<Value *>(I));
8652 if (It != ValueExprMap.end()) {
8653 ToForget.push_back(It->second);
8654 eraseValueFromMap(It->first);
8655 if (PHINode *PN = dyn_cast<PHINode>(I))
8656 ConstantEvolutionLoopExitValue.erase(PN);
8657 }
8658
8659 PushDefUseChildren(I, Worklist, Visited);
8660 }
8661}
8662
8664 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8667 SmallVector<SCEVUse, 16> ToForget;
8668
8669 // Iterate over all the loops and sub-loops to drop SCEV information.
8670 while (!LoopWorklist.empty()) {
8671 auto *CurrL = LoopWorklist.pop_back_val();
8672
8673 // Drop any stored trip count value.
8674 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8675 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8676
8677 // Drop information about predicated SCEV rewrites for this loop.
8678 PredicatedSCEVRewrites.remove_if(
8679 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8680
8681 auto LoopUsersItr = LoopUsers.find(CurrL);
8682 if (LoopUsersItr != LoopUsers.end())
8683 llvm::append_range(ToForget, LoopUsersItr->second);
8684
8685 // Drop information about expressions based on loop-header PHIs.
8686 PushLoopPHIs(CurrL, Worklist, Visited);
8687 visitAndClearUsers(Worklist, Visited, ToForget);
8688
8689 LoopPropertiesCache.erase(CurrL);
8690 // Forget all contained loops too, to avoid dangling entries in the
8691 // ValuesAtScopes map.
8692 LoopWorklist.append(CurrL->begin(), CurrL->end());
8693 }
8694 forgetMemoizedResults(ToForget);
8695}
8696
8698 forgetLoop(L->getOutermostLoop());
8699}
8700
8703 if (!I) return;
8704
8705 // Drop information about expressions based on loop-header PHIs.
8708 SmallVector<SCEVUse, 8> ToForget;
8709 Worklist.push_back(I);
8710 Visited.insert(I);
8711 visitAndClearUsers(Worklist, Visited, ToForget);
8712
8713 forgetMemoizedResults(ToForget);
8714}
8715
8719 SmallVector<SCEVUse, 8> ToForget;
8720 for (Value *V : Values)
8721 if (auto *I = dyn_cast<Instruction>(V))
8722 if (Visited.insert(I).second)
8723 Worklist.push_back(I);
8724 visitAndClearUsers(Worklist, Visited, ToForget);
8725
8726 forgetMemoizedResults(ToForget);
8727}
8728
8730 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8731 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8732 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8733 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8734 auto InvalidateValue = [&](Value *Val) {
8735 if (!isSCEVable(Val->getType()))
8736 return;
8737 if (const SCEV *S = getExistingSCEV(Val)) {
8738 struct InvalidationRootCollector {
8739 Loop *L;
8741
8742 InvalidationRootCollector(Loop *L) : L(L) {}
8743
8744 bool follow(const SCEV *S) {
8745 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8746 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8747 if (L->contains(I))
8748 Roots.push_back(S);
8749 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8750 if (L->contains(AddRec->getLoop()))
8751 Roots.push_back(S);
8752 }
8753 return true;
8754 }
8755 bool isDone() const { return false; }
8756 };
8757
8758 InvalidationRootCollector C(L);
8759 visitAll(S, C);
8760 forgetMemoizedResults(C.Roots);
8761 }
8762 };
8763
8764 InvalidateValue(V);
8765
8766 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8767 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8768 // expressions referencing loop-internal values.
8769 if (!isSCEVable(V->getType()) &&
8770 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8771 for (User *U : V->users())
8772 InvalidateValue(U);
8773 // Also perform the normal invalidation.
8774 forgetValue(V);
8775}
8776
8777void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8778
8780 // Unless a specific value is passed to invalidation, completely clear both
8781 // caches.
8782 if (!V) {
8783 BlockDispositions.clear();
8784 LoopDispositions.clear();
8785 return;
8786 }
8787
8788 if (!isSCEVable(V->getType()))
8789 return;
8790
8791 const SCEV *S = getExistingSCEV(V);
8792 if (!S)
8793 return;
8794
8795 // Invalidate the block and loop dispositions cached for S. Dispositions of
8796 // S's users may change if S's disposition changes (i.e. a user may change to
8797 // loop-invariant, if S changes to loop invariant), so also invalidate
8798 // dispositions of S's users recursively.
8799 SmallVector<SCEVUse, 8> Worklist = {S};
8801 while (!Worklist.empty()) {
8802 const SCEV *Curr = Worklist.pop_back_val();
8803 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8804 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8805 if (!LoopDispoRemoved && !BlockDispoRemoved)
8806 continue;
8807 auto Users = SCEVUsers.find(Curr);
8808 if (Users != SCEVUsers.end())
8809 for (const auto *User : Users->second)
8810 if (Seen.insert(User).second)
8811 Worklist.push_back(User);
8812 }
8813}
8814
8815/// Get the exact loop backedge taken count considering all loop exits. A
8816/// computable result can only be returned for loops with all exiting blocks
8817/// dominating the latch. howFarToZero assumes that the limit of each loop test
8818/// is never skipped. This is a valid assumption as long as the loop exits via
8819/// that test. For precise results, it is the caller's responsibility to specify
8820/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8821const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8822 const Loop *L, ScalarEvolution *SE,
8824 // If any exits were not computable, the loop is not computable.
8825 if (!isComplete() || ExitNotTaken.empty())
8826 return SE->getCouldNotCompute();
8827
8828 const BasicBlock *Latch = L->getLoopLatch();
8829 // All exiting blocks we have collected must dominate the only backedge.
8830 if (!Latch)
8831 return SE->getCouldNotCompute();
8832
8833 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8834 // count is simply a minimum out of all these calculated exit counts.
8836 for (const auto &ENT : ExitNotTaken) {
8837 const SCEV *BECount = ENT.ExactNotTaken;
8838 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8839 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8840 "We should only have known counts for exiting blocks that dominate "
8841 "latch!");
8842
8843 Ops.push_back(BECount);
8844
8845 if (Preds)
8846 append_range(*Preds, ENT.Predicates);
8847
8848 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8849 "Predicate should be always true!");
8850 }
8851
8852 // If an earlier exit exits on the first iteration (exit count zero), then
8853 // a later poison exit count should not propagate into the result. This are
8854 // exactly the semantics provided by umin_seq.
8855 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8856}
8857
8858const ScalarEvolution::ExitNotTakenInfo *
8859ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8860 const BasicBlock *ExitingBlock,
8861 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8862 for (const auto &ENT : ExitNotTaken)
8863 if (ENT.ExitingBlock == ExitingBlock) {
8864 if (ENT.hasAlwaysTruePredicate())
8865 return &ENT;
8866 else if (Predicates) {
8867 append_range(*Predicates, ENT.Predicates);
8868 return &ENT;
8869 }
8870 }
8871
8872 return nullptr;
8873}
8874
8875/// getConstantMax - Get the constant max backedge taken count for the loop.
8876const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8877 ScalarEvolution *SE,
8878 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8879 if (!getConstantMax())
8880 return SE->getCouldNotCompute();
8881
8882 for (const auto &ENT : ExitNotTaken)
8883 if (!ENT.hasAlwaysTruePredicate()) {
8884 if (!Predicates)
8885 return SE->getCouldNotCompute();
8886 append_range(*Predicates, ENT.Predicates);
8887 }
8888
8889 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8890 isa<SCEVConstant>(getConstantMax())) &&
8891 "No point in having a non-constant max backedge taken count!");
8892 return getConstantMax();
8893}
8894
8895const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8896 const Loop *L, ScalarEvolution *SE,
8897 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8898 if (!SymbolicMax) {
8899 // Form an expression for the maximum exit count possible for this loop. We
8900 // merge the max and exact information to approximate a version of
8901 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8902 // constants.
8903 SmallVector<SCEVUse, 4> ExitCounts;
8904
8905 for (const auto &ENT : ExitNotTaken) {
8906 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8907 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8908 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8909 "We should only have known counts for exiting blocks that "
8910 "dominate latch!");
8911 ExitCounts.push_back(ExitCount);
8912 if (Predicates)
8913 append_range(*Predicates, ENT.Predicates);
8914
8915 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8916 "Predicate should be always true!");
8917 }
8918 }
8919 if (ExitCounts.empty())
8920 SymbolicMax = SE->getCouldNotCompute();
8921 else
8922 SymbolicMax =
8923 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8924 }
8925 return SymbolicMax;
8926}
8927
8928bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8929 ScalarEvolution *SE) const {
8930 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8931 return !ENT.hasAlwaysTruePredicate();
8932 };
8933 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8934}
8935
8938
8940 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8941 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8945 // If we prove the max count is zero, so is the symbolic bound. This happens
8946 // in practice due to differences in a) how context sensitive we've chosen
8947 // to be and b) how we reason about bounds implied by UB.
8948 if (ConstantMaxNotTaken->isZero()) {
8949 this->ExactNotTaken = E = ConstantMaxNotTaken;
8950 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8951 }
8952
8955 "Exact is not allowed to be less precise than Constant Max");
8958 "Exact is not allowed to be less precise than Symbolic Max");
8961 "Symbolic Max is not allowed to be less precise than Constant Max");
8964 "No point in having a non-constant max backedge taken count!");
8966 for (const auto PredList : PredLists)
8967 for (const auto *P : PredList) {
8968 if (SeenPreds.contains(P))
8969 continue;
8970 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8971 SeenPreds.insert(P);
8972 Predicates.push_back(P);
8973 }
8974 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8975 "Backedge count should be int");
8977 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8978 "Max backedge count should be int");
8979}
8980
8988
8989/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8990/// computable exit into a persistent ExitNotTakenInfo array.
8991ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
8993 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
8994 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
8995 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
8996
8997 ExitNotTaken.reserve(ExitCounts.size());
8998 std::transform(ExitCounts.begin(), ExitCounts.end(),
8999 std::back_inserter(ExitNotTaken),
9000 [&](const EdgeExitInfo &EEI) {
9001 BasicBlock *ExitBB = EEI.first;
9002 const ExitLimit &EL = EEI.second;
9003 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9004 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9005 EL.Predicates);
9006 });
9007 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9008 isa<SCEVConstant>(ConstantMax)) &&
9009 "No point in having a non-constant max backedge taken count!");
9010}
9011
9012/// Compute the number of times the backedge of the specified loop will execute.
9013ScalarEvolution::BackedgeTakenInfo
9014ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9015 bool AllowPredicates) {
9016 SmallVector<BasicBlock *, 8> ExitingBlocks;
9017 L->getExitingBlocks(ExitingBlocks);
9018
9019 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9020
9022 bool CouldComputeBECount = true;
9023 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9024 const SCEV *MustExitMaxBECount = nullptr;
9025 const SCEV *MayExitMaxBECount = nullptr;
9026 bool MustExitMaxOrZero = false;
9027 bool IsOnlyExit = ExitingBlocks.size() == 1;
9028
9029 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9030 // and compute maxBECount.
9031 // Do a union of all the predicates here.
9032 for (BasicBlock *ExitBB : ExitingBlocks) {
9033 // We canonicalize untaken exits to br (constant), ignore them so that
9034 // proving an exit untaken doesn't negatively impact our ability to reason
9035 // about the loop as whole.
9036 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9037 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9038 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9039 if (ExitIfTrue == CI->isZero())
9040 continue;
9041 }
9042
9043 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9044
9045 assert((AllowPredicates || EL.Predicates.empty()) &&
9046 "Predicated exit limit when predicates are not allowed!");
9047
9048 // 1. For each exit that can be computed, add an entry to ExitCounts.
9049 // CouldComputeBECount is true only if all exits can be computed.
9050 if (EL.ExactNotTaken != getCouldNotCompute())
9051 ++NumExitCountsComputed;
9052 else
9053 // We couldn't compute an exact value for this exit, so
9054 // we won't be able to compute an exact value for the loop.
9055 CouldComputeBECount = false;
9056 // Remember exit count if either exact or symbolic is known. Because
9057 // Exact always implies symbolic, only check symbolic.
9058 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9059 ExitCounts.emplace_back(ExitBB, EL);
9060 else {
9061 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9062 "Exact is known but symbolic isn't?");
9063 ++NumExitCountsNotComputed;
9064 }
9065
9066 // 2. Derive the loop's MaxBECount from each exit's max number of
9067 // non-exiting iterations. Partition the loop exits into two kinds:
9068 // LoopMustExits and LoopMayExits.
9069 //
9070 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9071 // is a LoopMayExit. If any computable LoopMustExit is found, then
9072 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9073 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9074 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9075 // any
9076 // computable EL.ConstantMaxNotTaken.
9077 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9078 DT.dominates(ExitBB, Latch)) {
9079 if (!MustExitMaxBECount) {
9080 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9081 MustExitMaxOrZero = EL.MaxOrZero;
9082 } else {
9083 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9084 EL.ConstantMaxNotTaken);
9085 }
9086 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9087 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9088 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9089 else {
9090 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9091 EL.ConstantMaxNotTaken);
9092 }
9093 }
9094 }
9095 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9096 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9097 // The loop backedge will be taken the maximum or zero times if there's
9098 // a single exit that must be taken the maximum or zero times.
9099 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9100
9101 // Remember which SCEVs are used in exit limits for invalidation purposes.
9102 // We only care about non-constant SCEVs here, so we can ignore
9103 // EL.ConstantMaxNotTaken
9104 // and MaxBECount, which must be SCEVConstant.
9105 for (const auto &Pair : ExitCounts) {
9106 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9107 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9108 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9109 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9110 {L, AllowPredicates});
9111 }
9112 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9113 MaxBECount, MaxOrZero);
9114}
9115
9116ScalarEvolution::ExitLimit
9117ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9118 bool IsOnlyExit, bool AllowPredicates) {
9119 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9120 // If our exiting block does not dominate the latch, then its connection with
9121 // loop's exit limit may be far from trivial.
9122 const BasicBlock *Latch = L->getLoopLatch();
9123 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9124 return getCouldNotCompute();
9125
9126 Instruction *Term = ExitingBlock->getTerminator();
9127 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9128 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9129 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9130 "It should have one successor in loop and one exit block!");
9131 // Proceed to the next level to examine the exit condition expression.
9132 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9133 /*ControlsOnlyExit=*/IsOnlyExit,
9134 AllowPredicates);
9135 }
9136
9137 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9138 // For switch, make sure that there is a single exit from the loop.
9139 BasicBlock *Exit = nullptr;
9140 for (auto *SBB : successors(ExitingBlock))
9141 if (!L->contains(SBB)) {
9142 if (Exit) // Multiple exit successors.
9143 return getCouldNotCompute();
9144 Exit = SBB;
9145 }
9146 assert(Exit && "Exiting block must have at least one exit");
9147 return computeExitLimitFromSingleExitSwitch(
9148 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9149 }
9150
9151 return getCouldNotCompute();
9152}
9153
9155 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9156 bool AllowPredicates) {
9157 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9158 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9159 ControlsOnlyExit, AllowPredicates);
9160}
9161
9162std::optional<ScalarEvolution::ExitLimit>
9163ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9164 bool ExitIfTrue, bool ControlsOnlyExit,
9165 bool AllowPredicates) {
9166 (void)this->L;
9167 (void)this->ExitIfTrue;
9168 (void)this->AllowPredicates;
9169
9170 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9171 this->AllowPredicates == AllowPredicates &&
9172 "Variance in assumed invariant key components!");
9173 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9174 if (Itr == TripCountMap.end())
9175 return std::nullopt;
9176 return Itr->second;
9177}
9178
9179void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9180 bool ExitIfTrue,
9181 bool ControlsOnlyExit,
9182 bool AllowPredicates,
9183 const ExitLimit &EL) {
9184 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9185 this->AllowPredicates == AllowPredicates &&
9186 "Variance in assumed invariant key components!");
9187
9188 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9189 assert(InsertResult.second && "Expected successful insertion!");
9190 (void)InsertResult;
9191 (void)ExitIfTrue;
9192}
9193
9194ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9195 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9196 bool ControlsOnlyExit, bool AllowPredicates) {
9197
9198 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9199 AllowPredicates))
9200 return *MaybeEL;
9201
9202 ExitLimit EL = computeExitLimitFromCondImpl(
9203 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9204 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9205 return EL;
9206}
9207
9208ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9209 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9210 bool ControlsOnlyExit, bool AllowPredicates) {
9211 // Handle BinOp conditions (And, Or).
9212 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9213 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9214 return *LimitFromBinOp;
9215
9216 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9217 // Proceed to the next level to examine the icmp.
9218 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9219 ExitLimit EL =
9220 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9221 if (EL.hasFullInfo() || !AllowPredicates)
9222 return EL;
9223
9224 // Try again, but use SCEV predicates this time.
9225 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9226 ControlsOnlyExit,
9227 /*AllowPredicates=*/true);
9228 }
9229
9230 // Check for a constant condition. These are normally stripped out by
9231 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9232 // preserve the CFG and is temporarily leaving constant conditions
9233 // in place.
9234 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9235 if (ExitIfTrue == !CI->getZExtValue())
9236 // The backedge is always taken.
9237 return getCouldNotCompute();
9238 // The backedge is never taken.
9239 return getZero(CI->getType());
9240 }
9241
9242 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9243 // with a constant step, we can form an equivalent icmp predicate and figure
9244 // out how many iterations will be taken before we exit.
9245 const WithOverflowInst *WO;
9246 const APInt *C;
9247 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9248 match(WO->getRHS(), m_APInt(C))) {
9249 ConstantRange NWR =
9251 WO->getNoWrapKind());
9252 CmpInst::Predicate Pred;
9253 APInt NewRHSC, Offset;
9254 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9255 if (!ExitIfTrue)
9256 Pred = ICmpInst::getInversePredicate(Pred);
9257 auto *LHS = getSCEV(WO->getLHS());
9258 if (Offset != 0)
9260 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9261 ControlsOnlyExit, AllowPredicates);
9262 if (EL.hasAnyInfo())
9263 return EL;
9264 }
9265
9266 // If it's not an integer or pointer comparison then compute it the hard way.
9267 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9268}
9269
9270std::optional<ScalarEvolution::ExitLimit>
9271ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9272 const Loop *L,
9273 Value *ExitCond,
9274 bool ExitIfTrue,
9275 bool AllowPredicates) {
9276 // Check if the controlling expression for this loop is an And or Or.
9277 Value *Op0, *Op1;
9278 bool IsAnd;
9279 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9280 IsAnd = true;
9281 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9282 IsAnd = false;
9283 else
9284 return std::nullopt;
9285
9286 // A sub-condition of a non-trivial binop never solely controls the exit,
9287 // whether we exit always depends on both conditions.
9288 ExitLimit EL0 = computeExitLimitFromCondCached(
9289 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9290 ExitLimit EL1 = computeExitLimitFromCondCached(
9291 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9292
9293 // EitherMayExit is true in these two cases:
9294 // br (and Op0 Op1), loop, exit
9295 // br (or Op0 Op1), exit, loop
9296 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9297
9298 const SCEV *BECount = getCouldNotCompute();
9299 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9300 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9301 if (EitherMayExit) {
9302 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9303 // Both conditions must be same for the loop to continue executing.
9304 // Choose the less conservative count.
9305 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9306 EL1.ExactNotTaken != getCouldNotCompute()) {
9307 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9308 UseSequentialUMin);
9309 }
9310 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9311 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9312 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9313 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9314 else
9315 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9316 EL1.ConstantMaxNotTaken);
9317 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9318 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9319 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9320 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9321 else
9322 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9323 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9324 } else {
9325 // Both conditions must be same at the same time for the loop to exit.
9326 // For now, be conservative.
9327 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9328 BECount = EL0.ExactNotTaken;
9329 }
9330
9331 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9332 // to be more aggressive when computing BECount than when computing
9333 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9334 // and
9335 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9336 // EL1.ConstantMaxNotTaken to not.
9337 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9338 !isa<SCEVCouldNotCompute>(BECount))
9339 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9340 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9341 SymbolicMaxBECount =
9342 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9343 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9344 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9345}
9346
9347ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9348 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9349 bool AllowPredicates) {
9350 // If the condition was exit on true, convert the condition to exit on false
9351 CmpPredicate Pred;
9352 if (!ExitIfTrue)
9353 Pred = ExitCond->getCmpPredicate();
9354 else
9355 Pred = ExitCond->getInverseCmpPredicate();
9356 const ICmpInst::Predicate OriginalPred = Pred;
9357
9358 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9359 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9360
9361 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9362 AllowPredicates);
9363 if (EL.hasAnyInfo())
9364 return EL;
9365
9366 auto *ExhaustiveCount =
9367 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9368
9369 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9370 return ExhaustiveCount;
9371
9372 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9373 ExitCond->getOperand(1), L, OriginalPred);
9374}
9375ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9376 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9377 bool ControlsOnlyExit, bool AllowPredicates) {
9378
9379 // Try to evaluate any dependencies out of the loop.
9380 LHS = getSCEVAtScope(LHS, L);
9381 RHS = getSCEVAtScope(RHS, L);
9382
9383 // At this point, we would like to compute how many iterations of the
9384 // loop the predicate will return true for these inputs.
9385 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9386 // If there is a loop-invariant, force it into the RHS.
9387 std::swap(LHS, RHS);
9389 }
9390
9391 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9393 // Simplify the operands before analyzing them.
9394 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9395
9396 // If we have a comparison of a chrec against a constant, try to use value
9397 // ranges to answer this query.
9398 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9399 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9400 if (AddRec->getLoop() == L) {
9401 // Form the constant range.
9402 ConstantRange CompRange =
9403 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9404
9405 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9406 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9407 }
9408
9409 // If this loop must exit based on this condition (or execute undefined
9410 // behaviour), see if we can improve wrap flags. This is essentially
9411 // a must execute style proof.
9412 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9413 // If we can prove the test sequence produced must repeat the same values
9414 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9415 // because if it did, we'd have an infinite (undefined) loop.
9416 // TODO: We can peel off any functions which are invertible *in L*. Loop
9417 // invariant terms are effectively constants for our purposes here.
9418 SCEVUse InnerLHS = LHS;
9419 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9420 InnerLHS = ZExt->getOperand();
9421 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9422 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9423 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9424 /*OrNegative=*/true)) {
9425 auto Flags = AR->getNoWrapFlags();
9426 Flags = setFlags(Flags, SCEV::FlagNW);
9429 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9430 }
9431
9432 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9433 // From no-self-wrap, this follows trivially from the fact that every
9434 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9435 // last value before (un)signed wrap. Since we know that last value
9436 // didn't exit, nor will any smaller one.
9437 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9438 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9439 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9440 AR && AR->getLoop() == L && AR->isAffine() &&
9441 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9442 isKnownPositive(AR->getStepRecurrence(*this))) {
9443 auto Flags = AR->getNoWrapFlags();
9444 Flags = setFlags(Flags, WrapType);
9447 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9448 }
9449 }
9450 }
9451
9452 switch (Pred) {
9453 case ICmpInst::ICMP_NE: { // while (X != Y)
9454 // Convert to: while (X-Y != 0)
9455 if (LHS->getType()->isPointerTy()) {
9458 return LHS;
9459 }
9460 if (RHS->getType()->isPointerTy()) {
9463 return RHS;
9464 }
9465 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9466 AllowPredicates);
9467 if (EL.hasAnyInfo())
9468 return EL;
9469 break;
9470 }
9471 case ICmpInst::ICMP_EQ: { // while (X == Y)
9472 // Convert to: while (X-Y == 0)
9473 if (LHS->getType()->isPointerTy()) {
9476 return LHS;
9477 }
9478 if (RHS->getType()->isPointerTy()) {
9481 return RHS;
9482 }
9483 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9484 if (EL.hasAnyInfo()) return EL;
9485 break;
9486 }
9487 case ICmpInst::ICMP_SLE:
9488 case ICmpInst::ICMP_ULE:
9489 // Since the loop is finite, an invariant RHS cannot include the boundary
9490 // value, otherwise it would loop forever.
9491 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9492 !isLoopInvariant(RHS, L)) {
9493 // Otherwise, perform the addition in a wider type, to avoid overflow.
9494 // If the LHS is an addrec with the appropriate nowrap flag, the
9495 // extension will be sunk into it and the exit count can be analyzed.
9496 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9497 if (!OldType)
9498 break;
9499 // Prefer doubling the bitwidth over adding a single bit to make it more
9500 // likely that we use a legal type.
9501 auto *NewType =
9502 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9503 if (ICmpInst::isSigned(Pred)) {
9504 LHS = getSignExtendExpr(LHS, NewType);
9505 RHS = getSignExtendExpr(RHS, NewType);
9506 } else {
9507 LHS = getZeroExtendExpr(LHS, NewType);
9508 RHS = getZeroExtendExpr(RHS, NewType);
9509 }
9510 }
9512 [[fallthrough]];
9513 case ICmpInst::ICMP_SLT:
9514 case ICmpInst::ICMP_ULT: { // while (X < Y)
9515 bool IsSigned = ICmpInst::isSigned(Pred);
9516 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9517 ControlsOnlyExit, AllowPredicates);
9518 if (EL.hasAnyInfo())
9519 return EL;
9520 break;
9521 }
9522 case ICmpInst::ICMP_SGE:
9523 case ICmpInst::ICMP_UGE:
9524 // Since the loop is finite, an invariant RHS cannot include the boundary
9525 // value, otherwise it would loop forever.
9526 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9527 !isLoopInvariant(RHS, L))
9528 break;
9530 [[fallthrough]];
9531 case ICmpInst::ICMP_SGT:
9532 case ICmpInst::ICMP_UGT: { // while (X > Y)
9533 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9534 bool IsSigned = ICmpInst::isSigned(Pred);
9535 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9536 ControlsOnlyExit, AllowPredicates);
9537 if (EL.hasAnyInfo())
9538 return EL;
9539 break;
9540 }
9541 default:
9542 break;
9543 }
9544
9545 return getCouldNotCompute();
9546}
9547
9548ScalarEvolution::ExitLimit
9549ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9550 SwitchInst *Switch,
9551 BasicBlock *ExitingBlock,
9552 bool ControlsOnlyExit) {
9553 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9554
9555 // Give up if the exit is the default dest of a switch.
9556 if (Switch->getDefaultDest() == ExitingBlock)
9557 return getCouldNotCompute();
9558
9559 assert(L->contains(Switch->getDefaultDest()) &&
9560 "Default case must not exit the loop!");
9561 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9562 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9563
9564 // while (X != Y) --> while (X-Y != 0)
9565 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9566 if (EL.hasAnyInfo())
9567 return EL;
9568
9569 return getCouldNotCompute();
9570}
9571
9572static ConstantInt *
9574 ScalarEvolution &SE) {
9575 const SCEV *InVal = SE.getConstant(C);
9576 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9578 "Evaluation of SCEV at constant didn't fold correctly?");
9579 return cast<SCEVConstant>(Val)->getValue();
9580}
9581
9582ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9583 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9584 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9585 if (!RHS)
9586 return getCouldNotCompute();
9587
9588 const BasicBlock *Latch = L->getLoopLatch();
9589 if (!Latch)
9590 return getCouldNotCompute();
9591
9592 const BasicBlock *Predecessor = L->getLoopPredecessor();
9593 if (!Predecessor)
9594 return getCouldNotCompute();
9595
9596 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9597 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9598 // OutShiftAmt.
9599 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9600 Instruction::BinaryOps &OutOpCode,
9601 unsigned &OutShiftAmt) {
9602 using namespace PatternMatch;
9603
9604 ConstantInt *ShiftAmt;
9605 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9606 OutOpCode = Instruction::LShr;
9607 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9608 OutOpCode = Instruction::AShr;
9609 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9610 OutOpCode = Instruction::Shl;
9611 else
9612 return false;
9613
9614 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9615 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9616 return false;
9617 OutShiftAmt = Amt;
9618 return true;
9619 };
9620
9621 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9622 //
9623 // loop:
9624 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9625 // %iv.shifted = lshr i32 %iv, <positive constant>
9626 //
9627 // Return true on a successful match. Return the corresponding PHI node (%iv
9628 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9629 // shift amount in ShiftAmtOut.
9630 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9631 Instruction::BinaryOps &OpCodeOut,
9632 unsigned &ShiftAmtOut) {
9633 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9634
9635 {
9637 Value *V;
9638 unsigned Amt;
9639
9640 // If we encounter a shift instruction, "peel off" the shift operation,
9641 // and remember that we did so. Later when we inspect %iv's backedge
9642 // value, we will make sure that the backedge value uses the same
9643 // operation.
9644 //
9645 // Note: the peeled shift operation does not have to be the same
9646 // instruction as the one feeding into the PHI's backedge value. We only
9647 // really care about it being the same *kind* of shift instruction --
9648 // that's all that is required for our later inferences to hold.
9649 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9650 PostShiftOpCode = OpC;
9651 LHS = V;
9652 }
9653 }
9654
9655 PNOut = dyn_cast<PHINode>(LHS);
9656 if (!PNOut || PNOut->getParent() != L->getHeader())
9657 return false;
9658
9659 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9660 Value *OpLHS;
9661
9662 return
9663 // The backedge value for the PHI node must be a shift by a positive
9664 // amount
9665 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9666
9667 // of the PHI node itself
9668 OpLHS == PNOut &&
9669
9670 // and the kind of shift should be match the kind of shift we peeled
9671 // off, if any.
9672 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9673 };
9674
9675 PHINode *PN;
9677 unsigned ShiftAmt;
9678 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9679 return getCouldNotCompute();
9680
9681 const DataLayout &DL = getDataLayout();
9682
9683 // The key rationale for this optimization is that for some kinds of shift
9684 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9685 // within a finite number of iterations. If the condition guarding the
9686 // backedge (in the sense that the backedge is taken if the condition is true)
9687 // is false for the value the shift recurrence stabilizes to, then we know
9688 // that the backedge is taken only a finite number of times.
9689
9690 ConstantInt *StableValue = nullptr;
9691 switch (OpCode) {
9692 default:
9693 llvm_unreachable("Impossible case!");
9694
9695 case Instruction::AShr: {
9696 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9697 // bitwidth(K) iterations.
9698 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9699 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9700 Predecessor->getTerminator(), &DT);
9701 auto *Ty = cast<IntegerType>(RHS->getType());
9702 if (Known.isNonNegative())
9703 StableValue = ConstantInt::get(Ty, 0);
9704 else if (Known.isNegative())
9705 StableValue = ConstantInt::get(Ty, -1, true);
9706 else
9707 return getCouldNotCompute();
9708
9709 break;
9710 }
9711 case Instruction::LShr:
9712 case Instruction::Shl:
9713 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9714 // stabilize to 0 in at most bitwidth(K) iterations.
9715 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9716 break;
9717 }
9718
9719 auto *Result =
9720 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9721 assert(Result->getType()->isIntegerTy(1) &&
9722 "Otherwise cannot be an operand to a branch instruction");
9723
9724 if (Result->isNullValue()) {
9725 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9726 unsigned MaxBTC = BitWidth;
9727
9728 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9729 // compute a tighter max backedge-taken count from the range of the start
9730 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9731 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9732 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9733 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9734 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9735 const SCEV *StartSCEV = getSCEV(StartValue);
9736 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9737 if (MaxStart.isStrictlyPositive()) {
9738 unsigned ActiveBits = MaxStart.getActiveBits();
9739 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9740 MaxBTC = std::min(MaxBTC, RangeBTC);
9741 }
9742 }
9743
9744 const SCEV *UpperBound =
9746 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9747 }
9748
9749 return getCouldNotCompute();
9750}
9751
9752/// Return true if we can constant fold an instruction of the specified type,
9753/// assuming that all operands were constants.
9754static bool canConstantFold(const Instruction *I,
9755 const TargetLibraryInfo *TLI) {
9759 return true;
9760
9761 if (const CallInst *CI = dyn_cast<CallInst>(I))
9762 if (const Function *F = CI->getCalledFunction())
9763 return canConstantFoldCallTo(CI, F, TLI);
9764 return false;
9765}
9766
9767/// Determine whether this instruction can constant evolve within this loop
9768/// assuming its operands can all constant evolve.
9769static bool canConstantEvolve(Instruction *I, const Loop *L,
9770 const TargetLibraryInfo *TLI) {
9771 // An instruction outside of the loop can't be derived from a loop PHI.
9772 if (!L->contains(I)) return false;
9773
9774 if (isa<PHINode>(I)) {
9775 // We don't currently keep track of the control flow needed to evaluate
9776 // PHIs, so we cannot handle PHIs inside of loops.
9777 return L->getHeader() == I->getParent();
9778 }
9779
9780 // If we won't be able to constant fold this expression even if the operands
9781 // are constants, bail early.
9782 return canConstantFold(I, TLI);
9783}
9784
9785/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9786/// recursing through each instruction operand until reaching a loop header phi.
9787static PHINode *
9790 const TargetLibraryInfo *TLI, unsigned Depth) {
9792 return nullptr;
9793
9794 // Otherwise, we can evaluate this instruction if all of its operands are
9795 // constant or derived from a PHI node themselves.
9796 PHINode *PHI = nullptr;
9797 for (Value *Op : UseInst->operands()) {
9798 if (isa<Constant>(Op)) continue;
9799
9801 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9802 return nullptr;
9803
9804 PHINode *P = dyn_cast<PHINode>(OpInst);
9805 if (!P)
9806 // If this operand is already visited, reuse the prior result.
9807 // We may have P != PHI if this is the deepest point at which the
9808 // inconsistent paths meet.
9809 P = PHIMap.lookup(OpInst);
9810 if (!P) {
9811 // Recurse and memoize the results, whether a phi is found or not.
9812 // This recursive call invalidates pointers into PHIMap.
9813 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9814 PHIMap[OpInst] = P;
9815 }
9816 if (!P)
9817 return nullptr; // Not evolving from PHI
9818 if (PHI && PHI != P)
9819 return nullptr; // Evolving from multiple different PHIs.
9820 PHI = P;
9821 }
9822 // This is a expression evolving from a constant PHI!
9823 return PHI;
9824}
9825
9826/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9827/// in the loop that V is derived from. We allow arbitrary operations along the
9828/// way, but the operands of an operation must either be constants or a value
9829/// derived from a constant PHI. If this expression does not fit with these
9830/// constraints, return null.
9832 const TargetLibraryInfo *TLI) {
9834 if (!I || !canConstantEvolve(I, L, TLI))
9835 return nullptr;
9836
9837 if (PHINode *PN = dyn_cast<PHINode>(I))
9838 return PN;
9839
9840 // Record non-constant instructions contained by the loop.
9842 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9843}
9844
9845/// EvaluateExpression - Given an expression that passes the
9846/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9847/// in the loop has the value PHIVal. If we can't fold this expression for some
9848/// reason, return null.
9851 const DataLayout &DL,
9852 const TargetLibraryInfo *TLI) {
9853 // Convenient constant check, but redundant for recursive calls.
9854 if (Constant *C = dyn_cast<Constant>(V)) return C;
9856 if (!I) return nullptr;
9857
9858 if (Constant *C = Vals.lookup(I)) return C;
9859
9860 // An instruction inside the loop depends on a value outside the loop that we
9861 // weren't given a mapping for, or a value such as a call inside the loop.
9862 if (!canConstantEvolve(I, L, TLI))
9863 return nullptr;
9864
9865 // An unmapped PHI can be due to a branch or another loop inside this loop,
9866 // or due to this not being the initial iteration through a loop where we
9867 // couldn't compute the evolution of this particular PHI last time.
9868 if (isa<PHINode>(I)) return nullptr;
9869
9870 std::vector<Constant*> Operands(I->getNumOperands());
9871
9872 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9873 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9874 if (!Operand) {
9875 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9876 if (!Operands[i]) return nullptr;
9877 continue;
9878 }
9879 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9880 Vals[Operand] = C;
9881 if (!C) return nullptr;
9882 Operands[i] = C;
9883 }
9884
9885 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9886 /*AllowNonDeterministic=*/false);
9887}
9888
9889
9890// If every incoming value to PN except the one for BB is a specific Constant,
9891// return that, else return nullptr.
9893 Constant *IncomingVal = nullptr;
9894
9895 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9896 if (PN->getIncomingBlock(i) == BB)
9897 continue;
9898
9899 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9900 if (!CurrentVal)
9901 return nullptr;
9902
9903 if (IncomingVal != CurrentVal) {
9904 if (IncomingVal)
9905 return nullptr;
9906 IncomingVal = CurrentVal;
9907 }
9908 }
9909
9910 return IncomingVal;
9911}
9912
9913/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9914/// in the header of its containing loop, we know the loop executes a
9915/// constant number of times, and the PHI node is just a recurrence
9916/// involving constants, fold it.
9917Constant *
9918ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9919 const APInt &BEs,
9920 const Loop *L) {
9921 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9922 if (!Inserted)
9923 return I->second;
9924
9926 return nullptr; // Not going to evaluate it.
9927
9928 Constant *&RetVal = I->second;
9929
9930 DenseMap<Instruction *, Constant *> CurrentIterVals;
9931 BasicBlock *Header = L->getHeader();
9932 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9933
9934 BasicBlock *Latch = L->getLoopLatch();
9935 if (!Latch)
9936 return nullptr;
9937
9938 for (PHINode &PHI : Header->phis()) {
9939 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9940 CurrentIterVals[&PHI] = StartCST;
9941 }
9942 if (!CurrentIterVals.count(PN))
9943 return RetVal = nullptr;
9944
9945 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9946
9947 // Execute the loop symbolically to determine the exit value.
9948 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9949 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9950
9951 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9952 unsigned IterationNum = 0;
9953 const DataLayout &DL = getDataLayout();
9954 for (; ; ++IterationNum) {
9955 if (IterationNum == NumIterations)
9956 return RetVal = CurrentIterVals[PN]; // Got exit value!
9957
9958 // Compute the value of the PHIs for the next iteration.
9959 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9960 DenseMap<Instruction *, Constant *> NextIterVals;
9961 Constant *NextPHI =
9962 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9963 if (!NextPHI)
9964 return nullptr; // Couldn't evaluate!
9965 NextIterVals[PN] = NextPHI;
9966
9967 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9968
9969 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9970 // cease to be able to evaluate one of them or if they stop evolving,
9971 // because that doesn't necessarily prevent us from computing PN.
9973 for (const auto &I : CurrentIterVals) {
9974 PHINode *PHI = dyn_cast<PHINode>(I.first);
9975 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9976 PHIsToCompute.emplace_back(PHI, I.second);
9977 }
9978 // We use two distinct loops because EvaluateExpression may invalidate any
9979 // iterators into CurrentIterVals.
9980 for (const auto &I : PHIsToCompute) {
9981 PHINode *PHI = I.first;
9982 Constant *&NextPHI = NextIterVals[PHI];
9983 if (!NextPHI) { // Not already computed.
9984 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9985 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9986 }
9987 if (NextPHI != I.second)
9988 StoppedEvolving = false;
9989 }
9990
9991 // If all entries in CurrentIterVals == NextIterVals then we can stop
9992 // iterating, the loop can't continue to change.
9993 if (StoppedEvolving)
9994 return RetVal = CurrentIterVals[PN];
9995
9996 CurrentIterVals.swap(NextIterVals);
9997 }
9998}
9999
10000const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10001 Value *Cond,
10002 bool ExitWhen) {
10003 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
10004 if (!PN) return getCouldNotCompute();
10005
10006 // If the loop is canonicalized, the PHI will have exactly two entries.
10007 // That's the only form we support here.
10008 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10009
10010 DenseMap<Instruction *, Constant *> CurrentIterVals;
10011 BasicBlock *Header = L->getHeader();
10012 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10013
10014 BasicBlock *Latch = L->getLoopLatch();
10015 assert(Latch && "Should follow from NumIncomingValues == 2!");
10016
10017 for (PHINode &PHI : Header->phis()) {
10018 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10019 CurrentIterVals[&PHI] = StartCST;
10020 }
10021 if (!CurrentIterVals.count(PN))
10022 return getCouldNotCompute();
10023
10024 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10025 // the loop symbolically to determine when the condition gets a value of
10026 // "ExitWhen".
10027 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10028 const DataLayout &DL = getDataLayout();
10029 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10030 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10031 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10032
10033 // Couldn't symbolically evaluate.
10034 if (!CondVal) return getCouldNotCompute();
10035
10036 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10037 ++NumBruteForceTripCountsComputed;
10038 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10039 }
10040
10041 // Update all the PHI nodes for the next iteration.
10042 DenseMap<Instruction *, Constant *> NextIterVals;
10043
10044 // Create a list of which PHIs we need to compute. We want to do this before
10045 // calling EvaluateExpression on them because that may invalidate iterators
10046 // into CurrentIterVals.
10047 SmallVector<PHINode *, 8> PHIsToCompute;
10048 for (const auto &I : CurrentIterVals) {
10049 PHINode *PHI = dyn_cast<PHINode>(I.first);
10050 if (!PHI || PHI->getParent() != Header) continue;
10051 PHIsToCompute.push_back(PHI);
10052 }
10053 for (PHINode *PHI : PHIsToCompute) {
10054 Constant *&NextPHI = NextIterVals[PHI];
10055 if (NextPHI) continue; // Already computed!
10056
10057 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10058 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10059 }
10060 CurrentIterVals.swap(NextIterVals);
10061 }
10062
10063 // Too many iterations were needed to evaluate.
10064 return getCouldNotCompute();
10065}
10066
10068 if (isa<SCEVConstant>(V))
10069 return V;
10070
10071 auto &Values = ValuesAtScopes[V];
10072 // Check to see if we've folded this expression at this loop before.
10073 for (auto &LS : Values)
10074 if (LS.first == L)
10075 return LS.second ? LS.second : SCEVUse(V);
10076
10077 Values.emplace_back(L, nullptr);
10078
10079 // Otherwise compute it.
10080 SCEVUse C = computeSCEVAtScope(V, L);
10081 for (auto &LS : reverse(ValuesAtScopes[V]))
10082 if (LS.first == L) {
10083 LS.second = C;
10084 // Record the dependency under the bare expression: invalidation walks
10085 // expressions, and any use flags on C do not change which expression
10086 // this is the value at scope of.
10087 if (!isa<SCEVConstant>(C))
10088 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10089 break;
10090 }
10091 return C;
10092}
10093
10095 const BasicBlock *ExitingBlock) {
10096 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10097 if (!isLoopInvariant(ExitValue, L)) {
10098 // If we failed to evaluate it in the outer scope, try to evaluate an
10099 // addrec for the specific exit.
10100 // TODO: Generalize this to other expressions.
10101 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10102 if (!isa<SCEVCouldNotCompute>(ExitCount))
10103 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10104 if (AddRec->getLoop() == L)
10105 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10106 }
10107 return ExitValue;
10108}
10109
10110/// This builds up a Constant using the ConstantExpr interface. That way, we
10111/// will return Constants for objects which aren't represented by a
10112/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10113/// Returns NULL if the SCEV isn't representable as a Constant.
10115 switch (V->getSCEVType()) {
10116 case scCouldNotCompute:
10117 case scAddRecExpr:
10118 case scVScale:
10119 return nullptr;
10120 case scConstant:
10121 return cast<SCEVConstant>(V)->getValue();
10122 case scUnknown:
10124 case scPtrToAddr: {
10126 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10127 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10128
10129 return nullptr;
10130 }
10131 case scTruncate: {
10133 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10134 return ConstantExpr::getTrunc(CastOp, ST->getType());
10135 return nullptr;
10136 }
10137 case scAddExpr: {
10138 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10139 Constant *C = nullptr;
10140 for (const SCEV *Op : SA->operands()) {
10142 if (!OpC)
10143 return nullptr;
10144 if (!C) {
10145 C = OpC;
10146 continue;
10147 }
10148 assert(!C->getType()->isPointerTy() &&
10149 "Can only have one pointer, and it must be last");
10150 if (OpC->getType()->isPointerTy()) {
10151 // The offsets have been converted to bytes. We can add bytes using
10152 // an i8 GEP.
10153 C = ConstantExpr::getPtrAdd(OpC, C);
10154 } else {
10155 C = ConstantExpr::getAdd(C, OpC);
10156 }
10157 }
10158 return C;
10159 }
10160 case scMulExpr:
10161 case scSignExtend:
10162 case scZeroExtend:
10163 case scUDivExpr:
10164 case scSMaxExpr:
10165 case scUMaxExpr:
10166 case scSMinExpr:
10167 case scUMinExpr:
10169 return nullptr;
10170 }
10171 llvm_unreachable("Unknown SCEV kind!");
10172}
10173
10174const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10175 SmallVectorImpl<SCEVUse> &NewOps) {
10176 switch (S->getSCEVType()) {
10177 case scTruncate:
10178 case scZeroExtend:
10179 case scSignExtend:
10180 case scPtrToAddr:
10181 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10182 case scAddRecExpr: {
10183 auto *AddRec = cast<SCEVAddRecExpr>(S);
10184 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10185 }
10186 case scAddExpr:
10187 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10188 case scMulExpr:
10189 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10190 case scUDivExpr:
10191 return getUDivExpr(NewOps[0], NewOps[1]);
10192 case scUMaxExpr:
10193 case scSMaxExpr:
10194 case scUMinExpr:
10195 case scSMinExpr:
10196 return getMinMaxExpr(S->getSCEVType(), NewOps);
10198 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10199 case scConstant:
10200 case scVScale:
10201 case scUnknown:
10202 return S;
10203 case scCouldNotCompute:
10204 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10205 }
10206 llvm_unreachable("Unknown SCEV kind!");
10207}
10208
10209SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10210 switch (V->getSCEVType()) {
10211 case scConstant:
10212 case scVScale:
10213 return V;
10214 case scAddRecExpr: {
10215 // If this is a loop recurrence for a loop that does not contain L, then we
10216 // are dealing with the final value computed by the loop.
10217 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10218 // First, attempt to evaluate each operand.
10219 // Avoid performing the look-up in the common case where the specified
10220 // expression has no loop-variant portions.
10221 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10222 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10223 if (OpAtScope == AddRec->getOperand(i))
10224 continue;
10225
10226 // Okay, at least one of these operands is loop variant but might be
10227 // foldable. Build a new instance of the folded commutative expression.
10229 NewOps.reserve(AddRec->getNumOperands());
10230 append_range(NewOps, AddRec->operands().take_front(i));
10231 NewOps.push_back(OpAtScope);
10232 for (++i; i != e; ++i)
10233 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10234
10235 const SCEV *FoldedRec = getAddRecExpr(
10236 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10237 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10238 // The addrec may be folded to a nonrecurrence, for example, if the
10239 // induction variable is multiplied by zero after constant folding. Go
10240 // ahead and return the folded value.
10241 if (!AddRec)
10242 return FoldedRec;
10243 break;
10244 }
10245
10246 // If the scope is outside the addrec's loop, evaluate it by using the
10247 // loop exit value of the addrec.
10248 if (!AddRec->getLoop()->contains(L)) {
10249 SCEVUse ExitValue = AddRec->getExitValue(*this);
10250 if (isa<SCEVCouldNotCompute>(ExitValue))
10251 return AddRec;
10252 return ExitValue;
10253 }
10254
10255 return AddRec;
10256 }
10257 case scTruncate:
10258 case scZeroExtend:
10259 case scSignExtend:
10260 case scPtrToAddr:
10261 case scAddExpr:
10262 case scMulExpr:
10263 case scUDivExpr:
10264 case scUMaxExpr:
10265 case scSMaxExpr:
10266 case scUMinExpr:
10267 case scSMinExpr:
10268 case scSequentialUMinExpr: {
10269 ArrayRef<SCEVUse> Ops = V->operands();
10270 // Avoid performing the look-up in the common case where the specified
10271 // expression has no loop-variant portions.
10272 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10273 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10274 if (OpAtScope != Ops[i].getPointer()) {
10275 // Okay, at least one of these operands is loop variant but might be
10276 // foldable. Build a new instance of the folded commutative expression.
10278 NewOps.reserve(Ops.size());
10279 append_range(NewOps, Ops.take_front(i));
10280 NewOps.push_back(OpAtScope);
10281
10282 for (++i; i != e; ++i) {
10283 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10284 NewOps.push_back(OpAtScope);
10285 }
10286
10287 return getWithOperands(V, NewOps);
10288 }
10289 }
10290 // If we got here, all operands are loop invariant.
10291 return V;
10292 }
10293 case scUnknown: {
10294 // If this instruction is evolved from a constant-evolving PHI, compute the
10295 // exit value from the loop without using SCEVs.
10296 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10298 if (!I)
10299 return V; // This is some other type of SCEVUnknown, just return it.
10300
10301 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10302 const Loop *CurrLoop = this->LI[I->getParent()];
10303 // Looking for loop exit value.
10304 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10305 PN->getParent() == CurrLoop->getHeader()) {
10306 // Okay, there is no closed form solution for the PHI node. Check
10307 // to see if the loop that contains it has a known backedge-taken
10308 // count. If so, we may be able to force computation of the exit
10309 // value.
10310 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10311 // This trivial case can show up in some degenerate cases where
10312 // the incoming IR has not yet been fully simplified.
10313 if (BackedgeTakenCount->isZero()) {
10314 Value *InitValue = nullptr;
10315 bool MultipleInitValues = false;
10316 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10317 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10318 if (!InitValue)
10319 InitValue = PN->getIncomingValue(i);
10320 else if (InitValue != PN->getIncomingValue(i)) {
10321 MultipleInitValues = true;
10322 break;
10323 }
10324 }
10325 }
10326 if (!MultipleInitValues && InitValue)
10327 return getSCEV(InitValue);
10328 }
10329 // Do we have a loop invariant value flowing around the backedge
10330 // for a loop which must execute the backedge?
10331 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10332 isKnownNonZero(BackedgeTakenCount) &&
10333 PN->getNumIncomingValues() == 2) {
10334
10335 unsigned InLoopPred =
10336 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10337 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10338 if (CurrLoop->isLoopInvariant(BackedgeVal))
10339 return getSCEV(BackedgeVal);
10340 }
10341 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10342 // Okay, we know how many times the containing loop executes. If
10343 // this is a constant evolving PHI node, get the final value at
10344 // the specified iteration number.
10345 Constant *RV =
10346 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10347 if (RV)
10348 return getSCEV(RV);
10349 }
10350 }
10351 }
10352
10353 // Okay, this is an expression that we cannot symbolically evaluate
10354 // into a SCEV. Check to see if it's possible to symbolically evaluate
10355 // the arguments into constants, and if so, try to constant propagate the
10356 // result. This is particularly useful for computing loop exit values.
10357 if (!canConstantFold(I, &TLI))
10358 return V; // This is some other type of SCEVUnknown, just return it.
10359
10360 SmallVector<Constant *, 4> Operands;
10361 Operands.reserve(I->getNumOperands());
10362 bool MadeImprovement = false;
10363 for (Value *Op : I->operands()) {
10364 if (Constant *C = dyn_cast<Constant>(Op)) {
10365 Operands.push_back(C);
10366 continue;
10367 }
10368
10369 // If any of the operands is non-constant and if they are
10370 // non-integer and non-pointer, don't even try to analyze them
10371 // with scev techniques.
10372 if (!isSCEVable(Op->getType()))
10373 return V;
10374
10375 const SCEV *OrigV = getSCEV(Op);
10376 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10377 MadeImprovement |= OrigV != OpV;
10378
10380 if (!C)
10381 return V;
10382 assert(C->getType() == Op->getType() && "Type mismatch");
10383 Operands.push_back(C);
10384 }
10385
10386 // Check to see if getSCEVAtScope actually made an improvement.
10387 if (!MadeImprovement)
10388 return V; // This is some other type of SCEVUnknown, just return it.
10389
10390 Constant *C = nullptr;
10391 const DataLayout &DL = getDataLayout();
10392 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10393 /*AllowNonDeterministic=*/false);
10394 if (!C)
10395 return V;
10396 return getSCEV(C);
10397 }
10398 case scCouldNotCompute:
10399 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10400 }
10401 llvm_unreachable("Unknown SCEV type!");
10402}
10403
10405 return getSCEVAtScope(getSCEV(V), L);
10406}
10407
10408const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10410 return stripInjectiveFunctions(ZExt->getOperand());
10412 return stripInjectiveFunctions(SExt->getOperand());
10413 return S;
10414}
10415
10416/// Finds the minimum unsigned root of the following equation:
10417///
10418/// A * X = B (mod N)
10419///
10420/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10421/// A and B isn't important.
10422///
10423/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10424static const SCEV *
10427 ScalarEvolution &SE, const Loop *L) {
10428 uint32_t BW = A.getBitWidth();
10429 assert(BW == SE.getTypeSizeInBits(B->getType()));
10430 assert(A != 0 && "A must be non-zero.");
10431
10432 // 1. D = gcd(A, N)
10433 //
10434 // The gcd of A and N may have only one prime factor: 2. The number of
10435 // trailing zeros in A is its multiplicity
10436 uint32_t Mult2 = A.countr_zero();
10437 // D = 2^Mult2
10438
10439 // 2. Check if B is divisible by D.
10440 //
10441 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10442 // is not less than multiplicity of this prime factor for D.
10443 unsigned MinTZ = SE.getMinTrailingZeros(B);
10444 // Try again with the terminator of the loop predecessor for context-specific
10445 // result, if MinTZ s too small.
10446 if (MinTZ < Mult2 && L->getLoopPredecessor())
10447 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10448 if (MinTZ < Mult2) {
10449 // Check if we can prove there's no remainder using URem.
10450 const SCEV *URem =
10451 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10452 const SCEV *Zero = SE.getZero(B->getType());
10453 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10454 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10455 if (!Predicates)
10456 return SE.getCouldNotCompute();
10457
10458 // Avoid adding a predicate that is known to be false.
10459 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10460 return SE.getCouldNotCompute();
10461 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10462 }
10463 }
10464
10465 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10466 // modulo (N / D).
10467 //
10468 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10469 // (N / D) in general. The inverse itself always fits into BW bits, though,
10470 // so we immediately truncate it.
10471 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10472 APInt I = AD.multiplicativeInverse().zext(BW);
10473
10474 // 4. Compute the minimum unsigned root of the equation:
10475 // I * (B / D) mod (N / D)
10476 // To simplify the computation, we factor out the divide by D:
10477 // (I * B mod N) / D
10478 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10479 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10480}
10481
10482/// For a given quadratic addrec, generate coefficients of the corresponding
10483/// quadratic equation, multiplied by a common value to ensure that they are
10484/// integers.
10485/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10486/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10487/// were multiplied by, and BitWidth is the bit width of the original addrec
10488/// coefficients.
10489/// This function returns std::nullopt if the addrec coefficients are not
10490/// compile- time constants.
10491static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10493 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10494 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10495 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10496 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10497 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10498 << *AddRec << '\n');
10499
10500 // We currently can only solve this if the coefficients are constants.
10501 if (!LC || !MC || !NC) {
10502 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10503 return std::nullopt;
10504 }
10505
10506 APInt L = LC->getAPInt();
10507 APInt M = MC->getAPInt();
10508 APInt N = NC->getAPInt();
10509 assert(!N.isZero() && "This is not a quadratic addrec");
10510
10511 unsigned BitWidth = LC->getAPInt().getBitWidth();
10512 unsigned NewWidth = BitWidth + 1;
10513 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10514 << BitWidth << '\n');
10515 // The sign-extension (as opposed to a zero-extension) here matches the
10516 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10517 N = N.sext(NewWidth);
10518 M = M.sext(NewWidth);
10519 L = L.sext(NewWidth);
10520
10521 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10522 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10523 // L+M, L+2M+N, L+3M+3N, ...
10524 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10525 //
10526 // The equation Acc = 0 is then
10527 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10528 // In a quadratic form it becomes:
10529 // N n^2 + (2M-N) n + 2L = 0.
10530
10531 APInt A = N;
10532 APInt B = 2 * M - A;
10533 APInt C = 2 * L;
10534 APInt T = APInt(NewWidth, 2);
10535 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10536 << "x + " << C << ", coeff bw: " << NewWidth
10537 << ", multiplied by " << T << '\n');
10538 return std::make_tuple(A, B, C, T, BitWidth);
10539}
10540
10541/// Helper function to compare optional APInts:
10542/// (a) if X and Y both exist, return min(X, Y),
10543/// (b) if neither X nor Y exist, return std::nullopt,
10544/// (c) if exactly one of X and Y exists, return that value.
10545static std::optional<APInt> MinOptional(std::optional<APInt> X,
10546 std::optional<APInt> Y) {
10547 if (X && Y) {
10548 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10549 APInt XW = X->sext(W);
10550 APInt YW = Y->sext(W);
10551 return XW.slt(YW) ? *X : *Y;
10552 }
10553 if (!X && !Y)
10554 return std::nullopt;
10555 return X ? *X : *Y;
10556}
10557
10558/// Helper function to truncate an optional APInt to a given BitWidth.
10559/// When solving addrec-related equations, it is preferable to return a value
10560/// that has the same bit width as the original addrec's coefficients. If the
10561/// solution fits in the original bit width, truncate it (except for i1).
10562/// Returning a value of a different bit width may inhibit some optimizations.
10563///
10564/// In general, a solution to a quadratic equation generated from an addrec
10565/// may require BW+1 bits, where BW is the bit width of the addrec's
10566/// coefficients. The reason is that the coefficients of the quadratic
10567/// equation are BW+1 bits wide (to avoid truncation when converting from
10568/// the addrec to the equation).
10569static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10570 unsigned BitWidth) {
10571 if (!X)
10572 return std::nullopt;
10573 unsigned W = X->getBitWidth();
10575 return X->trunc(BitWidth);
10576 return X;
10577}
10578
10579/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10580/// iterations. The values L, M, N are assumed to be signed, and they
10581/// should all have the same bit widths.
10582/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10583/// where BW is the bit width of the addrec's coefficients.
10584/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10585/// returned as such, otherwise the bit width of the returned value may
10586/// be greater than BW.
10587///
10588/// This function returns std::nullopt if
10589/// (a) the addrec coefficients are not constant, or
10590/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10591/// like x^2 = 5, no integer solutions exist, in other cases an integer
10592/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10593static std::optional<APInt>
10595 APInt A, B, C, M;
10596 unsigned BitWidth;
10597 auto T = GetQuadraticEquation(AddRec);
10598 if (!T)
10599 return std::nullopt;
10600
10601 std::tie(A, B, C, M, BitWidth) = *T;
10602 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10603 std::optional<APInt> X =
10605 if (!X)
10606 return std::nullopt;
10607
10608 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10609 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10610 if (!V->isZero())
10611 return std::nullopt;
10612
10613 return TruncIfPossible(X, BitWidth);
10614}
10615
10616/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10617/// iterations. The values M, N are assumed to be signed, and they
10618/// should all have the same bit widths.
10619/// Find the least n such that c(n) does not belong to the given range,
10620/// while c(n-1) does.
10621///
10622/// This function returns std::nullopt if
10623/// (a) the addrec coefficients are not constant, or
10624/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10625/// bounds of the range.
10626static std::optional<APInt>
10628 const ConstantRange &Range, ScalarEvolution &SE) {
10629 assert(AddRec->getOperand(0)->isZero() &&
10630 "Starting value of addrec should be 0");
10631 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10632 << Range << ", addrec " << *AddRec << '\n');
10633 // This case is handled in getNumIterationsInRange. Here we can assume that
10634 // we start in the range.
10635 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10636 "Addrec's initial value should be in range");
10637
10638 APInt A, B, C, M;
10639 unsigned BitWidth;
10640 auto T = GetQuadraticEquation(AddRec);
10641 if (!T)
10642 return std::nullopt;
10643
10644 // Be careful about the return value: there can be two reasons for not
10645 // returning an actual number. First, if no solutions to the equations
10646 // were found, and second, if the solutions don't leave the given range.
10647 // The first case means that the actual solution is "unknown", the second
10648 // means that it's known, but not valid. If the solution is unknown, we
10649 // cannot make any conclusions.
10650 // Return a pair: the optional solution and a flag indicating if the
10651 // solution was found.
10652 auto SolveForBoundary =
10653 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10654 // Solve for signed overflow and unsigned overflow, pick the lower
10655 // solution.
10656 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10657 << Bound << " (before multiplying by " << M << ")\n");
10658 Bound *= M; // The quadratic equation multiplier.
10659
10660 std::optional<APInt> SO;
10661 if (BitWidth > 1) {
10662 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10663 "signed overflow\n");
10665 }
10666 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10667 "unsigned overflow\n");
10668 std::optional<APInt> UO =
10670
10671 auto LeavesRange = [&] (const APInt &X) {
10672 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10673 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10674 if (Range.contains(V0->getValue()))
10675 return false;
10676 // X should be at least 1, so X-1 is non-negative.
10677 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10679 if (Range.contains(V1->getValue()))
10680 return true;
10681 return false;
10682 };
10683
10684 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10685 // can be a solution, but the function failed to find it. We cannot treat it
10686 // as "no solution".
10687 if (!SO || !UO)
10688 return {std::nullopt, false};
10689
10690 // Check the smaller value first to see if it leaves the range.
10691 // At this point, both SO and UO must have values.
10692 std::optional<APInt> Min = MinOptional(SO, UO);
10693 if (LeavesRange(*Min))
10694 return { Min, true };
10695 std::optional<APInt> Max = Min == SO ? UO : SO;
10696 if (LeavesRange(*Max))
10697 return { Max, true };
10698
10699 // Solutions were found, but were eliminated, hence the "true".
10700 return {std::nullopt, true};
10701 };
10702
10703 std::tie(A, B, C, M, BitWidth) = *T;
10704 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10705 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10706 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10707 auto SL = SolveForBoundary(Lower);
10708 auto SU = SolveForBoundary(Upper);
10709 // If any of the solutions was unknown, no meaninigful conclusions can
10710 // be made.
10711 if (!SL.second || !SU.second)
10712 return std::nullopt;
10713
10714 // Claim: The correct solution is not some value between Min and Max.
10715 //
10716 // Justification: Assuming that Min and Max are different values, one of
10717 // them is when the first signed overflow happens, the other is when the
10718 // first unsigned overflow happens. Crossing the range boundary is only
10719 // possible via an overflow (treating 0 as a special case of it, modeling
10720 // an overflow as crossing k*2^W for some k).
10721 //
10722 // The interesting case here is when Min was eliminated as an invalid
10723 // solution, but Max was not. The argument is that if there was another
10724 // overflow between Min and Max, it would also have been eliminated if
10725 // it was considered.
10726 //
10727 // For a given boundary, it is possible to have two overflows of the same
10728 // type (signed/unsigned) without having the other type in between: this
10729 // can happen when the vertex of the parabola is between the iterations
10730 // corresponding to the overflows. This is only possible when the two
10731 // overflows cross k*2^W for the same k. In such case, if the second one
10732 // left the range (and was the first one to do so), the first overflow
10733 // would have to enter the range, which would mean that either we had left
10734 // the range before or that we started outside of it. Both of these cases
10735 // are contradictions.
10736 //
10737 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10738 // solution is not some value between the Max for this boundary and the
10739 // Min of the other boundary.
10740 //
10741 // Justification: Assume that we had such Max_A and Min_B corresponding
10742 // to range boundaries A and B and such that Max_A < Min_B. If there was
10743 // a solution between Max_A and Min_B, it would have to be caused by an
10744 // overflow corresponding to either A or B. It cannot correspond to B,
10745 // since Min_B is the first occurrence of such an overflow. If it
10746 // corresponded to A, it would have to be either a signed or an unsigned
10747 // overflow that is larger than both eliminated overflows for A. But
10748 // between the eliminated overflows and this overflow, the values would
10749 // cover the entire value space, thus crossing the other boundary, which
10750 // is a contradiction.
10751
10752 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10753}
10754
10755ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10756 const Loop *L,
10757 bool ControlsOnlyExit,
10758 bool AllowPredicates) {
10759
10760 // This is only used for loops with a "x != y" exit test. The exit condition
10761 // is now expressed as a single expression, V = x-y. So the exit test is
10762 // effectively V != 0. We know and take advantage of the fact that this
10763 // expression only being used in a comparison by zero context.
10764
10766 // If the value is a constant
10767 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10768 // If the value is already zero, the branch will execute zero times.
10769 if (C->getValue()->isZero()) return C;
10770 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10771 }
10772
10773 const SCEVAddRecExpr *AddRec =
10774 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10775
10776 if (!AddRec && AllowPredicates)
10777 // Try to make this an AddRec using runtime tests, in the first X
10778 // iterations of this loop, where X is the SCEV expression found by the
10779 // algorithm below.
10780 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10781
10782 if (!AddRec || AddRec->getLoop() != L)
10783 return getCouldNotCompute();
10784
10785 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10786 // the quadratic equation to solve it.
10787 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10788 // We can only use this value if the chrec ends up with an exact zero
10789 // value at this index. When solving for "X*X != 5", for example, we
10790 // should not accept a root of 2.
10791 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10792 const auto *R = cast<SCEVConstant>(getConstant(*S));
10793 return ExitLimit(R, R, R, false, Predicates);
10794 }
10795 return getCouldNotCompute();
10796 }
10797
10798 // Otherwise we can only handle this if it is affine.
10799 if (!AddRec->isAffine())
10800 return getCouldNotCompute();
10801
10802 // If this is an affine expression, the execution count of this branch is
10803 // the minimum unsigned root of the following equation:
10804 //
10805 // Start + Step*N = 0 (mod 2^BW)
10806 //
10807 // equivalent to:
10808 //
10809 // Step*N = -Start (mod 2^BW)
10810 //
10811 // where BW is the common bit width of Start and Step.
10812
10813 // Get the initial value for the loop.
10814 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10815 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10816
10817 if (!isLoopInvariant(Step, L))
10818 return getCouldNotCompute();
10819
10820 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10821 // Specialize step for this loop so we get context sensitive facts below.
10822 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10823
10824 // For positive steps (counting up until unsigned overflow):
10825 // N = -Start/Step (as unsigned)
10826 // For negative steps (counting down to zero):
10827 // N = Start/-Step
10828 // First compute the unsigned distance from zero in the direction of Step.
10829 bool CountDown = isKnownNegative(StepWLG);
10830 if (!CountDown && !isKnownNonNegative(StepWLG))
10831 return getCouldNotCompute();
10832
10833 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10834 // Handle unitary steps, which cannot wraparound.
10835 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10836 // N = Distance (as unsigned)
10837
10838 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10839 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10840 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10841
10842 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10843 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10844 // case, and see if we can improve the bound.
10845 //
10846 // Explicitly handling this here is necessary because getUnsignedRange
10847 // isn't context-sensitive; it doesn't know that we only care about the
10848 // range inside the loop.
10849 const SCEV *Zero = getZero(Distance->getType());
10850 const SCEV *One = getOne(Distance->getType());
10851 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10852 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10853 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10854 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10855 // Distance + 1; the range of Distance itself may be a wrapped set even
10856 // when the guards bound Distance + 1 tightly.
10857 APInt Max = APIntOps::umin(
10858 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10859 getUnsignedRangeMax(DistancePlusOne));
10860 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10861 }
10862 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10863 Predicates);
10864 }
10865
10866 // If the condition controls loop exit (the loop exits only if the expression
10867 // is true) and the addition is no-wrap we can use unsigned divide to
10868 // compute the backedge count. In this case, the step may not divide the
10869 // distance, but we don't care because if the condition is "missed" the loop
10870 // will have undefined behavior due to wrapping.
10871 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10872 loopHasNoAbnormalExits(AddRec->getLoop())) {
10873
10874 // If the stride is zero and the start is non-zero, the loop must be
10875 // infinite. In C++, most loops are finite by assumption, in which case the
10876 // step being zero implies UB must execute if the loop is entered.
10877 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10878 !isKnownNonZero(StepWLG))
10879 return getCouldNotCompute();
10880
10881 const SCEV *Exact =
10882 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10883 const SCEV *ConstantMax = getCouldNotCompute();
10884 if (Exact != getCouldNotCompute()) {
10885 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10886 ConstantMax =
10888 }
10889 const SCEV *SymbolicMax =
10890 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10891 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10892 }
10893
10894 // Solve the general equation.
10895 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10896 if (!StepC || StepC->getValue()->isZero())
10897 return getCouldNotCompute();
10898 const SCEV *E = SolveLinEquationWithOverflow(
10899 StepC->getAPInt(), getNegativeSCEV(Start),
10900 AllowPredicates ? &Predicates : nullptr, *this, L);
10901
10902 const SCEV *M = E;
10903 if (E != getCouldNotCompute()) {
10904 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10905 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10906 }
10907 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10908 return ExitLimit(E, M, S, false, Predicates);
10909}
10910
10911ScalarEvolution::ExitLimit
10912ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10913 // Loops that look like: while (X == 0) are very strange indeed. We don't
10914 // handle them yet except for the trivial case. This could be expanded in the
10915 // future as needed.
10916
10917 // If the value is a constant, check to see if it is known to be non-zero
10918 // already. If so, the backedge will execute zero times.
10919 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10920 if (!C->getValue()->isZero())
10921 return getZero(C->getType());
10922 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10923 }
10924
10925 // We could implement others, but I really doubt anyone writes loops like
10926 // this, and if they did, they would already be constant folded.
10927 return getCouldNotCompute();
10928}
10929
10930std::pair<const BasicBlock *, const BasicBlock *>
10931ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10932 const {
10933 // If the block has a unique predecessor, then there is no path from the
10934 // predecessor to the block that does not go through the direct edge
10935 // from the predecessor to the block.
10936 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10937 return {Pred, BB};
10938
10939 // A loop's header is defined to be a block that dominates the loop.
10940 // If the header has a unique predecessor outside the loop, it must be
10941 // a block that has exactly one successor that can reach the loop.
10942 if (const Loop *L = LI.getLoopFor(BB))
10943 return {L->getLoopPredecessor(), L->getHeader()};
10944
10945 return {nullptr, BB};
10946}
10947
10948/// SCEV structural equivalence is usually sufficient for testing whether two
10949/// expressions are equal, however for the purposes of looking for a condition
10950/// guarding a loop, it can be useful to be a little more general, since a
10951/// front-end may have replicated the controlling expression.
10952static bool HasSameValue(const SCEV *A, const SCEV *B) {
10953 // Quick check to see if they are the same SCEV.
10954 if (A == B) return true;
10955
10956 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10957 // Not all instructions that are "identical" compute the same value. For
10958 // instance, two distinct alloca instructions allocating the same type are
10959 // identical and do not read memory; but compute distinct values.
10960 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10961 };
10962
10963 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10964 // two different instructions with the same value. Check for this case.
10965 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10966 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10967 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10968 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10969 if (ComputesEqualValues(AI, BI))
10970 return true;
10971
10972 // Otherwise assume they may have a different value.
10973 return false;
10974}
10975
10976static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10977 const SCEV *Op0, *Op1;
10978 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10979 return false;
10980 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10981 LHS = Op1;
10982 return true;
10983 }
10984 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10985 LHS = Op0;
10986 return true;
10987 }
10988 return false;
10989}
10990
10992 SCEVUse &RHS, unsigned Depth) {
10993 bool Changed = false;
10994 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
10995 // '0 != 0'.
10996 auto TrivialCase = [&](bool TriviallyTrue) {
10998 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
10999 return true;
11000 };
11001 // If we hit the max recursion limit bail out.
11002 if (Depth >= 3)
11003 return false;
11004
11005 const SCEV *NewLHS, *NewRHS;
11006 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11007 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11008 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11009 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11010
11011 // (X * vscale) pred (Y * vscale) ==> X pred Y
11012 // when both multiples are NSW.
11013 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11014 // when both multiples are NUW.
11015 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11016 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11017 !ICmpInst::isSigned(Pred))) {
11018 LHS = NewLHS;
11019 RHS = NewRHS;
11020 Changed = true;
11021 }
11022 }
11023
11024 // Canonicalize a constant to the right side.
11025 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11026 // Check for both operands constant.
11027 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11028 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11029 return TrivialCase(false);
11030 return TrivialCase(true);
11031 }
11032 // Otherwise swap the operands to put the constant on the right.
11033 std::swap(LHS, RHS);
11035 Changed = true;
11036 }
11037
11038 // (K + A) pred (K + B) --> A pred B
11039 // For equality, no flags are needed.
11040 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11041 {
11042 const SCEVConstant *C = nullptr;
11043 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11044 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11045 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11046 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11047 if (ICmpInst::isEquality(Pred) ||
11048 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11049 RAdd->hasNoSignedWrap()) ||
11050 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11051 RAdd->hasNoUnsignedWrap())) {
11052 LHS = NewLHS;
11053 RHS = NewRHS;
11054 Changed = true;
11055 }
11056 }
11057 }
11058
11059 // (C * A) pred (C * B) --> A pred B
11060 // For equality predicates, both muls must be NUW or both must be NSW
11061 // (either suffices to make multiplication by C injective; C == 0 is
11062 // impossible because SCEV folds 0 * X to 0).
11063 // For signed ordering, C must be positive and both muls must be NSW.
11064 // For unsigned ordering, both muls must be NUW.
11065 {
11066 const SCEVConstant *C = nullptr;
11067 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11068 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11069 const auto *LMul = cast<SCEVMulExpr>(LHS);
11070 const auto *RMul = cast<SCEVMulExpr>(RHS);
11071 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11072 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11073 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11074 (ICmpInst::isSigned(Pred) && BothNSW &&
11075 C->getAPInt().isStrictlyPositive()) ||
11076 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11077 LHS = NewLHS;
11078 RHS = NewRHS;
11079 Changed = true;
11080 }
11081 }
11082 }
11083
11084 // If we're comparing an addrec with a value which is loop-invariant in the
11085 // addrec's loop, put the addrec on the left. Also make a dominance check,
11086 // as both operands could be addrecs loop-invariant in each other's loop.
11087 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11088 const Loop *L = AR->getLoop();
11089 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11090 std::swap(LHS, RHS);
11092 Changed = true;
11093 }
11094 }
11095
11096 // If there's a constant operand, canonicalize comparisons with boundary
11097 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11098 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11099 const APInt &RA = RC->getAPInt();
11100
11101 bool SimplifiedByConstantRange = false;
11102
11103 if (!ICmpInst::isEquality(Pred)) {
11105 if (ExactCR.isFullSet())
11106 return TrivialCase(true);
11107 if (ExactCR.isEmptySet())
11108 return TrivialCase(false);
11109
11110 APInt NewRHS;
11111 CmpInst::Predicate NewPred;
11112 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11113 ICmpInst::isEquality(NewPred)) {
11114 // We were able to convert an inequality to an equality.
11115 Pred = NewPred;
11116 RHS = getConstant(NewRHS);
11117 Changed = SimplifiedByConstantRange = true;
11118 }
11119 }
11120
11121 if (!SimplifiedByConstantRange) {
11122 switch (Pred) {
11123 default:
11124 break;
11125 case ICmpInst::ICMP_EQ:
11126 case ICmpInst::ICMP_NE:
11127 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11128 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11129 Changed = true;
11130 break;
11131
11132 // The "Should have been caught earlier!" messages refer to the fact
11133 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11134 // should have fired on the corresponding cases, and canonicalized the
11135 // check to trivial case.
11136
11137 case ICmpInst::ICMP_UGE:
11138 assert(!RA.isMinValue() && "Should have been caught earlier!");
11139 Pred = ICmpInst::ICMP_UGT;
11140 RHS = getConstant(RA - 1);
11141 Changed = true;
11142 break;
11143 case ICmpInst::ICMP_ULE:
11144 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11145 Pred = ICmpInst::ICMP_ULT;
11146 RHS = getConstant(RA + 1);
11147 Changed = true;
11148 break;
11149 case ICmpInst::ICMP_SGE:
11150 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11151 Pred = ICmpInst::ICMP_SGT;
11152 RHS = getConstant(RA - 1);
11153 Changed = true;
11154 break;
11155 case ICmpInst::ICMP_SLE:
11156 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11157 Pred = ICmpInst::ICMP_SLT;
11158 RHS = getConstant(RA + 1);
11159 Changed = true;
11160 break;
11161 }
11162 }
11163 }
11164
11165 // a /u b == 0 => a < b
11166 // a /u b != 0 => a >= b
11167 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11168 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11170 Changed = true;
11171 }
11172
11173 // Check for obvious equality.
11174 if (HasSameValue(LHS, RHS)) {
11175 if (ICmpInst::isTrueWhenEqual(Pred))
11176 return TrivialCase(true);
11178 return TrivialCase(false);
11179 }
11180
11181 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11182 // adding or subtracting 1 from one of the operands.
11183 switch (Pred) {
11184 case ICmpInst::ICMP_SLE:
11185 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11186 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11188 Pred = ICmpInst::ICMP_SLT;
11189 Changed = true;
11190 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11191 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11193 Pred = ICmpInst::ICMP_SLT;
11194 Changed = true;
11195 }
11196 break;
11197 case ICmpInst::ICMP_SGE:
11198 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11199 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11201 Pred = ICmpInst::ICMP_SGT;
11202 Changed = true;
11203 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11204 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11206 Pred = ICmpInst::ICMP_SGT;
11207 Changed = true;
11208 }
11209 break;
11210 case ICmpInst::ICMP_ULE:
11211 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11212 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11214 Pred = ICmpInst::ICMP_ULT;
11215 Changed = true;
11216 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11217 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11218 Pred = ICmpInst::ICMP_ULT;
11219 Changed = true;
11220 }
11221 break;
11222 case ICmpInst::ICMP_UGE:
11223 // If RHS is an op we can fold the -1, try that first.
11224 // Otherwise prefer LHS to preserve the nuw flag.
11225 if ((isa<SCEVConstant>(RHS) ||
11227 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11228 !getUnsignedRangeMin(RHS).isMinValue()) {
11229 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11230 Pred = ICmpInst::ICMP_UGT;
11231 Changed = true;
11232 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11233 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11235 Pred = ICmpInst::ICMP_UGT;
11236 Changed = true;
11237 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11238 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11239 Pred = ICmpInst::ICMP_UGT;
11240 Changed = true;
11241 }
11242 break;
11243 default:
11244 break;
11245 }
11246
11247 // TODO: More simplifications are possible here.
11248
11249 // Recursively simplify until we either hit a recursion limit or nothing
11250 // changes.
11251 if (Changed)
11252 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11253
11254 return Changed;
11255}
11256
11258 return getSignedRangeMax(S).isNegative();
11259}
11260
11264
11266 return !getSignedRangeMin(S).isNegative();
11267}
11268
11272
11274 // Query push down for cases where the unsigned range is
11275 // less than sufficient.
11276 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11277 return isKnownNonZero(SExt->getOperand(0));
11278 return getUnsignedRangeMin(S) != 0;
11279}
11280
11282 bool OrNegative) {
11283 auto NonRecursive = [OrNegative](const SCEV *S) {
11284 if (auto *C = dyn_cast<SCEVConstant>(S))
11285 return C->getAPInt().isPowerOf2() ||
11286 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11287
11288 // vscale is a power-of-two.
11289 return isa<SCEVVScale>(S);
11290 };
11291
11292 if (NonRecursive(S))
11293 return true;
11294
11295 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11296 if (!Mul)
11297 return false;
11298 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11299}
11300
11302 const SCEV *S, uint64_t M,
11304 if (M == 0)
11305 return false;
11306 if (M == 1)
11307 return true;
11308
11309 // For a constant, check that "S % M == 0".
11310 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11311 APInt C = Cst->getAPInt();
11312 return C.urem(M) == 0;
11313 }
11314
11315 // Basic tests have failed.
11316 // Check "S % M == 0" at compile time and record runtime Assumptions.
11317 auto *STy = dyn_cast<IntegerType>(S->getType());
11318 const SCEV *SmodM =
11319 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11320 const SCEV *Zero = getZero(STy);
11321
11322 // Check whether "S % M == 0" is known at compile time.
11323 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11324 return true;
11325
11326 // Check whether "S % M != 0" is known at compile time.
11327 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11328 return false;
11329
11330 if (!Predicates)
11331 return false;
11332
11333 // Look through Add and AddRec expressions with nuw to improve the
11334 // precision of added predicates. S is a multiple of M if S starts with a
11335 // multiple of M and at every iteration step S only adds multiples of M.
11338 all_of(S->operands(),
11339 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11340 return true;
11341
11342 // Similarly, look through Mul with nuw, where any operand being a
11343 // known-multiple is sufficient.
11344 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11345 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11346 return isKnownMultipleOf(Op, M, Predicates);
11347 }))
11348 return true;
11349
11350 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11351 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11352 return isKnownMultipleOf(Op, M, Predicates);
11353 }))
11354 return true;
11355
11357
11358 // Detect redundant predicates.
11359 for (auto *A : *Predicates)
11360 if (A->implies(P, *this))
11361 return true;
11362
11363 // Only record non-redundant predicates.
11364 Predicates->push_back(P);
11365 return true;
11366}
11367
11369 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11371}
11372
11373std::pair<const SCEV *, const SCEV *>
11375 // Compute SCEV on entry of loop L.
11376 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11377 if (Start == getCouldNotCompute())
11378 return { Start, Start };
11379 // Compute post increment SCEV for loop L.
11380 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11381 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11382 return { Start, PostInc };
11383}
11384
11386 SCEVUse RHS) {
11387 // First collect all loops.
11389 getUsedLoops(LHS, LoopsUsed);
11390 getUsedLoops(RHS, LoopsUsed);
11391
11392 if (LoopsUsed.empty())
11393 return false;
11394
11395 // Domination relationship must be a linear order on collected loops.
11396#ifndef NDEBUG
11397 for (const auto *L1 : LoopsUsed)
11398 for (const auto *L2 : LoopsUsed)
11399 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11400 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11401 "Domination relationship is not a linear order");
11402#endif
11403
11404 const Loop *MDL =
11405 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11406 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11407 });
11408
11409 // Get init and post increment value for LHS.
11410 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11411 // if LHS contains unknown non-invariant SCEV then bail out.
11412 if (SplitLHS.first == getCouldNotCompute())
11413 return false;
11414 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11415 // Get init and post increment value for RHS.
11416 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11417 // if RHS contains unknown non-invariant SCEV then bail out.
11418 if (SplitRHS.first == getCouldNotCompute())
11419 return false;
11420 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11421 // It is possible that init SCEV contains an invariant load but it does
11422 // not dominate MDL and is not available at MDL loop entry, so we should
11423 // check it here.
11424 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11425 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11426 return false;
11427
11428 // It seems backedge guard check is faster than entry one so in some cases
11429 // it can speed up whole estimation by short circuit
11430 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11431 SplitRHS.second) &&
11432 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11433}
11434
11436 SCEVUse RHS) {
11437 // Canonicalize the inputs first.
11438 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11439
11440 return isKnownViaInduction(Pred, LHS, RHS) ||
11441 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11442 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11443}
11444
11446 const SCEV *LHS,
11447 const SCEV *RHS) {
11448 if (isKnownPredicate(Pred, LHS, RHS))
11449 return true;
11451 return false;
11452 return std::nullopt;
11453}
11454
11456 const SCEV *RHS,
11457 const Instruction *CtxI) {
11458 // TODO: Analyze guards and assumes from Context's block.
11459 return isKnownPredicate(Pred, LHS, RHS) ||
11460 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11461}
11462
11463std::optional<bool>
11465 const SCEV *RHS, const Instruction *CtxI) {
11466 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11467 if (KnownWithoutContext)
11468 return KnownWithoutContext;
11469
11470 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11471 return true;
11473 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11474 return false;
11475 return std::nullopt;
11476}
11477
11479 const SCEVAddRecExpr *LHS,
11480 const SCEV *RHS) {
11481 const Loop *L = LHS->getLoop();
11482 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11483 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11484}
11485
11486std::optional<ScalarEvolution::MonotonicPredicateType>
11488 ICmpInst::Predicate Pred) {
11489 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11490
11491#ifndef NDEBUG
11492 // Verify an invariant: inverting the predicate should turn a monotonically
11493 // increasing change to a monotonically decreasing one, and vice versa.
11494 if (Result) {
11495 auto ResultSwapped =
11496 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11497
11498 assert(*ResultSwapped != *Result &&
11499 "monotonicity should flip as we flip the predicate");
11500 }
11501#endif
11502
11503 return Result;
11504}
11505
11506std::optional<ScalarEvolution::MonotonicPredicateType>
11507ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11508 ICmpInst::Predicate Pred) {
11509 // A zero step value for LHS means the induction variable is essentially a
11510 // loop invariant value. We don't really depend on the predicate actually
11511 // flipping from false to true (for increasing predicates, and the other way
11512 // around for decreasing predicates), all we care about is that *if* the
11513 // predicate changes then it only changes from false to true.
11514 //
11515 // A zero step value in itself is not very useful, but there may be places
11516 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11517 // as general as possible.
11518
11519 // Only handle LE/LT/GE/GT predicates.
11520 if (!ICmpInst::isRelational(Pred))
11521 return std::nullopt;
11522
11523 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11524 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11525 "Should be greater or less!");
11526
11527 // Check that AR does not wrap.
11528 if (ICmpInst::isUnsigned(Pred)) {
11529 if (!LHS->hasNoUnsignedWrap())
11530 return std::nullopt;
11532 }
11533 assert(ICmpInst::isSigned(Pred) &&
11534 "Relational predicate is either signed or unsigned!");
11535 if (!LHS->hasNoSignedWrap())
11536 return std::nullopt;
11537
11538 const SCEV *Step = LHS->getStepRecurrence(*this);
11539
11540 if (isKnownNonNegative(Step))
11542
11543 if (isKnownNonPositive(Step))
11545
11546 return std::nullopt;
11547}
11548
11549std::optional<ScalarEvolution::LoopInvariantPredicate>
11551 const SCEV *RHS, const Loop *L,
11552 const Instruction *CtxI) {
11553 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11554 if (!isLoopInvariant(RHS, L)) {
11555 if (!isLoopInvariant(LHS, L))
11556 return std::nullopt;
11557
11558 std::swap(LHS, RHS);
11560 }
11561
11562 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11563 if (!ArLHS || ArLHS->getLoop() != L)
11564 return std::nullopt;
11565
11566 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11567 if (!MonotonicType)
11568 return std::nullopt;
11569 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11570 // true as the loop iterates, and the backedge is control dependent on
11571 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11572 //
11573 // * if the predicate was false in the first iteration then the predicate
11574 // is never evaluated again, since the loop exits without taking the
11575 // backedge.
11576 // * if the predicate was true in the first iteration then it will
11577 // continue to be true for all future iterations since it is
11578 // monotonically increasing.
11579 //
11580 // For both the above possibilities, we can replace the loop varying
11581 // predicate with its value on the first iteration of the loop (which is
11582 // loop invariant).
11583 //
11584 // A similar reasoning applies for a monotonically decreasing predicate, by
11585 // replacing true with false and false with true in the above two bullets.
11587 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11588
11589 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11591 RHS);
11592
11593 if (!CtxI)
11594 return std::nullopt;
11595 // Try to prove via context.
11596 // TODO: Support other cases.
11597 switch (Pred) {
11598 default:
11599 break;
11600 case ICmpInst::ICMP_ULE:
11601 case ICmpInst::ICMP_ULT: {
11602 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11603 // Given preconditions
11604 // (1) ArLHS does not cross the border of positive and negative parts of
11605 // range because of:
11606 // - Positive step; (TODO: lift this limitation)
11607 // - nuw - does not cross zero boundary;
11608 // - nsw - does not cross SINT_MAX boundary;
11609 // (2) ArLHS <s RHS
11610 // (3) RHS >=s 0
11611 // we can replace the loop variant ArLHS <u RHS condition with loop
11612 // invariant Start(ArLHS) <u RHS.
11613 //
11614 // Because of (1) there are two options:
11615 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11616 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11617 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11618 // Because of (2) ArLHS <u RHS is trivially true.
11619 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11620 // We can strengthen this to Start(ArLHS) <u RHS.
11621 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11622 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11623 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11624 isKnownNonNegative(RHS) &&
11625 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11627 RHS);
11628 }
11629 }
11630
11631 return std::nullopt;
11632}
11633
11634std::optional<ScalarEvolution::LoopInvariantPredicate>
11636 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11637 const Instruction *CtxI, const SCEV *MaxIter) {
11639 Pred, LHS, RHS, L, CtxI, MaxIter))
11640 return LIP;
11641 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11642 // Number of iterations expressed as UMIN isn't always great for expressing
11643 // the value on the last iteration. If the straightforward approach didn't
11644 // work, try the following trick: if the a predicate is invariant for X, it
11645 // is also invariant for umin(X, ...). So try to find something that works
11646 // among subexpressions of MaxIter expressed as umin.
11647 for (SCEVUse Op : UMin->operands())
11649 Pred, LHS, RHS, L, CtxI, Op))
11650 return LIP;
11651 return std::nullopt;
11652}
11653
11654std::optional<ScalarEvolution::LoopInvariantPredicate>
11656 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11657 const Instruction *CtxI, const SCEV *MaxIter) {
11658 // Try to prove the following set of facts:
11659 // - The predicate is monotonic in the iteration space.
11660 // - If the check does not fail on the 1st iteration:
11661 // - No overflow will happen during first MaxIter iterations;
11662 // - It will not fail on the MaxIter'th iteration.
11663 // If the check does fail on the 1st iteration, we leave the loop and no
11664 // other checks matter.
11665
11666 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11667 if (!isLoopInvariant(RHS, L)) {
11668 if (!isLoopInvariant(LHS, L))
11669 return std::nullopt;
11670
11671 std::swap(LHS, RHS);
11673 }
11674
11675 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11676 if (!AR || AR->getLoop() != L)
11677 return std::nullopt;
11678
11679 // Even if both are valid, we need to consistently chose the unsigned or the
11680 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11681 // predicate.
11682 Pred = Pred.dropSameSign();
11683
11684 // The predicate must be relational (i.e. <, <=, >=, >).
11685 if (!ICmpInst::isRelational(Pred))
11686 return std::nullopt;
11687
11688 // TODO: Support steps other than +/- 1.
11689 const SCEV *Step = AR->getStepRecurrence(*this);
11690 auto *One = getOne(Step->getType());
11691 auto *MinusOne = getNegativeSCEV(One);
11692 if (Step != One && Step != MinusOne)
11693 return std::nullopt;
11694
11695 // Type mismatch here means that MaxIter is potentially larger than max
11696 // unsigned value in start type, which mean we cannot prove no wrap for the
11697 // indvar.
11698 if (AR->getType() != MaxIter->getType())
11699 return std::nullopt;
11700
11701 // Value of IV on suggested last iteration.
11702 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11703 // Does it still meet the requirement?
11704 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11705 return std::nullopt;
11706 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11707 // not exceed max unsigned value of this type), this effectively proves
11708 // that there is no wrap during the iteration. To prove that there is no
11709 // signed/unsigned wrap, we need to check that
11710 // Start <= Last for step = 1 or Start >= Last for step = -1.
11711 ICmpInst::Predicate NoOverflowPred =
11713 if (Step == MinusOne)
11714 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11715 const SCEV *Start = AR->getStart();
11716 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11717 return std::nullopt;
11718
11719 // Everything is fine.
11720 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11721}
11722
11723bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11724 SCEVUse LHS,
11725 SCEVUse RHS) {
11726 if (HasSameValue(LHS, RHS))
11727 return ICmpInst::isTrueWhenEqual(Pred);
11728
11729 auto CheckRange = [&](bool IsSigned) {
11730 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11731 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11732 return RangeLHS.icmp(Pred, RangeRHS);
11733 };
11734
11735 // The check at the top of the function catches the case where the values are
11736 // known to be equal.
11737 if (Pred == CmpInst::ICMP_EQ)
11738 return false;
11739
11740 if (Pred == CmpInst::ICMP_NE) {
11741 if (CheckRange(true) || CheckRange(false))
11742 return true;
11743 auto *Diff = getMinusSCEV(LHS, RHS);
11744 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11745 }
11746
11747 return CheckRange(CmpInst::isSigned(Pred));
11748}
11749
11750bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11752 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11753 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11754 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11755 // OutC1 and OutC2.
11756 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11757 APInt &OutC2, SCEVFlags ExpectedFlags) {
11758 SCEVUse XNonConstOp, XConstOp;
11759 SCEVUse YNonConstOp, YConstOp;
11760 SCEVFlags XFlagsPresent;
11761 SCEVFlags YFlagsPresent;
11762
11763 // Use nullptr for 0, to avoid creating a zero SCEV.
11764 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11765 XConstOp = nullptr;
11766 XNonConstOp = X;
11767 XFlagsPresent = ExpectedFlags;
11768 }
11769 if (XConstOp && !isa<SCEVConstant>(XConstOp))
11770 return false;
11771
11772 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11773 YConstOp = nullptr;
11774 YNonConstOp = Y;
11775 YFlagsPresent = ExpectedFlags;
11776 }
11777
11778 if (YNonConstOp != XNonConstOp)
11779 return false;
11780
11781 if (YConstOp && !isa<SCEVConstant>(YConstOp))
11782 return false;
11783
11784 // When matching ADDs with NUW flags (and unsigned predicates), only the
11785 // second ADD (with the larger constant) requires NUW.
11786 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11787 return false;
11788 if (ExpectedFlags != SCEV::FlagNUW &&
11789 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11790 return false;
11791 }
11792
11793 OutC1 = XConstOp ? cast<SCEVConstant>(XConstOp)->getAPInt()
11794 : APInt::getZero(getTypeSizeInBits(X->getType()));
11795 OutC2 = YConstOp ? cast<SCEVConstant>(YConstOp)->getAPInt()
11796 : APInt::getZero(getTypeSizeInBits(Y->getType()));
11797
11798 return true;
11799 };
11800
11801 APInt C1;
11802 APInt C2;
11803
11804 switch (Pred) {
11805 default:
11806 break;
11807
11808 case ICmpInst::ICMP_SGE:
11809 std::swap(LHS, RHS);
11810 [[fallthrough]];
11811 case ICmpInst::ICMP_SLE:
11812 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11813 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11814 return true;
11815
11816 break;
11817
11818 case ICmpInst::ICMP_SGT:
11819 std::swap(LHS, RHS);
11820 [[fallthrough]];
11821 case ICmpInst::ICMP_SLT:
11822 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11823 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11824 return true;
11825
11826 break;
11827
11828 case ICmpInst::ICMP_UGE:
11829 std::swap(LHS, RHS);
11830 [[fallthrough]];
11831 case ICmpInst::ICMP_ULE:
11832 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11833 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11834 return true;
11835
11836 break;
11837
11838 case ICmpInst::ICMP_UGT:
11839 std::swap(LHS, RHS);
11840 [[fallthrough]];
11841 case ICmpInst::ICMP_ULT:
11842 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11843 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11844 return true;
11845 break;
11846 }
11847
11848 return false;
11849}
11850
11851bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11853 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11854 return false;
11855
11856 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11857 // the stack can result in exponential time complexity.
11858 SaveAndRestore Restore(ProvingSplitPredicate, true);
11859
11860 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11861 //
11862 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11863 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11864 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11865 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11866 // use isKnownPredicate later if needed.
11867 return isKnownNonNegative(RHS) &&
11870}
11871
11872bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11873 const SCEV *LHS, const SCEV *RHS) {
11874 // No need to even try if we know the module has no guards.
11875 if (!HasGuards)
11876 return false;
11877
11878 return any_of(*BB, [&](const Instruction &I) {
11879 using namespace llvm::PatternMatch;
11880
11881 Value *Condition;
11883 m_Value(Condition))) &&
11884 isImpliedCond(Pred, LHS, RHS, Condition, false);
11885 });
11886}
11887
11888/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11889/// protected by a conditional between LHS and RHS. This is used to
11890/// to eliminate casts.
11892 CmpPredicate Pred,
11893 const SCEV *LHS,
11894 const SCEV *RHS) {
11895 // Interpret a null as meaning no loop, where there is obviously no guard
11896 // (interprocedural conditions notwithstanding). Do not bother about
11897 // unreachable loops.
11898 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11899 return true;
11900
11901 if (VerifyIR)
11902 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11903 "This cannot be done on broken IR!");
11904
11905
11906 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11907 return true;
11908
11909 BasicBlock *Latch = L->getLoopLatch();
11910 if (!Latch)
11911 return false;
11912
11913 CondBrInst *LoopContinuePredicate =
11915 if (LoopContinuePredicate &&
11916 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11917 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11918 return true;
11919
11920 // We don't want more than one activation of the following loops on the stack
11921 // -- that can lead to O(n!) time complexity.
11922 if (WalkingBEDominatingConds)
11923 return false;
11924
11925 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11926
11927 // See if we can exploit a trip count to prove the predicate.
11928 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11929 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11930 if (LatchBECount != getCouldNotCompute()) {
11931 // We know that Latch branches back to the loop header exactly
11932 // LatchBECount times. This means the backdege condition at Latch is
11933 // equivalent to "{0,+,1} u< LatchBECount".
11934 Type *Ty = LatchBECount->getType();
11935 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11936 const SCEV *LoopCounter =
11937 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11938 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11939 LatchBECount))
11940 return true;
11941 }
11942
11943 // Check conditions due to any @llvm.assume intrinsics.
11944 for (auto &AssumeVH : AC.assumptions()) {
11945 if (!AssumeVH)
11946 continue;
11947 auto *CI = cast<CallInst>(AssumeVH);
11948 if (!DT.dominates(CI, Latch->getTerminator()))
11949 continue;
11950
11951 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11952 return true;
11953 }
11954
11955 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11956 return true;
11957
11958 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11959 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11960 assert(DTN && "should reach the loop header before reaching the root!");
11961
11962 BasicBlock *BB = DTN->getBlock();
11963 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11964 return true;
11965
11966 BasicBlock *PBB = BB->getSinglePredecessor();
11967 if (!PBB)
11968 continue;
11969
11971 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11972 continue;
11973
11974 // If we have an edge `E` within the loop body that dominates the only
11975 // latch, the condition guarding `E` also guards the backedge. This
11976 // reasoning works only for loops with a single latch.
11977 // We're constructively (and conservatively) enumerating edges within the
11978 // loop body that dominate the latch. The dominator tree better agree
11979 // with us on this:
11980 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11981 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11982 BB != ContBr->getSuccessor(0)))
11983 return true;
11984 }
11985
11986 return false;
11987}
11988
11990 CmpPredicate Pred,
11991 const SCEV *LHS,
11992 const SCEV *RHS) {
11993 // Do not bother proving facts for unreachable code.
11994 if (!DT.isReachableFromEntry(BB))
11995 return true;
11996 if (VerifyIR)
11997 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
11998 "This cannot be done on broken IR!");
11999
12000 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12001 // the facts (a >= b && a != b) separately. A typical situation is when the
12002 // non-strict comparison is known from ranges and non-equality is known from
12003 // dominating predicates. If we are proving strict comparison, we always try
12004 // to prove non-equality and non-strict comparison separately.
12005 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12006 const bool ProvingStrictComparison =
12007 Pred != NonStrictPredicate.dropSameSign();
12008 bool ProvedNonStrictComparison = false;
12009 bool ProvedNonEquality = false;
12010
12011 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12012 if (!ProvedNonStrictComparison)
12013 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12014 if (!ProvedNonEquality)
12015 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12016 if (ProvedNonStrictComparison && ProvedNonEquality)
12017 return true;
12018 return false;
12019 };
12020
12021 if (ProvingStrictComparison) {
12022 auto ProofFn = [&](CmpPredicate P) {
12023 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12024 };
12025 if (SplitAndProve(ProofFn))
12026 return true;
12027 }
12028
12029 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12030 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12031 const Instruction *CtxI = &BB->front();
12032 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12033 return true;
12034 if (ProvingStrictComparison) {
12035 auto ProofFn = [&](CmpPredicate P) {
12036 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12037 };
12038 if (SplitAndProve(ProofFn))
12039 return true;
12040 }
12041 return false;
12042 };
12043
12044 // Starting at the block's predecessor, climb up the predecessor chain, as long
12045 // as there are predecessors that can be found that have unique successors
12046 // leading to the original block.
12047 const Loop *ContainingLoop = LI.getLoopFor(BB);
12048 const BasicBlock *PredBB;
12049 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12050 PredBB = ContainingLoop->getLoopPredecessor();
12051 else
12052 PredBB = BB->getSinglePredecessor();
12053 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12054 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12055 const CondBrInst *BlockEntryPredicate =
12056 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12057 if (!BlockEntryPredicate)
12058 continue;
12059
12060 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12061 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12062 return true;
12063 }
12064
12065 // Check conditions due to any @llvm.assume intrinsics.
12066 for (auto &AssumeVH : AC.assumptions()) {
12067 if (!AssumeVH)
12068 continue;
12069 auto *CI = cast<CallInst>(AssumeVH);
12070 if (!DT.dominates(CI, BB))
12071 continue;
12072
12073 if (ProveViaCond(CI->getArgOperand(0), false))
12074 return true;
12075 }
12076
12077 // Check conditions due to any @llvm.experimental.guard intrinsics.
12078 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12079 F.getParent(), Intrinsic::experimental_guard);
12080 if (GuardDecl)
12081 for (const auto *GU : GuardDecl->users())
12082 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12083 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12084 if (ProveViaCond(Guard->getArgOperand(0), false))
12085 return true;
12086 return false;
12087}
12088
12090 const SCEV *LHS,
12091 const SCEV *RHS) {
12092 // Interpret a null as meaning no loop, where there is obviously no guard
12093 // (interprocedural conditions notwithstanding).
12094 if (!L)
12095 return false;
12096
12097 // Both LHS and RHS must be available at loop entry.
12099 "LHS is not available at Loop Entry");
12101 "RHS is not available at Loop Entry");
12102
12103 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12104 return true;
12105
12106 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12107}
12108
12109bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12110 const SCEV *RHS,
12111 const Value *FoundCondValue, bool Inverse,
12112 const Instruction *CtxI) {
12113 // False conditions implies anything. Do not bother analyzing it further.
12114 if (FoundCondValue ==
12115 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12116 return true;
12117
12118 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12119 return false;
12120
12121 llvm::scope_exit ClearOnExit(
12122 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12123
12124 // Recursively handle And and Or conditions.
12125 const Value *Op0, *Op1;
12126 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12127 if (!Inverse)
12128 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12129 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12130 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12131 if (Inverse)
12132 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12133 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12134 }
12135
12136 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12137 if (!ICI) return false;
12138
12139 // Now that we found a conditional branch that dominates the loop or controls
12140 // the loop latch. Check to see if it is the comparison we are looking for.
12141 CmpPredicate FoundPred;
12142 if (Inverse)
12143 FoundPred = ICI->getInverseCmpPredicate();
12144 else
12145 FoundPred = ICI->getCmpPredicate();
12146
12147 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12148 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12149
12150 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12151}
12152
12153bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12154 const SCEV *RHS, CmpPredicate FoundPred,
12155 const SCEV *FoundLHS, const SCEV *FoundRHS,
12156 const Instruction *CtxI) {
12157 // Balance the types.
12158 if (getTypeSizeInBits(LHS->getType()) <
12159 getTypeSizeInBits(FoundLHS->getType())) {
12160 // For unsigned and equality predicates, try to prove that both found
12161 // operands fit into narrow unsigned range. If so, try to prove facts in
12162 // narrow types.
12163 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12164 !FoundRHS->getType()->isPointerTy()) {
12165 auto *NarrowType = LHS->getType();
12166 auto *WideType = FoundLHS->getType();
12167 auto BitWidth = getTypeSizeInBits(NarrowType);
12168 const SCEV *MaxValue = getZeroExtendExpr(
12170 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12171 MaxValue) &&
12172 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12173 MaxValue)) {
12174 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12175 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12176 // We cannot preserve samesign after truncation.
12177 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12178 TruncFoundLHS, TruncFoundRHS, CtxI))
12179 return true;
12180 }
12181 }
12182
12183 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12184 return false;
12185 if (CmpInst::isSigned(Pred)) {
12186 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12187 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12188 } else {
12189 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12190 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12191 }
12192 } else if (getTypeSizeInBits(LHS->getType()) >
12193 getTypeSizeInBits(FoundLHS->getType())) {
12194 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12195 return false;
12196 if (CmpInst::isSigned(FoundPred)) {
12197 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12198 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12199 } else {
12200 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12201 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12202 }
12203 }
12204 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12205 FoundRHS, CtxI);
12206}
12207
12208bool ScalarEvolution::isImpliedCondBalancedTypes(
12209 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12210 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12212 getTypeSizeInBits(FoundLHS->getType()) &&
12213 "Types should be balanced!");
12214 // Canonicalize the query to match the way instcombine will have
12215 // canonicalized the comparison.
12216 if (SimplifyICmpOperands(Pred, LHS, RHS))
12217 if (LHS == RHS)
12218 return CmpInst::isTrueWhenEqual(Pred);
12219 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12220 if (FoundLHS == FoundRHS)
12221 return CmpInst::isFalseWhenEqual(FoundPred);
12222
12223 // Check to see if we can make the LHS or RHS match.
12224 if (LHS == FoundRHS || RHS == FoundLHS) {
12225 if (isa<SCEVConstant>(RHS)) {
12226 std::swap(FoundLHS, FoundRHS);
12227 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12228 } else {
12229 std::swap(LHS, RHS);
12231 }
12232 }
12233
12234 // Check whether the found predicate is the same as the desired predicate.
12235 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12236 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12237
12238 // Check whether swapping the found predicate makes it the same as the
12239 // desired predicate.
12240 if (auto P = CmpPredicate::getMatching(
12241 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12242 // We can write the implication
12243 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12244 // using one of the following ways:
12245 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12246 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12247 // Both require swapping the operands of one condition. Don't do this if it
12248 // would break canonical constant/addrec ordering.
12250 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12251 LHS, FoundLHS, FoundRHS, CtxI);
12252 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12253 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12254
12255 return false;
12256 }
12257
12258 // Try the query as is and with its operands swapped. E.g. "x >s -1" is
12259 // tried as "-1 <s x" too, to match the found condition "x <u y".
12260 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12262 return CmpInst::isRelational(P2) &&
12264 };
12265 if (IsSignFlippedPredicate(Pred, FoundPred) &&
12266 isImpliedCondViaSignFlippedPred(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12267 return true;
12268 CmpPredicate SwappedPred = ICmpInst::getSwappedCmpPredicate(Pred);
12269 if (IsSignFlippedPredicate(SwappedPred, FoundPred) &&
12270 isImpliedCondViaSignFlippedPred(SwappedPred, RHS, LHS, FoundLHS, FoundRHS,
12271 CtxI))
12272 return true;
12273
12274 // Check if we can make progress by sharpening ranges.
12275 if (FoundPred == ICmpInst::ICMP_NE &&
12276 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12277
12278 const SCEVConstant *C = nullptr;
12279 const SCEV *V = nullptr;
12280
12281 if (isa<SCEVConstant>(FoundLHS)) {
12282 C = cast<SCEVConstant>(FoundLHS);
12283 V = FoundRHS;
12284 } else {
12285 C = cast<SCEVConstant>(FoundRHS);
12286 V = FoundLHS;
12287 }
12288
12289 // The guarding predicate tells us that C != V. If the known range
12290 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12291 // range we consider has to correspond to same signedness as the
12292 // predicate we're interested in folding.
12293
12294 APInt Min = ICmpInst::isSigned(Pred) ?
12296
12297 if (Min == C->getAPInt()) {
12298 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12299 // This is true even if (Min + 1) wraps around -- in case of
12300 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12301
12302 APInt SharperMin = Min + 1;
12303
12304 switch (Pred) {
12305 case ICmpInst::ICMP_SGE:
12306 case ICmpInst::ICMP_UGE:
12307 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12308 // RHS, we're done.
12309 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12310 CtxI))
12311 return true;
12312 [[fallthrough]];
12313
12314 case ICmpInst::ICMP_SGT:
12315 case ICmpInst::ICMP_UGT:
12316 // We know from the range information that (V `Pred` Min ||
12317 // V == Min). We know from the guarding condition that !(V
12318 // == Min). This gives us
12319 //
12320 // V `Pred` Min || V == Min && !(V == Min)
12321 // => V `Pred` Min
12322 //
12323 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12324
12325 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12326 return true;
12327 break;
12328
12329 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12330 case ICmpInst::ICMP_SLE:
12331 case ICmpInst::ICMP_ULE:
12332 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12333 LHS, V, getConstant(SharperMin), CtxI))
12334 return true;
12335 [[fallthrough]];
12336
12337 case ICmpInst::ICMP_SLT:
12338 case ICmpInst::ICMP_ULT:
12339 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12340 LHS, V, getConstant(Min), CtxI))
12341 return true;
12342 break;
12343
12344 default:
12345 // No change
12346 break;
12347 }
12348 }
12349 }
12350
12351 // Check whether the actual condition is beyond sufficient.
12352 if (FoundPred == ICmpInst::ICMP_EQ)
12353 if (ICmpInst::isTrueWhenEqual(Pred))
12354 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12355 return true;
12356 if (Pred == ICmpInst::ICMP_NE)
12357 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12358 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12359 return true;
12360
12361 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12362 return true;
12363
12364 // Otherwise assume the worst.
12365 return false;
12366}
12367
12368bool ScalarEvolution::isImpliedCondViaSignFlippedPred(
12369 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12370 const SCEV *FoundRHS, const Instruction *CtxI) {
12371 CmpPredicate FoundPred = ICmpInst::getFlippedSignednessPredicate(Pred);
12372 // Unsigned comparison is the same as signed comparison when both the
12373 // operands are non-negative or negative.
12374 if (haveSameSign(FoundLHS, FoundRHS) &&
12375 isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12376 return true;
12377 // Canonicalize both conditions to "le/lt".
12378 if (ICmpInst::isGT(Pred) || ICmpInst::isGE(Pred)) {
12380 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12381 std::swap(LHS, RHS);
12382 std::swap(FoundLHS, FoundRHS);
12383 }
12384 assert((ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred)) && "Must be!");
12385 assert((ICmpInst::isLT(FoundPred) || ICmpInst::isLE(FoundPred)) &&
12386 "Must be!");
12387 if (ICmpInst::isSigned(Pred)) {
12388 // Use implication:
12389 // x <u y && y <=u 2^(n-1) --> x >=s 0,
12390 // x <=u y && y <u 2^(n-1) --> x >=s 0,
12391 // where n is the bit width of x and y.
12392 // In both cases x <u 2^(n-1), so x >=s 0.
12393 // y <=u 2^(n-1) means y >=s 0 or y == INT_MIN.
12394 // If the implication's left part holds, try proving the query from x >=s
12395 // 0.
12396 Type *Ty = FoundLHS->getType();
12397 unsigned BitWidth = getTypeSizeInBits(Ty);
12398 const SCEV *SignedMin = getConstant(APInt::getSignedMinValue(BitWidth));
12399 CmpPredicate BoundPred =
12401 if (isKnownViaNonRecursiveReasoning(BoundPred, FoundRHS, SignedMin)) {
12402 // x >=s 0, written as 0 <=s x, or as -1 <s x to match a strict query.
12403 const SCEV *Bound = ICmpInst::isLE(Pred) ? getZero(Ty) : getMinusOne(Ty);
12404 if (isImpliedCondOperands(Pred, LHS, RHS, Bound, FoundLHS, CtxI))
12405 return true;
12406 }
12407 }
12409 // Use implication:
12410 // x <u y && y >=s 0 --> x <s y.
12411 // If we can prove the left part, the right part is also proven.
12412 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12413 return true;
12414 }
12416 // Use implication:
12417 // x <s y && y <s 0 --> x <u y.
12418 // If we can prove the left part, the right part is also proven.
12419 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12420 return true;
12421 }
12422 return false;
12423}
12424
12425bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12426 SCEVFlags &Flags) {
12427 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12428 return false;
12429
12430 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12431 return true;
12432}
12433
12434std::optional<APInt>
12436 // We avoid subtracting expressions here because this function is usually
12437 // fairly deep in the call stack (i.e. is called many times).
12438
12439 unsigned BW = getTypeSizeInBits(More->getType());
12440 APInt Diff(BW, 0);
12441 APInt DiffMul(BW, 1);
12442 // Try various simplifications to reduce the difference to a constant. Limit
12443 // the number of allowed simplifications to keep compile-time low.
12444 for (unsigned I = 0; I < 8; ++I) {
12445 if (More == Less)
12446 return Diff;
12447
12448 // Reduce addrecs with identical steps to their start value.
12450 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12451 const auto *MAR = cast<SCEVAddRecExpr>(More);
12452
12453 if (LAR->getLoop() != MAR->getLoop())
12454 return std::nullopt;
12455
12456 // We look at affine expressions only; not for correctness but to keep
12457 // getStepRecurrence cheap.
12458 if (!LAR->isAffine() || !MAR->isAffine())
12459 return std::nullopt;
12460
12461 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12462 return std::nullopt;
12463
12464 Less = LAR->getStart();
12465 More = MAR->getStart();
12466 continue;
12467 }
12468
12469 // Try to match a common constant multiply.
12470 auto MatchConstMul =
12471 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12472 const APInt *C;
12473 const SCEV *Op;
12474 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12475 return {{Op, *C}};
12476 return std::nullopt;
12477 };
12478 if (auto MatchedMore = MatchConstMul(More)) {
12479 if (auto MatchedLess = MatchConstMul(Less)) {
12480 if (MatchedMore->second == MatchedLess->second) {
12481 More = MatchedMore->first;
12482 Less = MatchedLess->first;
12483 DiffMul *= MatchedMore->second;
12484 continue;
12485 }
12486 }
12487 }
12488
12489 // Try to cancel out common factors in two add expressions.
12491 auto Add = [&](const SCEV *S, int Mul) {
12492 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12493 if (Mul == 1) {
12494 Diff += C->getAPInt() * DiffMul;
12495 } else {
12496 assert(Mul == -1);
12497 Diff -= C->getAPInt() * DiffMul;
12498 }
12499 } else
12500 Multiplicity[S] += Mul;
12501 };
12502 auto Decompose = [&](const SCEV *S, int Mul) {
12503 if (isa<SCEVAddExpr>(S)) {
12504 for (const SCEV *Op : S->operands())
12505 Add(Op, Mul);
12506 } else
12507 Add(S, Mul);
12508 };
12509 Decompose(More, 1);
12510 Decompose(Less, -1);
12511
12512 // Check whether all the non-constants cancel out, or reduce to new
12513 // More/Less values.
12514 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12515 for (const auto &[S, Mul] : Multiplicity) {
12516 if (Mul == 0)
12517 continue;
12518 if (Mul == 1) {
12519 if (NewMore)
12520 return std::nullopt;
12521 NewMore = S;
12522 } else if (Mul == -1) {
12523 if (NewLess)
12524 return std::nullopt;
12525 NewLess = S;
12526 } else
12527 return std::nullopt;
12528 }
12529
12530 // Values stayed the same, no point in trying further.
12531 if (NewMore == More || NewLess == Less)
12532 return std::nullopt;
12533
12534 More = NewMore;
12535 Less = NewLess;
12536
12537 // Reduced to constant.
12538 if (!More && !Less)
12539 return Diff;
12540
12541 // Left with variable on only one side, bail out.
12542 if (!More || !Less)
12543 return std::nullopt;
12544 }
12545
12546 // Did not reduce to constant.
12547 return std::nullopt;
12548}
12549
12550bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12551 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12552 const SCEV *FoundRHS, const Instruction *CtxI) {
12553 // Try to recognize the following pattern:
12554 //
12555 // FoundRHS = ...
12556 // ...
12557 // loop:
12558 // FoundLHS = {Start,+,W}
12559 // context_bb: // Basic block from the same loop
12560 // known(Pred, FoundLHS, FoundRHS)
12561 //
12562 // If some predicate is known in the context of a loop, it is also known on
12563 // each iteration of this loop, including the first iteration. Therefore, in
12564 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12565 // prove the original pred using this fact.
12566 if (!CtxI)
12567 return false;
12568 const BasicBlock *ContextBB = CtxI->getParent();
12569 // Make sure AR varies in the context block.
12570 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12571 const Loop *L = AR->getLoop();
12572 const auto *Latch = L->getLoopLatch();
12573 // Make sure that context belongs to the loop and executes on 1st iteration
12574 // (if it ever executes at all).
12575 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12576 return false;
12577 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12578 return false;
12579 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12580 }
12581
12582 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12583 const Loop *L = AR->getLoop();
12584 const auto *Latch = L->getLoopLatch();
12585 // Make sure that context belongs to the loop and executes on 1st iteration
12586 // (if it ever executes at all).
12587 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12588 return false;
12589 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12590 return false;
12591 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12592 }
12593
12594 return false;
12595}
12596
12597bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12598 const SCEV *LHS,
12599 const SCEV *RHS,
12600 const SCEV *FoundLHS,
12601 const SCEV *FoundRHS) {
12602 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12603 return false;
12604
12605 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12606 if (!AddRecLHS)
12607 return false;
12608
12609 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12610 if (!AddRecFoundLHS)
12611 return false;
12612
12613 // We'd like to let SCEV reason about control dependencies, so we constrain
12614 // both the inequalities to be about add recurrences on the same loop. This
12615 // way we can use isLoopEntryGuardedByCond later.
12616
12617 const Loop *L = AddRecFoundLHS->getLoop();
12618 if (L != AddRecLHS->getLoop())
12619 return false;
12620
12621 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12622 //
12623 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12624 // ... (2)
12625 //
12626 // Informal proof for (2), assuming (1) [*]:
12627 //
12628 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12629 //
12630 // Then
12631 //
12632 // FoundLHS s< FoundRHS s< INT_MIN - C
12633 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12634 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12635 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12636 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12637 // <=> FoundLHS + C s< FoundRHS + C
12638 //
12639 // [*]: (1) can be proved by ruling out overflow.
12640 //
12641 // [**]: This can be proved by analyzing all the four possibilities:
12642 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12643 // (A s>= 0, B s>= 0).
12644 //
12645 // Note:
12646 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12647 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12648 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12649 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12650 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12651 // C)".
12652
12653 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12654 if (!LDiff)
12655 return false;
12656 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12657 if (!RDiff || *LDiff != *RDiff)
12658 return false;
12659
12660 if (LDiff->isMinValue())
12661 return true;
12662
12663 APInt FoundRHSLimit;
12664
12665 if (Pred == CmpInst::ICMP_ULT) {
12666 FoundRHSLimit = -(*RDiff);
12667 } else {
12668 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12669 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12670 }
12671
12672 // Try to prove (1) or (2), as needed.
12673 return isAvailableAtLoopEntry(FoundRHS, L) &&
12674 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12675 getConstant(FoundRHSLimit));
12676}
12677
12678bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12679 const SCEV *RHS, const SCEV *FoundLHS,
12680 const SCEV *FoundRHS, unsigned Depth) {
12681 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12682
12683 llvm::scope_exit ClearOnExit([&]() {
12684 if (LPhi) {
12685 bool Erased = PendingMerges.erase(LPhi);
12686 assert(Erased && "Failed to erase LPhi!");
12687 (void)Erased;
12688 }
12689 if (RPhi) {
12690 bool Erased = PendingMerges.erase(RPhi);
12691 assert(Erased && "Failed to erase RPhi!");
12692 (void)Erased;
12693 }
12694 });
12695
12696 // Find respective Phis and check that they are not being pending.
12697 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12698 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12699 if (!PendingMerges.insert(Phi).second)
12700 return false;
12701 LPhi = Phi;
12702 }
12703 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12704 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12705 // If we detect a loop of Phi nodes being processed by this method, for
12706 // example:
12707 //
12708 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12709 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12710 //
12711 // we don't want to deal with a case that complex, so return conservative
12712 // answer false.
12713 if (!PendingMerges.insert(Phi).second)
12714 return false;
12715 RPhi = Phi;
12716 }
12717
12718 // If none of LHS, RHS is a Phi, nothing to do here.
12719 if (!LPhi && !RPhi)
12720 return false;
12721
12722 // If there is a SCEVUnknown Phi we are interested in, make it left.
12723 if (!LPhi) {
12724 std::swap(LHS, RHS);
12725 std::swap(FoundLHS, FoundRHS);
12726 std::swap(LPhi, RPhi);
12728 }
12729
12730 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12731 const BasicBlock *LBB = LPhi->getParent();
12732 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12733
12734 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12735 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12736 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12737 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12738 };
12739
12740 if (RPhi && RPhi->getParent() == LBB) {
12741 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12742 // If we compare two Phis from the same block, and for each entry block
12743 // the predicate is true for incoming values from this block, then the
12744 // predicate is also true for the Phis.
12745 for (const BasicBlock *IncBB : predecessors(LBB)) {
12746 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12747 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12748 if (!ProvedEasily(L, R))
12749 return false;
12750 }
12751 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12752 // Case two: RHS is also a Phi from the same basic block, and it is an
12753 // AddRec. It means that there is a loop which has both AddRec and Unknown
12754 // PHIs, for it we can compare incoming values of AddRec from above the loop
12755 // and latch with their respective incoming values of LPhi.
12756 // TODO: Generalize to handle loops with many inputs in a header.
12757 if (LPhi->getNumIncomingValues() != 2) return false;
12758
12759 auto *RLoop = RAR->getLoop();
12760 auto *Predecessor = RLoop->getLoopPredecessor();
12761 assert(Predecessor && "Loop with AddRec with no predecessor?");
12762 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12763 if (!ProvedEasily(L1, RAR->getStart()))
12764 return false;
12765 auto *Latch = RLoop->getLoopLatch();
12766 assert(Latch && "Loop with AddRec with no latch?");
12767 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12768 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12769 return false;
12770 } else {
12771 // In all other cases go over inputs of LHS and compare each of them to RHS,
12772 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12773 // At this point RHS is either a non-Phi, or it is a Phi from some block
12774 // different from LBB.
12775 for (const BasicBlock *IncBB : predecessors(LBB)) {
12776 // Check that RHS is available in this block.
12777 if (!dominates(RHS, IncBB))
12778 return false;
12779 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12780 // Make sure L does not refer to a value from a potentially previous
12781 // iteration of a loop.
12782 if (!properlyDominates(L, LBB))
12783 return false;
12784 // Addrecs are considered to properly dominate their loop, so are missed
12785 // by the previous check. Discard any values that have computable
12786 // evolution in this loop.
12787 if (auto *Loop = LI.getLoopFor(LBB))
12789 return false;
12790 if (!ProvedEasily(L, RHS))
12791 return false;
12792 }
12793 }
12794 return true;
12795}
12796
12797bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12798 const SCEV *LHS,
12799 const SCEV *RHS,
12800 const SCEV *FoundLHS,
12801 const SCEV *FoundRHS) {
12802 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12803 // sure that we are dealing with same LHS.
12804 if (RHS == FoundRHS) {
12805 std::swap(LHS, RHS);
12806 std::swap(FoundLHS, FoundRHS);
12808 }
12809 if (LHS != FoundLHS)
12810 return false;
12811
12812 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12813 if (!SUFoundRHS)
12814 return false;
12815
12816 Value *Shiftee, *ShiftValue;
12817
12818 using namespace PatternMatch;
12819 if (match(SUFoundRHS->getValue(),
12820 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12821 auto *ShifteeS = getSCEV(Shiftee);
12822 // Prove one of the following:
12823 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12824 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12825 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12826 // ---> LHS <s RHS
12827 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12828 // ---> LHS <=s RHS
12829 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12830 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12831 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12832 if (isKnownNonNegative(ShifteeS))
12833 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12834 }
12835
12836 return false;
12837}
12838
12839bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12840 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12841 const SCEV *FoundRHS) {
12842 // Only valid for equality predicates: (A == B) implies (C == D) when
12843 // the SCEV difference A - B equals C - D (they check the same
12844 // underlying relationship at every iteration).
12845 if (!ICmpInst::isEquality(Pred))
12846 return false;
12847
12848 // Restrict to cases involving loop recurrences - that's where this
12849 // pattern arises (correlated IV comparisons). This avoids calling
12850 // getMinusSCEV on arbitrary non-loop expressions.
12852 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12853 return false;
12854
12855 // AddRecs from different loops can never produce matching differences.
12856 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12857 if (!QueryAddRec)
12858 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12859 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12860 if (!FoundAddRec)
12861 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12862 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12863 return false;
12864
12865 // If the strides differ, the differences can never match.
12866 if (QueryAddRec->getStepRecurrence(*this) !=
12867 FoundAddRec->getStepRecurrence(*this))
12868 return false;
12869
12870 // Compute differences. For pointer-typed operands sharing the same base,
12871 // getMinusSCEV strips the common base and returns an integer SCEV.
12872 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12873 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12874 if (isa<SCEVCouldNotCompute>(FoundDiff))
12875 return false;
12876
12877 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12878 if (isa<SCEVCouldNotCompute>(Diff))
12879 return false;
12880
12881 return Diff == FoundDiff;
12882}
12883
12884bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12885 const SCEV *RHS,
12886 const SCEV *FoundLHS,
12887 const SCEV *FoundRHS,
12888 const Instruction *CtxI) {
12889 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12890 FoundRHS) ||
12891 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12892 FoundRHS) ||
12893 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12894 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12895 CtxI) ||
12896 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12897 FoundRHS) ||
12898 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12899}
12900
12901/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12902template <typename MinMaxExprType>
12903static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12904 const SCEV *Candidate) {
12905 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12906 if (!MinMaxExpr)
12907 return false;
12908
12909 return is_contained(MinMaxExpr->operands(), Candidate);
12910}
12911
12913 CmpPredicate Pred, const SCEV *LHS,
12914 const SCEV *RHS) {
12915 // If both sides are affine addrecs for the same loop, with equal
12916 // steps, and we know the recurrences don't wrap, then we only
12917 // need to check the predicate on the starting values.
12918
12919 if (!ICmpInst::isRelational(Pred))
12920 return false;
12921
12922 const SCEV *LStart, *RStart, *Step;
12923 const Loop *L;
12924 if (!match(LHS,
12925 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12927 m_SpecificLoop(L))))
12928 return false;
12932 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12933 return false;
12934
12935 return SE.isKnownPredicate(Pred, LStart, RStart);
12936}
12937
12938/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12939/// go below its own start value?
12941 CmpPredicate Pred,
12942 const SCEV *LHS,
12943 const SCEV *RHS) {
12944 // Normalize to (AddRec Pred Start).
12947 std::swap(LHS, RHS);
12948 }
12949
12950 // The recurrence is equal to Start in the first iteration, so only the
12951 // non-strict predicate holds.
12952 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12953 return false;
12954
12955 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12956 if (!AR || AR->getStart() != RHS)
12957 return false;
12958
12959 return SE.getMonotonicPredicateType(AR, Pred) ==
12961}
12962
12963/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12964/// expression?
12966 const SCEV *LHS, const SCEV *RHS) {
12967 switch (Pred) {
12968 default:
12969 return false;
12970
12971 case ICmpInst::ICMP_SGE:
12972 std::swap(LHS, RHS);
12973 [[fallthrough]];
12974 case ICmpInst::ICMP_SLE:
12975 return
12976 // min(A, ...) <= A
12978 // A <= max(A, ...)
12980
12981 case ICmpInst::ICMP_UGE:
12982 std::swap(LHS, RHS);
12983 [[fallthrough]];
12984 case ICmpInst::ICMP_ULE:
12985 return
12986 // min(A, ...) <= A
12987 // FIXME: what about umin_seq?
12989 // A <= max(A, ...)
12991
12992 case ICmpInst::ICMP_UGT:
12993 std::swap(LHS, RHS);
12994 [[fallthrough]];
12995 case ICmpInst::ICMP_ULT:
12996 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
12997 // umin(Ops) u< RHS.
12998 //
12999 // Use computeConstantDifference instead of the more powerful
13000 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
13001 // is called from isKnownViaNonRecursiveReasoning, so recursing into
13002 // the full predicate prover would be expensive.
13003 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
13004 for (SCEVUse Op : Min->operands()) {
13005 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13006 // When Op and RHS share a common base differing by a
13007 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13008 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13009 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13010 return true;
13011 }
13012 }
13013 return false;
13014 }
13015
13016 llvm_unreachable("covered switch fell through?!");
13017}
13018
13019bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13020 const SCEV *RHS,
13021 const SCEV *FoundLHS,
13022 const SCEV *FoundRHS,
13023 unsigned Depth) {
13026 "LHS and RHS have different sizes?");
13027 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13028 getTypeSizeInBits(FoundRHS->getType()) &&
13029 "FoundLHS and FoundRHS have different sizes?");
13030 // We want to avoid hurting the compile time with analysis of too big trees.
13032 return false;
13033
13034 // We only want to work with GT comparison so far.
13035 if (ICmpInst::isLT(Pred)) {
13037 std::swap(LHS, RHS);
13038 std::swap(FoundLHS, FoundRHS);
13039 }
13040
13042
13043 // For unsigned, try to reduce it to corresponding signed comparison.
13044 if (P == ICmpInst::ICMP_UGT)
13045 // We can replace unsigned predicate with its signed counterpart if all
13046 // involved values are non-negative.
13047 // TODO: We could have better support for unsigned.
13048 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13049 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13050 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13051 // use this fact to prove that LHS and RHS are non-negative.
13052 const SCEV *MinusOne = getMinusOne(LHS->getType());
13053 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13054 FoundRHS) &&
13055 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13056 FoundRHS))
13058 }
13059
13060 if (P != ICmpInst::ICMP_SGT)
13061 return false;
13062
13063 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13064 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13065 return Ext->getOperand();
13066 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13067 // the constant in some cases.
13068 return S;
13069 };
13070
13071 // Acquire values from extensions.
13072 auto *OrigLHS = LHS;
13073 auto *OrigFoundLHS = FoundLHS;
13074 LHS = GetOpFromSExt(LHS);
13075 FoundLHS = GetOpFromSExt(FoundLHS);
13076
13077 // Is the SGT predicate can be proved trivially or using the found context.
13078 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13079 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13080 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13081 FoundRHS, Depth + 1);
13082 };
13083
13084 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13085 // We want to avoid creation of any new non-constant SCEV. Since we are
13086 // going to compare the operands to RHS, we should be certain that we don't
13087 // need any size extensions for this. So let's decline all cases when the
13088 // sizes of types of LHS and RHS do not match.
13089 // TODO: Maybe try to get RHS from sext to catch more cases?
13091 return false;
13092
13093 // Should not overflow.
13094 if (!LHSAddExpr->hasNoSignedWrap())
13095 return false;
13096
13097 SCEVUse LL = LHSAddExpr->getOperand(0);
13098 SCEVUse LR = LHSAddExpr->getOperand(1);
13099 auto *MinusOne = getMinusOne(RHS->getType());
13100
13101 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13102 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13103 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13104 };
13105 // Try to prove the following rule:
13106 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13107 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13108 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13109 return true;
13110 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13111 Value *LL, *LR;
13112 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13113
13114 using namespace llvm::PatternMatch;
13115
13116 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13117 // Rules for division.
13118 // We are going to perform some comparisons with Denominator and its
13119 // derivative expressions. In general case, creating a SCEV for it may
13120 // lead to a complex analysis of the entire graph, and in particular it
13121 // can request trip count recalculation for the same loop. This would
13122 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13123 // this, we only want to create SCEVs that are constants in this section.
13124 // So we bail if Denominator is not a constant.
13125 if (!isa<ConstantInt>(LR))
13126 return false;
13127
13128 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13129
13130 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13131 // then a SCEV for the numerator already exists and matches with FoundLHS.
13132 auto *Numerator = getExistingSCEV(LL);
13133 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13134 return false;
13135
13136 // Make sure that the numerator matches with FoundLHS and the denominator
13137 // is positive.
13138 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13139 return false;
13140
13141 auto *DTy = Denominator->getType();
13142 auto *FRHSTy = FoundRHS->getType();
13143 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13144 // One of types is a pointer and another one is not. We cannot extend
13145 // them properly to a wider type, so let us just reject this case.
13146 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13147 // to avoid this check.
13148 return false;
13149
13150 // Given that:
13151 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13152 auto *WTy = getWiderType(DTy, FRHSTy);
13153 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13154 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13155
13156 // Try to prove the following rule:
13157 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13158 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13159 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13160 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13161 if (isKnownNonPositive(RHS) &&
13162 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13163 return true;
13164
13165 // Try to prove the following rule:
13166 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13167 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13168 // If we divide it by Denominator > 2, then:
13169 // 1. If FoundLHS is negative, then the result is 0.
13170 // 2. If FoundLHS is non-negative, then the result is non-negative.
13171 // Anyways, the result is non-negative.
13172 auto *MinusOne = getMinusOne(WTy);
13173 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13174 if (isKnownNegative(RHS) &&
13175 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13176 return true;
13177 }
13178 }
13179
13180 // If our expression contained SCEVUnknown Phis, and we split it down and now
13181 // need to prove something for them, try to prove the predicate for every
13182 // possible incoming values of those Phis.
13183 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13184 return true;
13185
13186 return false;
13187}
13188
13190 const SCEV *RHS) {
13191 // zext x u<= sext x, sext x s<= zext x
13192 const SCEV *Op;
13193 switch (Pred) {
13194 case ICmpInst::ICMP_SGE:
13195 std::swap(LHS, RHS);
13196 [[fallthrough]];
13197 case ICmpInst::ICMP_SLE: {
13198 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13199 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13201 }
13202 case ICmpInst::ICMP_UGE:
13203 std::swap(LHS, RHS);
13204 [[fallthrough]];
13205 case ICmpInst::ICMP_ULE: {
13206 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13207 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13209 }
13210 default:
13211 return false;
13212 };
13213 llvm_unreachable("unhandled case");
13214}
13215
13216bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13217 SCEVUse LHS,
13218 SCEVUse RHS) {
13219 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13220 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13221 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13222 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13224 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13225}
13226
13227bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13228 const SCEV *LHS,
13229 const SCEV *RHS,
13230 const SCEV *FoundLHS,
13231 const SCEV *FoundRHS) {
13232 switch (Pred) {
13233 default:
13234 llvm_unreachable("Unexpected CmpPredicate value!");
13235 case ICmpInst::ICMP_EQ:
13236 case ICmpInst::ICMP_NE:
13237 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13238 return true;
13239 break;
13240 case ICmpInst::ICMP_SLT:
13241 case ICmpInst::ICMP_SLE:
13242 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13243 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13244 return true;
13245 break;
13246 case ICmpInst::ICMP_SGT:
13247 case ICmpInst::ICMP_SGE:
13248 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13249 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13250 return true;
13251 break;
13252 case ICmpInst::ICMP_ULT:
13253 case ICmpInst::ICMP_ULE:
13254 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13255 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13256 return true;
13257 break;
13258 case ICmpInst::ICMP_UGT:
13259 case ICmpInst::ICMP_UGE:
13260 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13261 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13262 return true;
13263 break;
13264 }
13265
13266 // Maybe it can be proved via operations?
13267 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13268 return true;
13269
13270 return false;
13271}
13272
13273bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13274 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13275 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13276 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13277 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13278 // reduce the compile time impact of this optimization.
13279 return false;
13280
13281 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13282 if (!Addend)
13283 return false;
13284
13285 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13286
13287 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13288 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13289 ConstantRange FoundLHSRange =
13290 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13291
13292 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13293 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13294
13295 // We can also compute the range of values for `LHS` that satisfy the
13296 // consequent, "`LHS` `Pred` `RHS`":
13297 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13298 // The antecedent implies the consequent if every value of `LHS` that
13299 // satisfies the antecedent also satisfies the consequent.
13300 return LHSRange.icmp(Pred, ConstRHS);
13301}
13302
13303bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13304 bool IsSigned, bool Invert) {
13305 assert(isKnownPositive(Stride) && "Positive stride expected!");
13306
13307 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13308 const SCEV *One = getOne(Stride->getType());
13309
13310 if (IsSigned) {
13311 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13312 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13313 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13314
13315 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13316 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13317 }
13318
13319 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13320 APInt MaxValue = APInt::getMaxValue(BitWidth);
13321 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13322
13323 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13324 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13325}
13326
13328 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13329 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13330 // expression fixes the case of N=0.
13331 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13332 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13333 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13334}
13335
13336const SCEV *
13337ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13338 const SCEV *End, unsigned BitWidth,
13339 bool IsSigned, bool Invert) {
13340 // The logic in this function assumes we can represent a positive stride.
13341 // If we can't, the backedge-taken count must be zero.
13342 if (IsSigned && BitWidth == 1)
13343 return getZero(Stride->getType());
13344
13345 // This code below only been closely audited for negative strides in the
13346 // unsigned comparison case, it may be correct for signed comparison, but
13347 // that needs to be established.
13348 if (IsSigned && isKnownNegative(Stride))
13349 return getCouldNotCompute();
13350
13351 // Calculate the maximum backedge count based on the range of values
13352 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13353 // need inverting. Stride was already negated by the caller.
13354 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13355
13356 APInt MinStride =
13357 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13358
13359 // We assume either the stride is positive, or the backedge-taken count
13360 // is zero. So force StrideForMaxBECount to be at least one.
13361 APInt One(BitWidth, 1);
13362 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13363 : APIntOps::umax(One, MinStride);
13364
13365 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13366 : APInt::getMaxValue(BitWidth);
13367 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13368
13369 // Although End can be a MAX expression we estimate MaxEnd considering only
13370 // the case End = RHS of the loop termination condition. This is safe because
13371 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13372 // taken count.
13373 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13374 MaxEnd =
13375 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13376
13377 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13378 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13379 : APIntOps::umax(MaxEnd, MinStart);
13380
13381 APInt Delta = MaxEnd - MinStart;
13382
13383 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13384 // tighter bound after folding.
13385 const SCEV *DeltaExpr =
13386 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13387 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13388
13389 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13390}
13391
13393ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13394 const Loop *L, bool IsSigned, bool Invert,
13395 bool ControlsOnlyExit, bool AllowPredicates) {
13397
13398 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
13399
13400 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13401 if (Invert && !isLoopInvariant(RHS, L))
13402 return getCouldNotCompute();
13403
13405 bool PredicatedIV = false;
13406 // FIXME: Generalize the NUW inference below to decreasing IVs.
13407 if (!IV && !Invert) {
13408 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13409 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13410 if (AR && AR->getLoop() == L && AR->isAffine()) {
13411 auto canProveNUW = [&]() {
13412 // We can use the comparison to infer no-wrap flags only if it fully
13413 // controls the loop exit.
13414 if (!ControlsOnlyExit)
13415 return false;
13416
13417 if (!isLoopInvariant(RHS, L))
13418 return false;
13419
13420 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13421 // We need the sequence defined by AR to strictly increase in the
13422 // unsigned integer domain for the logic below to hold.
13423 return false;
13424
13425 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13426 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13427 // If RHS <=u Limit, then there must exist a value V in the sequence
13428 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13429 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13430 // overflow occurs. This limit also implies that a signed comparison
13431 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13432 // the high bits on both sides must be zero.
13433 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13434 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13435 Limit = Limit.zext(OuterBitWidth);
13436 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13437 };
13438 auto Flags = AR->getNoWrapFlags();
13439 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13440 Flags = setFlags(Flags, SCEV::FlagNUW);
13441
13442 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13443 if (AR->hasNoUnsignedWrap()) {
13444 // Emulate what getZeroExtendExpr would have done during construction
13445 // if we'd been able to infer the fact just above at that time.
13446 const SCEV *Step = AR->getStepRecurrence(*this);
13447 Type *Ty = ZExt->getType();
13448 const SCEV *S = getAddRecExpr(
13450 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13452 }
13453 }
13454 }
13455 }
13456
13457 if (!IV && AllowPredicates) {
13458 // Try to make this an AddRec using runtime tests, in the first X
13459 // iterations of this loop, where X is the SCEV expression found by the
13460 // algorithm below.
13461 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13462 PredicatedIV = true;
13463 }
13464
13465 // Avoid weird loops
13466 if (!IV || IV->getLoop() != L || !IV->isAffine())
13467 return getCouldNotCompute();
13468
13469 // A precondition of this method is that the condition being analyzed
13470 // reaches an exiting branch which dominates the latch. Given that, we can
13471 // assume that an increment which violates the nowrap specification and
13472 // produces poison must cause undefined behavior when the resulting poison
13473 // value is branched upon and thus we can conclude that the backedge is
13474 // taken no more often than would be required to produce that poison value.
13475 // Note that a well defined loop can exit on the iteration which violates
13476 // the nowrap specification if there is another exit (either explicit or
13477 // implicit/exceptional) which causes the loop to execute before the
13478 // exiting instruction we're analyzing would trigger UB.
13479 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13480 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13481 // Reverse the ordering for greater-than comparisons.
13483 if (Invert)
13485
13486 // The step of ~IV is the negated step of IV.
13487 const SCEV *Stride = IV->getStepRecurrence(*this);
13488 if (Invert)
13489 Stride = getNegativeSCEV(Stride);
13490 const SCEV *GuardedStride = Stride;
13491
13492 // Whether the IV may reach the maximum (or minimum if inverted) value
13493 // before the exit is taken.
13494 bool IVMayOverflow = true;
13495
13496 bool PositiveStride = isKnownPositive(Stride);
13497 // A dominating guard may prove the stride positive.
13498 if (!PositiveStride) {
13499 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13500 if (isKnownPositive(LoopGuardedStride)) {
13501 GuardedStride = LoopGuardedStride;
13502 PositiveStride = true;
13503 // Encode the context-sensitive stride > 0 fact into the expression
13504 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13505 }
13506 }
13507
13508 // Avoid negative or zero stride values.
13509 if (!PositiveStride) {
13510 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13511 if (Invert)
13512 return getCouldNotCompute();
13513
13514 // We can compute the correct backedge taken count for loops with unknown
13515 // strides if we can prove that the loop is not an infinite loop with side
13516 // effects. Here's the loop structure we are trying to handle -
13517 //
13518 // i = start
13519 // do {
13520 // A[i] = i;
13521 // i += s;
13522 // } while (i < end);
13523 //
13524 // The backedge taken count for such loops is evaluated as -
13525 // (max(end, start + stride) - start - 1) /u stride
13526 //
13527 // The additional preconditions that we need to check to prove correctness
13528 // of the above formula is as follows -
13529 //
13530 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13531 // NoWrap flag).
13532 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13533 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13534 // no side effects within the loop) or a predicate is added to ensure
13535 // stride is positive.
13536 // c) loop has a single static exit (with no abnormal exits)
13537 //
13538 // Precondition a) implies that if the stride is negative, this is a single
13539 // trip loop. The backedge taken count formula reduces to zero in this case.
13540 //
13541 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13542 // then a zero stride means the backedge can't be taken without executing
13543 // undefined behavior.
13544 //
13545 // The positive stride case is the same as isKnownPositive(Stride) returning
13546 // true (original behavior of the function).
13547 //
13548 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13549 return getCouldNotCompute();
13550
13551 if (!loopIsFiniteByAssumption(L)) {
13552 // If the loop may be infinite, add a predicate ensuring Stride is
13553 // positive, to guarantee forward progress.
13554 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13555 return getCouldNotCompute();
13556
13557 const SCEV *Zero = getZero(Stride->getType());
13558 const SCEVPredicate *P =
13560 Predicates.push_back(P);
13561 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13562 // so the result is unchanged. To prevent div by zero.
13563 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13564 } else if (!isKnownNonZero(Stride)) {
13565 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13566 // if it might eventually be greater than start and if so, on which
13567 // iteration. We can't even produce a useful upper bound.
13568 if (!isLoopInvariant(RHS, L))
13569 return getCouldNotCompute();
13570
13571 // We allow a potentially zero stride, but we need to divide by stride
13572 // below. Since the loop can't be infinite and this check must control
13573 // the sole exit, we can infer the exit must be taken on the first
13574 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13575 // we know the numerator in the divides below must be zero, so we can
13576 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13577 // and produce the right result.
13578 // FIXME: Handle the case where Stride is poison?
13579 auto wouldZeroStrideBeUB = [&]() {
13580 // Proof by contradiction. Suppose the stride were zero. If we can
13581 // prove that the backedge *is* taken on the first iteration, then since
13582 // we know this condition controls the sole exit, we must have an
13583 // infinite loop. We can't have a (well defined) infinite loop per
13584 // check just above.
13585 // Note: The (Start - Stride) term is used to get the start' term from
13586 // (start' + stride,+,stride). Remember that we only care about the
13587 // result of this expression when stride == 0 at runtime.
13588 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13589 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13590 };
13591 if (!wouldZeroStrideBeUB()) {
13592 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13593 }
13594 }
13595 } else {
13596 // Avoid proven overflow cases: this will ensure that the backedge taken
13597 // count will not generate any unsigned overflow.
13598 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert) &&
13599 canIVOverflowOnLT(applyLoopGuards(RHS, Guards),
13600 GuardedStride, IsSigned, Invert);
13601 if (IVMayOverflow && !NoWrap)
13602 return getCouldNotCompute();
13603 }
13604
13605 // On all paths just preceeding, we established the following invariant:
13606 // IV can be assumed not to overflow up to and including the exiting
13607 // iteration. We proved this in one of two ways:
13608 // 1) We can show overflow doesn't occur before the exiting iteration
13609 // 1a) canIVOverflowOnLT, and b) step of one
13610 // 2) We can show that if overflow occurs, the loop must execute UB
13611 // before any possible exit.
13612 // Note that we have not yet proved RHS invariant (in general).
13613
13614 const SCEV *Start = IV->getStart();
13615
13616 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13617 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13618 // Use integer-typed versions for actual computation; we can't subtract
13619 // pointers in general.
13620 const SCEV *OrigStart = Start;
13621 const SCEV *OrigRHS = RHS;
13622 if (Start->getType()->isPointerTy()) {
13623 Start = getPtrToAddrExpr(Start);
13624 if (isa<SCEVCouldNotCompute>(Start))
13625 return Start;
13626 }
13627 if (RHS->getType()->isPointerTy()) {
13630 return RHS;
13631 }
13632
13633 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13634 *BECountIfBackedgeTaken = getCouldNotCompute();
13635 if (!isLoopInvariant(RHS, L)) {
13636 assert(!Invert && "RHS must be loop-invariant for Invert");
13637 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13638 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13639 any(RHSAddRec->getNoWrapFlags())) {
13640 // The structure of loop we are trying to calculate backedge count of:
13641 //
13642 // left = left_start
13643 // right = right_start
13644 //
13645 // while(left < right){
13646 // ... do something here ...
13647 // left += s1; // stride of left is s1 (s1 > 0)
13648 // right += s2; // stride of right is s2 (s2 < 0)
13649 // }
13650 //
13651
13652 const SCEV *RHSStart = RHSAddRec->getStart();
13653 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13654
13655 // If Stride - RHSStride is positive and does not overflow, we can write
13656 // backedge count as ->
13657 // ceil((End - Start) /u (Stride - RHSStride))
13658 // Where, End = max(RHSStart, Start)
13659
13660 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13661 if (isKnownNegative(RHSStride) &&
13662 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13663 RHSStride)) {
13664
13665 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13666 if (isKnownPositive(Denominator)) {
13667 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13668 : getUMaxExpr(RHSStart, Start);
13669
13670 // We can do this because End >= Start, as End = max(RHSStart, Start)
13671 const SCEV *Delta = getMinusSCEV(End, Start);
13672
13673 BECount = getUDivCeilSCEV(Delta, Denominator);
13674 BECountIfBackedgeTaken =
13675 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13676 }
13677 }
13678 }
13679 } else {
13680 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13681 // describe the backedge count: if the backedge is taken at least once then
13682 // End is RHS, and if not End is Start so we get a backedge count of zero.
13683 // Inverted, End is min(RHS, Start).
13684 //
13685 // AddingStrideMinusOneMayOverflow has the following preconditions:
13686 //
13687 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13688 // 2. The index variable doesn't overflow.
13689 //
13690 // Therefore, we know N exists such that
13691 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13692 // doesn't overflow.
13693 //
13694 // Using this information, try to prove whether the addition in
13695 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13696 //
13697 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13698 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13699 // the (Stride - 1) addition below cannot overflow.
13700 const SCEV *One = getOne(Stride->getType());
13701 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13702 if (isKnownToBeAPowerOfTwo(Stride)) {
13703 // Suppose Stride is a power of two, and Start/End are unsigned
13704 // integers. Let UMAX be the largest representable unsigned
13705 // integer.
13706 //
13707 // By the preconditions of this function, we know
13708 // "(Start + Stride * N) >= End", and this doesn't overflow.
13709 // As a formula:
13710 //
13711 // End <= (Start + Stride * N) <= UMAX
13712 //
13713 // Subtracting Start from all the terms:
13714 //
13715 // End - Start <= Stride * N <= UMAX - Start
13716 //
13717 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13718 //
13719 // End - Start <= Stride * N <= UMAX
13720 //
13721 // Stride * N is a multiple of Stride. Therefore,
13722 //
13723 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13724 //
13725 // Since Stride is a power of two, UMAX + 1 is divisible by
13726 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13727 // write:
13728 //
13729 // End - Start <= Stride * N <= UMAX - Stride - 1
13730 //
13731 // Dropping the middle term:
13732 //
13733 // End - Start <= UMAX - Stride - 1
13734 //
13735 // Adding Stride - 1 to both sides:
13736 //
13737 // (End - Start) + (Stride - 1) <= UMAX
13738 //
13739 // In other words, the addition doesn't have unsigned overflow.
13740 //
13741 // A similar proof works if we treat Start/End as signed values.
13742 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13743 // to use signed max instead of unsigned max. Note that we're
13744 // trying to prove a lack of unsigned overflow in either case.
13745 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13746 return false;
13747 }
13748 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13749 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13750 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13751 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13752 // 1 <s End.
13753 //
13754 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13755 // End.
13756 //
13757 // Both need Start to be the smaller value, so neither applies inverted.
13758 return false;
13759 }
13760 return true;
13761 }();
13762
13763 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13764 // Offset)" and "~To - ~From" is "From - To".
13765 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13766 if (Invert)
13767 return getAddExpr(V, Offset);
13768 return getMinusSCEV(V, Offset);
13769 };
13770 auto Distance = [&](const SCEV *From, const SCEV *To) {
13771 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13772 };
13773
13774 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13775 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13776 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13777 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13778 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13779 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13780 // does not overflow?
13781 if ((!AddingStrideMinusOneMayOverflow ||
13782 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13783 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13784 // In this case, we can use a refined formula for computing backedge
13785 // taken count. The general formula remains:
13786 // "End-Start /uceiling Stride"
13787 // We want to use the alternate formula:
13788 // "((RHS - 1) - (Start - Stride)) /u Stride"
13789 // Let's do a quick case analysis to show these are equivalent under
13790 // our preconditions. When inverted, the proof uses complemented Start,
13791 // RHS and End; Stride remains positive.
13792 // * For RHS <= Start (End is Start), the backedge-taken count must be
13793 // zero. Together with the precondition "Start - Stride < RHS", we have
13794 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13795 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13796 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13797 // So dividing that by Stride gives zero.
13798 //
13799 // * For RHS > Start (End is RHS), the backedge count must be
13800 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13801 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13802 //
13803 // If "Start - Stride < Start" holds, we have
13804 // "RHS > Start > Start - Stride". As such
13805 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13806 // reassociated numerator.
13807 //
13808 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13809 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13810 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13811 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13812 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13813 const SCEV *Numerator =
13814 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13815 BECount = getUDivExpr(Numerator, Stride);
13816 }
13817
13818 if (isa<SCEVCouldNotCompute>(BECount)) {
13819 auto canProveRHSIsAtOrBeyondStart = [&]() {
13820 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13821 // by swapping their operands rather than their predicates:
13822 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13823 // proof if the IV bound moves to the other side.
13824 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13825 return Invert ? std::pair(B, A) : std::pair(A, B);
13826 };
13827
13828 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13829 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13830 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13831 if (Invert)
13832 std::swap(GuardedRHS, GuardedStart);
13833
13834 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13835 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13836 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13837 return true;
13838
13839 // (RHS > Start - 1) implies RHS >= Start.
13840 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13841 // "Start - 1" doesn't overflow.
13842 // * For signed comparison, if Start - 1 does overflow, it's equal
13843 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13844 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13845 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13846 //
13847 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13848 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13849 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13850 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13851 };
13852
13853 // If we know that RHS >= Start in the context of loop, then we know
13854 // that max(RHS, Start) = RHS at this point.
13855 if (canProveRHSIsAtOrBeyondStart()) {
13856 End = RHS;
13857 } else {
13858 // If RHS < Start, the backedge will be taken zero times. So in
13859 // general, we can write the backedge-taken count as:
13860 //
13861 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13862 //
13863 // We convert it to the following to make it more convenient for SCEV:
13864 //
13865 // ceil(max(RHS, Start) - Start) / Stride
13866 //
13867 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13868 if (Invert)
13869 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13870 else
13871 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13872
13873 // See what would happen if we assume the backedge is taken. This is
13874 // used to compute MaxBECount.
13875 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13876 }
13877
13878 const SCEV *Delta = Distance(Start, End);
13879 if (!AddingStrideMinusOneMayOverflow) {
13880 // floor((D + (S - 1)) / S)
13881 // We prefer this formulation if it's legal because it's fewer
13882 // operations.
13883 BECount =
13884 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13885 } else {
13886 BECount = getUDivCeilSCEV(Delta, Stride);
13887 }
13888 }
13889 }
13890
13891 const SCEV *ConstantMaxBECount;
13892 bool MaxOrZero = false;
13893 if (isa<SCEVConstant>(BECount)) {
13894 ConstantMaxBECount = BECount;
13895 } else {
13896 ConstantMaxBECount = computeMaxBECountForLT(
13897 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13898 Invert);
13899 // If we know exactly how many times the backedge will be taken if it's
13900 // taken at least once, then the backedge count will either be that or
13901 // zero. If that count exceeds the range-based bound, the backedge can
13902 // never be taken.
13903 const APInt *IfTaken, *RangeMax;
13904 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13905 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13906 IfTaken->ugt(*RangeMax)) {
13907 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13908 } else {
13909 ConstantMaxBECount = BECountIfBackedgeTaken;
13910 MaxOrZero = true;
13911 }
13912 }
13913 }
13914
13915 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13916 !isa<SCEVCouldNotCompute>(BECount))
13917 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13918
13919 const SCEV *SymbolicMaxBECount =
13920 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13921 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13922 Predicates);
13923}
13924
13926 ScalarEvolution &SE) const {
13927 if (Range.isFullSet()) // Infinite loop.
13928 return SE.getCouldNotCompute();
13929
13930 // If the start is a non-zero constant, shift the range to simplify things.
13931 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13932 if (!SC->getValue()->isZero()) {
13934 Operands[0] = SE.getZero(SC->getType());
13935 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13937 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13938 return ShiftedAddRec->getNumIterationsInRange(
13939 Range.subtract(SC->getAPInt()), SE);
13940 // This is strange and shouldn't happen.
13941 return SE.getCouldNotCompute();
13942 }
13943
13944 // The only time we can solve this is when we have all constant indices.
13945 // Otherwise, we cannot determine the overflow conditions.
13947 return SE.getCouldNotCompute();
13948
13949 // Okay at this point we know that all elements of the chrec are constants and
13950 // that the start element is zero.
13951
13952 // First check to see if the range contains zero. If not, the first
13953 // iteration exits.
13954 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13955 if (!Range.contains(APInt(BitWidth, 0)))
13956 return SE.getZero(getType());
13957
13958 if (isAffine()) {
13959 // If this is an affine expression then we have this situation:
13960 // Solve {0,+,A} in Range === Ax in Range
13961
13962 // We know that zero is in the range. If A is positive then we know that
13963 // the upper value of the range must be the first possible exit value.
13964 // If A is negative then the lower of the range is the last possible loop
13965 // value. Also note that we already checked for a full range.
13966 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13967 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13968
13969 // The exit value should be (End+A)/A.
13970 APInt ExitVal = (End + A).udiv(A);
13971 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13972
13973 // Evaluate at the exit value. If we really did fall out of the valid
13974 // range, then we computed our trip count, otherwise wrap around or other
13975 // things must have happened.
13976 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13977 if (Range.contains(Val->getValue()))
13978 return SE.getCouldNotCompute(); // Something strange happened
13979
13980 // Ensure that the previous value is in the range.
13981 assert(Range.contains(
13983 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13984 "Linear scev computation is off in a bad way!");
13985 return SE.getConstant(ExitValue);
13986 }
13987
13988 if (isQuadratic()) {
13989 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13990 return SE.getConstant(*S);
13991 }
13992
13993 return SE.getCouldNotCompute();
13994}
13995
13996const SCEVAddRecExpr *
13998 assert(getNumOperands() > 1 && "AddRec with zero step?");
13999 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
14000 // but in this case we cannot guarantee that the value returned will be an
14001 // AddRec because SCEV does not have a fixed point where it stops
14002 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14003 // may happen if we reach arithmetic depth limit while simplifying. So we
14004 // construct the returned value explicitly.
14006 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14007 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14008 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14009 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14010 // We know that the last operand is not a constant zero (otherwise it would
14011 // have been popped out earlier). This guarantees us that if the result has
14012 // the same last operand, then it will also not be popped out, meaning that
14013 // the returned value will be an AddRec.
14014 const SCEV *Last = getOperand(getNumOperands() - 1);
14015 assert(!Last->isZero() && "Recurrency with zero step?");
14016 Ops.push_back(Last);
14018}
14019
14020// Return true when S contains at least an undef value.
14022 return SCEVExprContains(
14023 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14024}
14025
14026// Return true when S contains a value that is a nullptr.
14028 return SCEVExprContains(S, [](const SCEV *S) {
14029 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14030 return SU->getValue() == nullptr;
14031 return false;
14032 });
14033}
14034
14035/// Return the size of an element read or written by Inst.
14037 if (!isa<LoadInst, StoreInst>(Inst))
14038 return nullptr;
14040 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
14041}
14042
14043//===----------------------------------------------------------------------===//
14044// SCEVCallbackVH Class Implementation
14045//===----------------------------------------------------------------------===//
14046
14048 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14049 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14050 SE->ConstantEvolutionLoopExitValue.erase(PN);
14051 SE->eraseValueFromMap(getValPtr());
14052 // this now dangles!
14053}
14054
14055void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14056 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14057
14058 // Forget all the expressions associated with users of the old value,
14059 // so that future queries will recompute the expressions using the new
14060 // value.
14061 SE->forgetValue(getValPtr());
14062 // this now dangles!
14063}
14064
14065ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14066 : CallbackVH(V), SE(se) {}
14067
14068//===----------------------------------------------------------------------===//
14069// ScalarEvolution Class Implementation
14070//===----------------------------------------------------------------------===//
14071
14074 LoopInfo &LI)
14075 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14076 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14077 LoopDispositions(64), BlockDispositions(64) {
14078 // To use guards for proving predicates, we need to scan every instruction in
14079 // relevant basic blocks, and not just terminators. Doing this is a waste of
14080 // time if the IR does not actually contain any calls to
14081 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14082 //
14083 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14084 // to _add_ guards to the module when there weren't any before, and wants
14085 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14086 // efficient in lieu of being smart in that rather obscure case.
14087
14088 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14089 F.getParent(), Intrinsic::experimental_guard);
14090 HasGuards = GuardDecl && !GuardDecl->use_empty();
14091}
14092
14094 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14095 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14096 ValueExprMap(std::move(Arg.ValueExprMap)),
14097 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14098 PendingMerges(std::move(Arg.PendingMerges)),
14099 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14100 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14101 PredicatedBackedgeTakenCounts(
14102 std::move(Arg.PredicatedBackedgeTakenCounts)),
14103 BECountUsers(std::move(Arg.BECountUsers)),
14104 ConstantEvolutionLoopExitValue(
14105 std::move(Arg.ConstantEvolutionLoopExitValue)),
14106 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14107 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14108 LoopDispositions(std::move(Arg.LoopDispositions)),
14109 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14110 BlockDispositions(std::move(Arg.BlockDispositions)),
14111 SCEVUsers(std::move(Arg.SCEVUsers)),
14112 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14113 SignedRanges(std::move(Arg.SignedRanges)),
14114 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14115 UniquePreds(std::move(Arg.UniquePreds)),
14116 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14117 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14118 LoopUsers(std::move(Arg.LoopUsers)),
14119 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14120 FirstUnknown(Arg.FirstUnknown),
14121 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14122 Arg.FirstUnknown = nullptr;
14123}
14124
14126 // Iterate through all the SCEVUnknown instances and call their
14127 // destructors, so that they release their references to their values.
14128 for (SCEVUnknown *U = FirstUnknown; U;) {
14129 SCEVUnknown *Tmp = U;
14130 U = U->Next;
14131 Tmp->~SCEVUnknown();
14132 }
14133 FirstUnknown = nullptr;
14134
14135 ExprValueMap.clear();
14136 ValueExprMap.clear();
14137 HasRecMap.clear();
14138 BackedgeTakenCounts.clear();
14139 PredicatedBackedgeTakenCounts.clear();
14140
14141 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14142 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14143 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14144 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14145}
14146
14150
14151/// When printing a top-level SCEV for trip counts, it's helpful to include
14152/// a type for constants which are otherwise hard to disambiguate.
14153static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14154 if (isa<SCEVConstant>(S))
14155 OS << *S->getType() << " ";
14156 OS << *S;
14157}
14158
14160 const Loop *L) {
14161 // Print all inner loops first
14162 for (Loop *I : *L)
14163 PrintLoopInfo(OS, SE, I);
14164
14165 OS << "Loop ";
14166 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14167 OS << ": ";
14168
14169 SmallVector<BasicBlock *, 8> ExitingBlocks;
14170 L->getExitingBlocks(ExitingBlocks);
14171 if (ExitingBlocks.size() != 1)
14172 OS << "<multiple exits> ";
14173
14174 auto *BTC = SE->getBackedgeTakenCount(L);
14175 if (!isa<SCEVCouldNotCompute>(BTC)) {
14176 OS << "backedge-taken count is ";
14177 PrintSCEVWithTypeHint(OS, BTC);
14178 } else
14179 OS << "Unpredictable backedge-taken count.";
14180 OS << "\n";
14181
14182 if (ExitingBlocks.size() > 1)
14183 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14184 OS << " exit count for " << ExitingBlock->getName() << ": ";
14185 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14186 PrintSCEVWithTypeHint(OS, EC);
14187 if (isa<SCEVCouldNotCompute>(EC)) {
14188 // Retry with predicates.
14190 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14191 if (!isa<SCEVCouldNotCompute>(EC)) {
14192 OS << "\n predicated exit count for " << ExitingBlock->getName()
14193 << ": ";
14194 PrintSCEVWithTypeHint(OS, EC);
14195 OS << "\n Predicates:\n";
14196 for (const auto *P : Predicates)
14197 P->print(OS, 4);
14198 }
14199 }
14200 OS << "\n";
14201 }
14202
14203 OS << "Loop ";
14204 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14205 OS << ": ";
14206
14207 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14208 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14209 OS << "constant max backedge-taken count is ";
14210 PrintSCEVWithTypeHint(OS, ConstantBTC);
14212 OS << ", actual taken count either this or zero.";
14213 } else {
14214 OS << "Unpredictable constant max backedge-taken count. ";
14215 }
14216
14217 OS << "\n"
14218 "Loop ";
14219 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14220 OS << ": ";
14221
14222 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14223 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14224 OS << "symbolic max backedge-taken count is ";
14225 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14227 OS << ", actual taken count either this or zero.";
14228 } else {
14229 OS << "Unpredictable symbolic max backedge-taken count. ";
14230 }
14231 OS << "\n";
14232
14233 if (ExitingBlocks.size() > 1)
14234 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14235 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14236 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14238 PrintSCEVWithTypeHint(OS, ExitBTC);
14239 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14240 // Retry with predicates.
14242 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14244 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14245 OS << "\n predicated symbolic max exit count for "
14246 << ExitingBlock->getName() << ": ";
14247 PrintSCEVWithTypeHint(OS, ExitBTC);
14248 OS << "\n Predicates:\n";
14249 for (const auto *P : Predicates)
14250 P->print(OS, 4);
14251 }
14252 }
14253 OS << "\n";
14254 }
14255
14257 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14258 if (PBT != BTC) {
14259 OS << "Loop ";
14260 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14261 OS << ": ";
14262 if (!isa<SCEVCouldNotCompute>(PBT)) {
14263 OS << "Predicated backedge-taken count is ";
14264 PrintSCEVWithTypeHint(OS, PBT);
14265 } else
14266 OS << "Unpredictable predicated backedge-taken count.";
14267 OS << "\n";
14268 OS << " Predicates:\n";
14269 for (const auto *P : Preds)
14270 P->print(OS, 4);
14271 }
14272 Preds.clear();
14273
14274 auto *PredConstantMax =
14276 if (PredConstantMax != ConstantBTC) {
14277 OS << "Loop ";
14278 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14279 OS << ": ";
14280 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14281 OS << "Predicated constant max backedge-taken count is ";
14282 PrintSCEVWithTypeHint(OS, PredConstantMax);
14283 } else
14284 OS << "Unpredictable predicated constant max backedge-taken count.";
14285 OS << "\n";
14286 OS << " Predicates:\n";
14287 for (const auto *P : Preds)
14288 P->print(OS, 4);
14289 }
14290 Preds.clear();
14291
14292 auto *PredSymbolicMax =
14294 if (SymbolicBTC != PredSymbolicMax) {
14295 OS << "Loop ";
14296 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14297 OS << ": ";
14298 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14299 OS << "Predicated symbolic max backedge-taken count is ";
14300 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14301 } else
14302 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14303 OS << "\n";
14304 OS << " Predicates:\n";
14305 for (const auto *P : Preds)
14306 P->print(OS, 4);
14307 }
14308
14310 OS << "Loop ";
14311 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14312 OS << ": ";
14313 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14314 }
14315}
14316
14317namespace llvm {
14318// Note: these overloaded operators need to be in the llvm namespace for them
14319// to be resolved correctly. If we put them outside the llvm namespace, the
14320//
14321// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14322//
14323// code below "breaks" and start printing raw enum values as opposed to the
14324// string values.
14327 switch (LD) {
14329 OS << "Variant";
14330 break;
14332 OS << "Invariant";
14333 break;
14335 OS << "Uniform";
14336 break;
14338 OS << "Computable";
14339 break;
14340 }
14341 return OS;
14342}
14343
14346 switch (BD) {
14348 OS << "DoesNotDominate";
14349 break;
14351 OS << "Dominates";
14352 break;
14354 OS << "ProperlyDominates";
14355 break;
14356 }
14357 return OS;
14358}
14359} // namespace llvm
14360
14362 // ScalarEvolution's implementation of the print method is to print
14363 // out SCEV values of all instructions that are interesting. Doing
14364 // this potentially causes it to create new SCEV objects though,
14365 // which technically conflicts with the const qualifier. This isn't
14366 // observable from outside the class though, so casting away the
14367 // const isn't dangerous.
14368 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14369
14370 if (ClassifyExpressions) {
14371 OS << "Classifying expressions for: ";
14372 F.printAsOperand(OS, /*PrintType=*/false);
14373 OS << "\n";
14374 for (Instruction &I : instructions(F))
14375 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14376 OS << I << '\n';
14377 OS << " --> ";
14378 const SCEV *SV = SE.getSCEV(&I);
14379 SV->print(OS);
14380 if (!isa<SCEVCouldNotCompute>(SV)) {
14381 OS << " U: ";
14382 SE.getUnsignedRange(SV).print(OS);
14383 OS << " S: ";
14384 SE.getSignedRange(SV).print(OS);
14385 }
14386
14387 const Loop *L = LI.getLoopFor(I.getParent());
14388
14389 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14390 if (AtUse != SV) {
14391 OS << " --> ";
14392 OS << AtUse;
14393 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14394 OS << " U: ";
14395 SE.getUnsignedRange(AtUse).print(OS);
14396 OS << " S: ";
14397 SE.getSignedRange(AtUse).print(OS);
14398 }
14399 }
14400
14401 if (L) {
14402 OS << "\t\t" "Exits: ";
14403 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14404 if (!SE.isLoopInvariant(ExitValue, L)) {
14405 OS << "<<Unknown>>";
14406 } else {
14407 OS << ExitValue;
14408 }
14409
14410 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14411 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14412 OS << LS;
14413 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14414 OS << ": " << SE.getLoopDisposition(SV, Iter);
14415 }
14416
14417 for (const auto *InnerL : depth_first(L)) {
14418 if (InnerL == L)
14419 continue;
14420 OS << LS;
14421 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14422 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14423 }
14424
14425 OS << " }";
14426 }
14427
14428 OS << "\n";
14429 }
14430 }
14431
14432 OS << "Determining loop execution counts for: ";
14433 F.printAsOperand(OS, /*PrintType=*/false);
14434 OS << "\n";
14435 for (Loop *I : LI)
14436 PrintLoopInfo(OS, &SE, I);
14437}
14438
14441 if (isa<SCEVConstant>(S))
14442 return LoopInvariant;
14443
14444 auto &Values = LoopDispositions[S];
14445 for (auto &V : Values) {
14446 if (V.getPointer() == L)
14447 return V.getInt();
14448 }
14449 Values.emplace_back(L, LoopVariant);
14450 LoopDisposition D = computeLoopDisposition(S, L);
14451 auto &Values2 = LoopDispositions[S];
14452 for (auto &V : llvm::reverse(Values2)) {
14453 if (V.getPointer() == L) {
14454 V.setInt(D);
14455 break;
14456 }
14457 }
14458 return D;
14459}
14460
14462ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14463 switch (S->getSCEVType()) {
14464 case scConstant:
14465 case scVScale:
14466 return LoopInvariant;
14467 case scAddRecExpr: {
14468 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14469
14470 // If L is the addrec's loop, it's computable.
14471 if (AR->getLoop() == L)
14472 return LoopComputable;
14473
14474 // Add recurrences are never invariant in the function-body (null loop).
14475 if (!L)
14476 return LoopVariant;
14477
14478 // Everything that is not defined at loop entry is variant.
14479 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14480 if (L->contains(AR->getLoop()) &&
14481 llvm::all_of(AR->operands(),
14482 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14483 return LoopUniform;
14484
14485 return LoopVariant;
14486 }
14487 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14488 " dominate the contained loop's header?");
14489
14490 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14491 if (AR->getLoop()->contains(L))
14492 return LoopInvariant;
14493
14494 // This recurrence is variant w.r.t. L if any of its operands
14495 // are variant.
14496 for (SCEVUse Op : AR->operands())
14497 if (!isLoopInvariant(Op, L))
14498 return LoopVariant;
14499
14500 // Otherwise it's loop-invariant.
14501 return LoopInvariant;
14502 }
14503 case scTruncate:
14504 case scZeroExtend:
14505 case scSignExtend:
14506 case scPtrToAddr:
14507 case scAddExpr:
14508 case scMulExpr:
14509 case scUDivExpr:
14510 case scUMaxExpr:
14511 case scSMaxExpr:
14512 case scUMinExpr:
14513 case scSMinExpr:
14514 case scSequentialUMinExpr: {
14515 bool HasVarying = false;
14516 bool HasUniform = false;
14517 for (SCEVUse Op : S->operands()) {
14519 if (D == LoopVariant)
14520 return LoopVariant;
14521 if (D == LoopComputable)
14522 HasVarying = true;
14523 if (D == LoopUniform)
14524 HasUniform = true;
14525 }
14526 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14527 : (HasUniform ? LoopUniform : LoopInvariant);
14528 }
14529 case scUnknown:
14530 // All non-instruction values are loop invariant. All instructions are loop
14531 // invariant if they are not contained in the specified loop.
14532 // Instructions are never considered invariant in the function body
14533 // (null loop) because they are defined within the "loop".
14535 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14536 return LoopInvariant;
14537 case scCouldNotCompute:
14538 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14539 }
14540 llvm_unreachable("Unknown SCEV kind!");
14541}
14542
14543bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14545 return D == LoopUniform || D == LoopInvariant;
14546}
14547
14549 return getLoopDisposition(S, L) == LoopInvariant;
14550}
14551
14553 return getLoopDisposition(S, L) == LoopComputable;
14554}
14555
14558 if (isa<SCEVConstant>(S))
14560
14561 auto &Values = BlockDispositions[S];
14562 for (auto &V : Values) {
14563 if (V.getPointer() == BB)
14564 return V.getInt();
14565 }
14566 Values.emplace_back(BB, DoesNotDominateBlock);
14567 BlockDisposition D = computeBlockDisposition(S, BB);
14568 auto &Values2 = BlockDispositions[S];
14569 for (auto &V : llvm::reverse(Values2)) {
14570 if (V.getPointer() == BB) {
14571 V.setInt(D);
14572 break;
14573 }
14574 }
14575 return D;
14576}
14577
14579ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14580 switch (S->getSCEVType()) {
14581 case scConstant:
14582 case scVScale:
14584 case scAddRecExpr: {
14585 // This uses a "dominates" query instead of "properly dominates" query
14586 // to test for proper dominance too, because the instruction which
14587 // produces the addrec's value is a PHI, and a PHI effectively properly
14588 // dominates its entire containing block.
14589 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14590 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14591 return DoesNotDominateBlock;
14592
14593 // Fall through into SCEVNAryExpr handling.
14594 [[fallthrough]];
14595 }
14596 case scTruncate:
14597 case scZeroExtend:
14598 case scSignExtend:
14599 case scPtrToAddr:
14600 case scAddExpr:
14601 case scMulExpr:
14602 case scUDivExpr:
14603 case scUMaxExpr:
14604 case scSMaxExpr:
14605 case scUMinExpr:
14606 case scSMinExpr:
14607 case scSequentialUMinExpr: {
14608 bool Proper = true;
14609 for (const SCEV *NAryOp : S->operands()) {
14611 if (D == DoesNotDominateBlock)
14612 return DoesNotDominateBlock;
14613 if (D == DominatesBlock)
14614 Proper = false;
14615 }
14616 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14617 }
14618 case scUnknown:
14619 if (Instruction *I =
14621 if (I->getParent() == BB)
14622 return DominatesBlock;
14623 if (DT.properlyDominates(I->getParent(), BB))
14625 return DoesNotDominateBlock;
14626 }
14628 case scCouldNotCompute:
14629 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14630 }
14631 llvm_unreachable("Unknown SCEV kind!");
14632}
14633
14634bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14635 return getBlockDisposition(S, BB) >= DominatesBlock;
14636}
14637
14640}
14641
14642void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14643 bool Predicated) {
14644 auto &BECounts =
14645 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14646 auto It = BECounts.find(L);
14647 if (It != BECounts.end()) {
14648 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14649 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14650 if (!isa<SCEVConstant>(S)) {
14651 auto UserIt = BECountUsers.find(S);
14652 assert(UserIt != BECountUsers.end());
14653 UserIt->second.erase({L, Predicated});
14654 }
14655 }
14656 }
14657 BECounts.erase(It);
14658 }
14659}
14660
14661void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14662 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14663 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14664
14665 while (!Worklist.empty()) {
14666 const SCEV *Curr = Worklist.pop_back_val();
14667 auto Users = SCEVUsers.find(Curr);
14668 if (Users != SCEVUsers.end())
14669 for (const auto *User : Users->second)
14670 if (ToForget.insert(User).second)
14671 Worklist.push_back(User);
14672 }
14673
14674 for (const auto *S : ToForget)
14675 forgetMemoizedResultsImpl(S);
14676
14677 PredicatedSCEVRewrites.remove_if(
14678 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14679}
14680
14681void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14682 LoopDispositions.erase(S);
14683 BlockDispositions.erase(S);
14684 UnsignedRanges.erase(S);
14685 SignedRanges.erase(S);
14686 HasRecMap.erase(S);
14687 ConstantMultipleCache.erase(S);
14688
14689 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14690 UnsignedWrapViaInductionTried.erase(AR);
14691 SignedWrapViaInductionTried.erase(AR);
14692 }
14693
14694 auto ExprIt = ExprValueMap.find(S);
14695 if (ExprIt != ExprValueMap.end()) {
14696 for (Value *V : ExprIt->second) {
14697 auto ValueIt = ValueExprMap.find_as(V);
14698 if (ValueIt != ValueExprMap.end())
14699 ValueExprMap.erase(ValueIt);
14700 }
14701 ExprValueMap.erase(ExprIt);
14702 }
14703
14704 auto ScopeIt = ValuesAtScopes.find(S);
14705 if (ScopeIt != ValuesAtScopes.end()) {
14706 for (const auto &Pair : ScopeIt->second)
14707 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14708 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14709 std::make_pair(Pair.first, S));
14710 ValuesAtScopes.erase(ScopeIt);
14711 }
14712
14713 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14714 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14715 for (const auto &Pair : ScopeUserIt->second)
14716 // The recorded value at scope is a use of S, which may carry no-wrap
14717 // flags that are not part of this key.
14718 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14719 return LS.first == Pair.first && LS.second.getPointer() == S;
14720 });
14721 ValuesAtScopesUsers.erase(ScopeUserIt);
14722 }
14723
14724 auto BEUsersIt = BECountUsers.find(S);
14725 if (BEUsersIt != BECountUsers.end()) {
14726 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14727 auto Copy = BEUsersIt->second;
14728 for (const auto &Pair : Copy)
14729 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14730 BECountUsers.erase(BEUsersIt);
14731 }
14732
14733 auto FoldUser = FoldCacheUser.find(S);
14734 if (FoldUser != FoldCacheUser.end())
14735 for (auto &KV : FoldUser->second)
14736 FoldCache.erase(KV);
14737 FoldCacheUser.erase(S);
14738}
14739
14740void
14741ScalarEvolution::getUsedLoops(const SCEV *S,
14742 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14743 struct FindUsedLoops {
14744 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14745 : LoopsUsed(LoopsUsed) {}
14746 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14747 bool follow(const SCEV *S) {
14748 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14749 LoopsUsed.insert(AR->getLoop());
14750 return true;
14751 }
14752
14753 bool isDone() const { return false; }
14754 };
14755
14756 FindUsedLoops F(LoopsUsed);
14757 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14758}
14759
14760void ScalarEvolution::getReachableBlocks(
14763 Worklist.push_back(&F.getEntryBlock());
14764 while (!Worklist.empty()) {
14765 BasicBlock *BB = Worklist.pop_back_val();
14766 if (!Reachable.insert(BB).second)
14767 continue;
14768
14769 Value *Cond;
14770 BasicBlock *TrueBB, *FalseBB;
14771 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14772 m_BasicBlock(FalseBB)))) {
14773 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14774 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14775 continue;
14776 }
14777
14778 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14779 const SCEV *L = getSCEV(Cmp->getOperand(0));
14780 const SCEV *R = getSCEV(Cmp->getOperand(1));
14781 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14782 Worklist.push_back(TrueBB);
14783 continue;
14784 }
14785 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14786 R)) {
14787 Worklist.push_back(FalseBB);
14788 continue;
14789 }
14790 }
14791 }
14792
14793 append_range(Worklist, successors(BB));
14794 }
14795}
14796
14798 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14799 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14800
14801 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14802
14803 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14804 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14805 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14806
14807 const SCEV *visitConstant(const SCEVConstant *Constant) {
14808 return SE.getConstant(Constant->getAPInt());
14809 }
14810
14811 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14812 return SE.getUnknown(Expr->getValue());
14813 }
14814
14815 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14816 return SE.getCouldNotCompute();
14817 }
14818 };
14819
14820 SCEVMapper SCM(SE2);
14821 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14822 SE2.getReachableBlocks(ReachableBlocks, F);
14823
14824 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14825 if (containsUndefs(Old) || containsUndefs(New)) {
14826 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14827 // not propagate undef aggressively). This means we can (and do) fail
14828 // verification in cases where a transform makes a value go from "undef"
14829 // to "undef+1" (say). The transform is fine, since in both cases the
14830 // result is "undef", but SCEV thinks the value increased by 1.
14831 return nullptr;
14832 }
14833
14834 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14835 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14836 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14837 return nullptr;
14838
14839 return Delta;
14840 };
14841
14842 while (!LoopStack.empty()) {
14843 auto *L = LoopStack.pop_back_val();
14844 llvm::append_range(LoopStack, *L);
14845
14846 // Only verify BECounts in reachable loops. For an unreachable loop,
14847 // any BECount is legal.
14848 if (!ReachableBlocks.contains(L->getHeader()))
14849 continue;
14850
14851 // Only verify cached BECounts. Computing new BECounts may change the
14852 // results of subsequent SCEV uses.
14853 auto It = BackedgeTakenCounts.find(L);
14854 if (It == BackedgeTakenCounts.end())
14855 continue;
14856
14857 auto *CurBECount =
14858 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14859 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14860
14861 if (CurBECount == SE2.getCouldNotCompute() ||
14862 NewBECount == SE2.getCouldNotCompute()) {
14863 // NB! This situation is legal, but is very suspicious -- whatever pass
14864 // change the loop to make a trip count go from could not compute to
14865 // computable or vice-versa *should have* invalidated SCEV. However, we
14866 // choose not to assert here (for now) since we don't want false
14867 // positives.
14868 continue;
14869 }
14870
14871 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14872 SE.getTypeSizeInBits(NewBECount->getType()))
14873 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14874 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14875 SE.getTypeSizeInBits(NewBECount->getType()))
14876 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14877
14878 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14879 if (Delta && !Delta->isZero()) {
14880 dbgs() << "Trip Count for " << *L << " Changed!\n";
14881 dbgs() << "Old: " << *CurBECount << "\n";
14882 dbgs() << "New: " << *NewBECount << "\n";
14883 dbgs() << "Delta: " << *Delta << "\n";
14884 std::abort();
14885 }
14886 }
14887
14888 // Collect all valid loops currently in LoopInfo.
14889 SmallPtrSet<Loop *, 32> ValidLoops;
14890 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14891 while (!Worklist.empty()) {
14892 Loop *L = Worklist.pop_back_val();
14893 if (ValidLoops.insert(L).second)
14894 Worklist.append(L->begin(), L->end());
14895 }
14896 for (const auto &KV : ValueExprMap) {
14897#ifndef NDEBUG
14898 // Check for SCEV expressions referencing invalid/deleted loops.
14899 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14900 assert(ValidLoops.contains(AR->getLoop()) &&
14901 "AddRec references invalid loop");
14902 }
14903#endif
14904
14905 // Check that the value is also part of the reverse map.
14906 auto It = ExprValueMap.find(KV.second);
14907 if (It == ExprValueMap.end() || !is_contained(It->second, KV.first)) {
14908 dbgs() << "Value " << *KV.first
14909 << " is in ValueExprMap but not in ExprValueMap\n";
14910 std::abort();
14911 }
14912
14913 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14914 if (!ReachableBlocks.contains(I->getParent()))
14915 continue;
14916 const SCEV *OldSCEV = SCM.visit(KV.second);
14917 const SCEV *NewSCEV = SE2.getSCEV(I);
14918 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14919 if (Delta && !Delta->isZero()) {
14920 dbgs() << "SCEV for value " << *I << " changed!\n"
14921 << "Old: " << *OldSCEV << "\n"
14922 << "New: " << *NewSCEV << "\n"
14923 << "Delta: " << *Delta << "\n";
14924 std::abort();
14925 }
14926 }
14927 }
14928
14929 for (const auto &KV : ExprValueMap) {
14930 for (Value *V : KV.second) {
14931 const SCEV *S = ValueExprMap.lookup(V);
14932 if (!S) {
14933 dbgs() << "Value " << *V
14934 << " is in ExprValueMap but not in ValueExprMap\n";
14935 std::abort();
14936 }
14937 if (S != KV.first) {
14938 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14939 << *KV.first << "\n";
14940 std::abort();
14941 }
14942 }
14943 }
14944
14945 // Verify integrity of SCEV users.
14946 for (const auto &S : UniqueSCEVs) {
14947 for (SCEVUse Op : S.operands()) {
14948 // We do not store dependencies of constants.
14949 if (isa<SCEVConstant>(Op))
14950 continue;
14951 auto It = SCEVUsers.find(Op);
14952 if (It != SCEVUsers.end() && It->second.count(&S))
14953 continue;
14954 dbgs() << "Use of operand " << *Op << " by user " << S
14955 << " is not being tracked!\n";
14956 std::abort();
14957 }
14958 }
14959
14960 // Verify integrity of ValuesAtScopes users.
14961 for (const auto &ValueAndVec : ValuesAtScopes) {
14962 const SCEV *Value = ValueAndVec.first;
14963 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14964 const Loop *L = LoopAndValueAtScope.first;
14965 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14966 if (!isa<SCEVConstant>(ValueAtScope)) {
14967 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14968 if (It != ValuesAtScopesUsers.end() &&
14969 is_contained(It->second, std::make_pair(L, Value)))
14970 continue;
14971 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14972 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14973 std::abort();
14974 }
14975 }
14976 }
14977
14978 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14979 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14980 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14981 const Loop *L = LoopAndValue.first;
14982 const SCEV *Value = LoopAndValue.second;
14984 auto It = ValuesAtScopes.find(Value);
14985 // The recorded value at scope may carry no-wrap flags that are not part
14986 // of the key it is recorded under.
14987 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14988 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14989 }))
14990 continue;
14991 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14992 << *ValueAtScope << " missing in ValuesAtScopes\n";
14993 std::abort();
14994 }
14995 }
14996
14997 // Verify integrity of BECountUsers.
14998 auto VerifyBECountUsers = [&](bool Predicated) {
14999 auto &BECounts =
15000 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15001 for (const auto &LoopAndBEInfo : BECounts) {
15002 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15003 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15004 if (!isa<SCEVConstant>(S)) {
15005 auto UserIt = BECountUsers.find(S);
15006 if (UserIt != BECountUsers.end() &&
15007 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15008 continue;
15009 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15010 << " missing from BECountUsers\n";
15011 std::abort();
15012 }
15013 }
15014 }
15015 }
15016 };
15017 VerifyBECountUsers(/* Predicated */ false);
15018 VerifyBECountUsers(/* Predicated */ true);
15019
15020 // Verify intergity of loop disposition cache.
15021 for (auto &[S, Values] : LoopDispositions) {
15022 for (auto [Loop, CachedDisposition] : Values) {
15023 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15024 if (CachedDisposition != RecomputedDisposition) {
15025 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15026 << " is incorrect: cached " << CachedDisposition << ", actual "
15027 << RecomputedDisposition << "\n";
15028 std::abort();
15029 }
15030 }
15031 }
15032
15033 // Verify integrity of the block disposition cache.
15034 for (auto &[S, Values] : BlockDispositions) {
15035 for (auto [BB, CachedDisposition] : Values) {
15036 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15037 if (CachedDisposition != RecomputedDisposition) {
15038 dbgs() << "Cached disposition of " << *S << " for block %"
15039 << BB->getName() << " is incorrect: cached " << CachedDisposition
15040 << ", actual " << RecomputedDisposition << "\n";
15041 std::abort();
15042 }
15043 }
15044 }
15045
15046 // Verify FoldCache/FoldCacheUser caches.
15047 for (auto [FoldID, Expr] : FoldCache) {
15048 auto I = FoldCacheUser.find(Expr);
15049 if (I == FoldCacheUser.end()) {
15050 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15051 << "!\n";
15052 std::abort();
15053 }
15054 if (!is_contained(I->second, FoldID)) {
15055 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15056 std::abort();
15057 }
15058 }
15059 for (auto [Expr, IDs] : FoldCacheUser) {
15060 for (auto &FoldID : IDs) {
15061 const SCEV *S = FoldCache.lookup(FoldID);
15062 if (!S) {
15063 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15064 << "!\n";
15065 std::abort();
15066 }
15067 if (S != Expr) {
15068 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15069 << " != " << *Expr << "!\n";
15070 std::abort();
15071 }
15072 }
15073 }
15074
15075 // Verify that ConstantMultipleCache computations are correct. We check that
15076 // cached multiples and recomputed multiples are multiples of each other to
15077 // verify correctness. It is possible that a recomputed multiple is different
15078 // from the cached multiple due to strengthened no wrap flags or changes in
15079 // KnownBits computations.
15080 for (auto [S, Multiple] : ConstantMultipleCache) {
15081 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15082 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15083 Multiple.urem(RecomputedMultiple) != 0 &&
15084 RecomputedMultiple.urem(Multiple) != 0)) {
15085 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15086 << *S << " : Computed " << RecomputedMultiple
15087 << " but cache contains " << Multiple << "!\n";
15088 std::abort();
15089 }
15090 }
15091}
15092
15094 Function &F, const PreservedAnalyses &PA,
15095 FunctionAnalysisManager::Invalidator &Inv) {
15096 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15097 // of its dependencies is invalidated.
15098 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15099 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15100 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15101 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15102 Inv.invalidate<LoopAnalysis>(F, PA);
15103}
15104
15105AnalysisKey ScalarEvolutionAnalysis::Key;
15106
15109 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15110 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15111 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15112 auto &LI = AM.getResult<LoopAnalysis>(F);
15113 return ScalarEvolution(F, TLI, AC, DT, LI);
15114}
15115
15121
15124 // For compatibility with opt's -analyze feature under legacy pass manager
15125 // which was not ported to NPM. This keeps tests using
15126 // update_analyze_test_checks.py working.
15127 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15128 << F.getName() << "':\n";
15130 return PreservedAnalyses::all();
15131}
15132
15134 "Scalar Evolution Analysis", false, true)
15140 "Scalar Evolution Analysis", false, true)
15141
15142char ScalarEvolutionWrapperPass::ID = 0;
15143
15145
15147 SE.reset(new ScalarEvolution(
15149 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15151 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15152 return false;
15153}
15154
15156
15158 SE->print(OS);
15159}
15160
15162 if (!VerifySCEV)
15163 return;
15164
15165 SE->verify();
15166}
15167
15175
15177 const SCEV *RHS) {
15178 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15179}
15180
15181const SCEVPredicate *
15183 const SCEV *LHS, const SCEV *RHS) {
15185 assert(LHS->getType() == RHS->getType() &&
15186 "Type mismatch between LHS and RHS");
15187 // Unique this node based on the arguments
15188 ID.AddInteger(SCEVPredicate::P_Compare);
15189 ID.AddInteger(Pred);
15190 ID.AddPointer(LHS);
15191 ID.AddPointer(RHS);
15193 if (const auto *S = UniquePreds.lookup(ID, Token))
15194 return S;
15195 SCEVComparePredicate *Eq = new (SCEVAllocator)
15196 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15197 UniquePreds.insert(Eq, Token);
15198 return Eq;
15199}
15200
15202 const SCEVAddRecExpr *AR,
15205 // Unique this node based on the arguments
15207 ID.AddPointer(AR);
15208 ID.AddInteger(AddedFlags);
15210 if (const auto *S = UniquePreds.lookup(ID, Token))
15211 return S;
15212 auto *OF = new (SCEVAllocator)
15213 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15214 UniquePreds.insert(OF, Token);
15215 return OF;
15216}
15217
15218namespace {
15219
15220class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15221public:
15222
15223 /// Rewrites \p S in the context of a loop L and the SCEV predication
15224 /// infrastructure.
15225 ///
15226 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15227 /// equivalences present in \p Pred.
15228 ///
15229 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15230 /// \p NewPreds such that the result will be an AddRecExpr.
15231 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15233 const SCEVPredicate *Pred) {
15234 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15235 return Rewriter.visit(S);
15236 }
15237
15238 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15239 if (Pred) {
15240 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15241 for (const auto *Pred : U->getPredicates())
15242 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15243 if (IPred->getLHS() == Expr &&
15244 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15245 return IPred->getRHS();
15246 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15247 if (IPred->getLHS() == Expr &&
15248 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15249 return IPred->getRHS();
15250 }
15251 }
15252 return convertToAddRecWithPreds(Expr);
15253 }
15254
15255 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15256 const SCEV *Operand = visit(Expr->getOperand());
15257 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15258 if (AR && AR->getLoop() == L && AR->isAffine()) {
15259 // This couldn't be folded because the operand didn't have the nuw
15260 // flag. Add the nusw flag as an assumption that we could make.
15261 const SCEV *Step = AR->getStepRecurrence(SE);
15262 Type *Ty = Expr->getType();
15263 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15264 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15265 SE.getSignExtendExpr(Step, Ty), L,
15266 AR->getNoWrapFlags());
15267 }
15268 return SE.getZeroExtendExpr(Operand, Expr->getType());
15269 }
15270
15271 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15272 const SCEV *Operand = visit(Expr->getOperand());
15273 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15274 if (AR && AR->getLoop() == L && AR->isAffine()) {
15275 // This couldn't be folded because the operand didn't have the nsw
15276 // flag. Add the nssw flag as an assumption that we could make.
15277 const SCEV *Step = AR->getStepRecurrence(SE);
15278 Type *Ty = Expr->getType();
15279 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15280 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15281 SE.getSignExtendExpr(Step, Ty), L,
15282 AR->getNoWrapFlags());
15283 }
15284 return SE.getSignExtendExpr(Operand, Expr->getType());
15285 }
15286
15287private:
15288 explicit SCEVPredicateRewriter(
15289 const Loop *L, ScalarEvolution &SE,
15290 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15291 const SCEVPredicate *Pred)
15292 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15293
15294 bool addOverflowAssumption(const SCEVPredicate *P) {
15295 if (!NewPreds) {
15296 // Check if we've already made this assumption.
15297 return Pred && Pred->implies(P, SE);
15298 }
15299 NewPreds->push_back(P);
15300 return true;
15301 }
15302
15303 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15305 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15306 return addOverflowAssumption(A);
15307 }
15308
15309 // If \p Expr represents a PHINode, we try to see if it can be represented
15310 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15311 // to add this predicate as a runtime overflow check, we return the AddRec.
15312 // If \p Expr does not meet these conditions (is not a PHI node, or we
15313 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15314 // return \p Expr.
15315 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15316 if (!isa<PHINode>(Expr->getValue()))
15317 return Expr;
15318 std::optional<
15319 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15320 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15321 if (!PredicatedRewrite)
15322 return Expr;
15323 for (const auto *P : PredicatedRewrite->second){
15324 // Wrap predicates from outer loops are not supported.
15325 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15326 if (L != WP->getExpr()->getLoop())
15327 return Expr;
15328 }
15329 if (!addOverflowAssumption(P))
15330 return Expr;
15331 }
15332 return PredicatedRewrite->first;
15333 }
15334
15335 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15336 const SCEVPredicate *Pred;
15337 const Loop *L;
15338};
15339
15340} // end anonymous namespace
15341
15342const SCEV *
15344 const SCEVPredicate &Preds) {
15345 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15346}
15347
15349 const SCEV *S, const Loop *L,
15352 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15353 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15354
15355 if (!AddRec)
15356 return nullptr;
15357
15358 // Check if any of the transformed predicates is known to be false. In that
15359 // case, it doesn't make sense to convert to a predicated AddRec, as the
15360 // versioned loop will never execute.
15361 for (const SCEVPredicate *Pred : TransformPreds) {
15362 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15363 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15364 continue;
15365
15366 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15367 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15368 if (isa<SCEVCouldNotCompute>(ExitCount))
15369 continue;
15370
15371 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15372 if (!Step->isOne())
15373 continue;
15374
15375 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15376 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15377 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15378 return nullptr;
15379 }
15380
15381 // Since the transformation was successful, we can now transfer the SCEV
15382 // predicates.
15383 Preds.append(TransformPreds.begin(), TransformPreds.end());
15384
15385 return AddRec;
15386}
15387
15388/// SCEV predicates
15392
15394 const ICmpInst::Predicate Pred,
15395 const SCEV *LHS, const SCEV *RHS)
15396 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15397 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15398 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15399}
15400
15402 ScalarEvolution &SE) const {
15403 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15404
15405 if (!Op)
15406 return false;
15407
15408 if (Pred != ICmpInst::ICMP_EQ)
15409 return false;
15410
15411 return Op->LHS == LHS && Op->RHS == RHS;
15412}
15413
15414bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15415
15417 if (Pred == ICmpInst::ICMP_EQ)
15418 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15419 else
15420 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15421 << *RHS << "\n";
15422
15423}
15424
15426 const SCEVAddRecExpr *AR,
15427 IncrementWrapFlags Flags)
15428 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15429
15430const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15431
15433 ScalarEvolution &SE) const {
15434 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15435 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15436 return false;
15437
15438 if (Op->AR == AR)
15439 return true;
15440
15441 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15443 return false;
15444
15445 const SCEV *Start = AR->getStart();
15446 const SCEV *OpStart = Op->AR->getStart();
15447 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15448 return false;
15449
15450 // Reject pointers to different address spaces.
15451 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15452 return false;
15453
15454 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15455 // narrower-type AddRec.
15456 if (SE.getTypeSizeInBits(AR->getType()) >
15457 SE.getTypeSizeInBits(Op->AR->getType()))
15458 return false;
15459
15460 const SCEV *Step = AR->getStepRecurrence(SE);
15461 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15462 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15463 return false;
15464
15465 // If both steps are positive, this implies N, if N's start and step are
15466 // ULE/SLE (for NSUW/NSSW) than this'.
15467 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15468 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15469 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15470
15471 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15472 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15473 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15474 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15475 : SE.getNoopOrSignExtend(Start, WiderTy);
15477 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15478 SE.isKnownPredicate(Pred, OpStart, Start);
15479}
15480
15482 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15483 IncrementWrapFlags IFlags = Flags;
15484
15485 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15486 IFlags = clearFlags(IFlags, IncrementNSSW);
15487
15488 return IFlags == IncrementAnyWrap;
15489}
15490
15491void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15492 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15494 OS << "<nusw>";
15496 OS << "<nssw>";
15497 OS << "\n";
15498}
15499
15500/// Union predicates don't get cached so create a dummy set ID for it.
15502 ScalarEvolution &SE)
15504 for (const auto *P : Preds)
15505 add(P, SE);
15506}
15507
15509 return all_of(Preds,
15510 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15511}
15512
15514 ScalarEvolution &SE) const {
15515 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15516 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15517 return this->implies(I, SE);
15518 });
15519
15520 if (any_of(Preds,
15521 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15522 return true;
15523
15524 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15525 // equal predicates.
15526 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15527 if (!NWrap)
15528 return false;
15529 const Loop *L = NWrap->getExpr()->getLoop();
15530 return any_of(Preds, [&](const SCEVPredicate *I) {
15531 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15532 if (!IWrap)
15533 return false;
15534 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15535 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15536 return RewrittenAR &&
15537 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15538 });
15539}
15540
15542 for (const auto *Pred : Preds)
15543 Pred->print(OS, Depth);
15544}
15545
15546void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15547 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15548 for (const auto *Pred : Set->Preds)
15549 add(Pred, SE);
15550 return;
15551 }
15552
15553 // Implication checks are quadratic in the number of predicates. Stop doing
15554 // them if there are many predicates, as they should be too expensive to use
15555 // anyway at that point.
15556 bool CheckImplies = Preds.size() < 16;
15557
15558 // Only add predicate if it is not already implied by this union predicate.
15559 if (CheckImplies && implies(N, SE))
15560 return;
15561
15562 // Build a new vector containing the current predicates, except the ones that
15563 // are implied by the new predicate N.
15565 for (auto *P : Preds) {
15566 if (CheckImplies && N->implies(P, SE))
15567 continue;
15568 PrunedPreds.push_back(P);
15569 }
15570 Preds = std::move(PrunedPreds);
15571 Preds.push_back(N);
15572}
15573
15575 Loop &L)
15576 : SE(SE), L(L) {
15578 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15579}
15580
15582 for (const SCEV *Op : Ops)
15583 // We do not expect that forgetting cached data for SCEVConstants will ever
15584 // open any prospects for sharpening or introduce any correctness issues,
15585 // so we don't bother storing their dependencies.
15586 if (!isa<SCEVConstant>(Op))
15587 SCEVUsers[Op].insert(User);
15588}
15589
15591 const SCEV *Expr = SE.getSCEV(V);
15592 return getPredicatedSCEV(Expr);
15593}
15594
15596 RewriteEntry &Entry = RewriteMap[Expr];
15597
15598 // If we already have an entry and the version matches, return it.
15599 if (Entry.second && Generation == Entry.first)
15600 return Entry.second;
15601
15602 // We found an entry but it's stale. Rewrite the stale entry
15603 // according to the current predicate.
15604 if (Entry.second)
15605 Expr = Entry.second;
15606
15607 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15608 Entry = {Generation, NewSCEV};
15609
15610 return NewSCEV;
15611}
15612
15614 if (!BackedgeCount) {
15616 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15617 for (const auto *P : Preds)
15618 addPredicate(*P);
15619 }
15620 return BackedgeCount;
15621}
15622
15624 if (!SymbolicMaxBackedgeCount) {
15626 SymbolicMaxBackedgeCount =
15627 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15628 for (const auto *P : Preds)
15629 addPredicate(*P);
15630 }
15631 return SymbolicMaxBackedgeCount;
15632}
15633
15635 if (!SmallConstantMaxTripCount) {
15637 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15638 for (const auto *P : Preds)
15639 addPredicate(*P);
15640 }
15641 return *SmallConstantMaxTripCount;
15642}
15643
15645 if (Preds->implies(&Pred, SE))
15646 return;
15647
15648 Preds = std::make_unique<SCEVUnionPredicate>(Preds->getUnionWith(&Pred, SE));
15649 updateGeneration();
15650}
15651
15654 for (const SCEVPredicate *P : Preds)
15655 addPredicate(*P);
15656}
15657
15659 return *Preds;
15660}
15661
15662void PredicatedScalarEvolution::updateGeneration() {
15663 // If the generation number wrapped recompute everything.
15664 if (++Generation == 0) {
15665 for (auto &II : RewriteMap) {
15666 const SCEV *Rewritten = II.second.second;
15667 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15668 }
15669 }
15670}
15671
15674 const SCEV *Expr = this->getSCEV(V);
15676 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15677
15678 if (!New)
15679 return nullptr;
15680
15681 if (ExtraPreds) {
15682 ExtraPreds->append(NewPreds);
15683 return New;
15684 }
15685
15686 addPredicates(NewPreds);
15687
15688 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15689 return New;
15690}
15691
15694 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15695 Preds(std::make_unique<SCEVUnionPredicate>(*Init.Preds)),
15696 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15697
15699 // For each block.
15700 for (auto *BB : L.getBlocks())
15701 for (auto &I : *BB) {
15702 if (!SE.isSCEVable(I.getType()))
15703 continue;
15704
15705 auto *Expr = SE.getSCEV(&I);
15706 auto II = RewriteMap.find(Expr);
15707
15708 if (II == RewriteMap.end())
15709 continue;
15710
15711 // Don't print things that are not interesting.
15712 if (II->second.second == Expr)
15713 continue;
15714
15715 OS.indent(Depth) << "[PSE]" << I << ":\n";
15716 OS.indent(Depth + 2) << *Expr << "\n";
15717 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15718 }
15719}
15720
15721void ScalarEvolution::LoopGuards::collectPending() {
15722 const Loop *L = PendingLoop;
15723 if (!L)
15724 return;
15725 PendingLoop = nullptr;
15726 BasicBlock *Pred = L->getLoopPredecessor();
15727 if (!Pred)
15728 return;
15730 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15731}
15732
15733void ScalarEvolution::LoopGuards::collectFromPHI(
15737 unsigned Depth) {
15738 if (!SE.isSCEVable(Phi.getType()))
15739 return;
15740
15741 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15742 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15743 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15744 if (!VisitedBlocks.insert(InBlock).second)
15745 return {nullptr, scCouldNotCompute};
15746
15747 // Avoid analyzing unreachable blocks so that we don't get trapped
15748 // traversing cycles with ill-formed dominance or infinite cycles
15749 if (!SE.DT.isReachableFromEntry(InBlock))
15750 return {nullptr, scCouldNotCompute};
15751
15752 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15753 if (Inserted)
15754 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15755 Depth + 1);
15756 auto &RewriteMap = G->second.RewriteMap;
15757 if (RewriteMap.empty())
15758 return {nullptr, scCouldNotCompute};
15759 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15760 if (S == RewriteMap.end())
15761 return {nullptr, scCouldNotCompute};
15762 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15763 if (!SM)
15764 return {nullptr, scCouldNotCompute};
15765 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15766 return {C0, SM->getSCEVType()};
15767 return {nullptr, scCouldNotCompute};
15768 };
15769 auto MergeMinMaxConst = [](MinMaxPattern P1,
15770 MinMaxPattern P2) -> MinMaxPattern {
15771 auto [C1, T1] = P1;
15772 auto [C2, T2] = P2;
15773 if (!C1 || !C2 || T1 != T2)
15774 return {nullptr, scCouldNotCompute};
15775 switch (T1) {
15776 case scUMaxExpr:
15777 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15778 case scSMaxExpr:
15779 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15780 case scUMinExpr:
15781 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15782 case scSMinExpr:
15783 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15784 default:
15785 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15786 }
15787 };
15788 auto P = GetMinMaxConst(0);
15789 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15790 if (!P.first)
15791 break;
15792 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15793 }
15794 if (P.first) {
15795 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15796 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15797 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15798 Guards.RewriteMap.insert({LHS, RHS});
15799 }
15800}
15801
15802// Return a new SCEV that modifies \p Expr to the closest number divides by
15803// \p Divisor and less or equal than Expr. For now, only handle constant
15804// Expr.
15806 const APInt &DivisorVal,
15807 ScalarEvolution &SE) {
15808 const APInt *ExprVal;
15809 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15810 DivisorVal.isNonPositive())
15811 return Expr;
15812 APInt Rem = ExprVal->urem(DivisorVal);
15813 // return the SCEV: Expr - Expr % Divisor
15814 return SE.getConstant(*ExprVal - Rem);
15815}
15816
15817// Return a new SCEV that modifies \p Expr to the closest number divides by
15818// \p Divisor and greater or equal than Expr. For now, only handle constant
15819// Expr.
15820static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15821 const APInt &DivisorVal,
15822 ScalarEvolution &SE) {
15823 const APInt *ExprVal;
15824 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15825 DivisorVal.isNonPositive())
15826 return Expr;
15827 APInt Rem = ExprVal->urem(DivisorVal);
15828 if (Rem.isZero())
15829 return Expr;
15830 // return the SCEV: Expr + Divisor - Expr % Divisor
15831 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15832}
15833
15835 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15838 // If we have LHS == 0, check if LHS is computing a property of some unknown
15839 // SCEV %v which we can rewrite %v to express explicitly.
15841 return false;
15842 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15843 // explicitly express that.
15844 const SCEVUnknown *URemLHS = nullptr;
15845 const SCEV *URemRHS = nullptr;
15846 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15847 return false;
15848
15849 const SCEV *Multiple =
15850 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15851 DivInfo[URemLHS] = Multiple;
15852 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15853 Multiples[URemLHS] = C->getAPInt();
15854 return true;
15855}
15856
15857// Check if the condition is a divisibility guard (A % B == 0).
15858static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15859 ScalarEvolution &SE) {
15860 const SCEV *X, *Y;
15861 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15862}
15863
15864// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15865// recursively. This is done by aligning up/down the constant value to the
15866// Divisor.
15867static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15868 APInt Divisor,
15869 ScalarEvolution &SE) {
15870 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15871 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15872 // the non-constant operand and in \p LHS the constant operand.
15873 auto IsMinMaxSCEVWithNonNegativeConstant =
15874 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15875 const SCEV *&RHS) {
15876 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15877 if (MinMax->getNumOperands() != 2)
15878 return false;
15879 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15880 if (C->getAPInt().isNegative())
15881 return false;
15882 SCTy = MinMax->getSCEVType();
15883 LHS = MinMax->getOperand(0);
15884 RHS = MinMax->getOperand(1);
15885 return true;
15886 }
15887 }
15888 return false;
15889 };
15890
15891 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15892 SCEVTypes SCTy;
15893 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15894 MinMaxRHS))
15895 return MinMaxExpr;
15896 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15897 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15898 auto *DivisibleExpr =
15899 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15900 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15902 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15903 return SE.getMinMaxExpr(SCTy, Ops);
15904}
15905
15906void ScalarEvolution::LoopGuards::collectFromBlock(
15907 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15908 const BasicBlock *Block, const BasicBlock *Pred,
15909 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15910
15912
15913 SmallVector<SCEVUse> ExprsToRewrite;
15914 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15915 const SCEV *RHS,
15916 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15917 const LoopGuards &DivGuards) {
15918 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15919 // replacement SCEV which isn't directly implied by the structure of that
15920 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15921 // legal. See the scoping rules for flags in the header to understand why.
15922
15923 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15924 // and \p FromRewritten are the same (i.e. there has been no rewrite
15925 // registered for \p From), then puts this value in the list of rewritten
15926 // expressions.
15927 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15928 const SCEV *To) {
15929 if (From == FromRewritten)
15930 ExprsToRewrite.push_back(From);
15931 RewriteMap[From] = To;
15932 };
15933
15934 // Checks whether \p S has already been rewritten. In that case returns the
15935 // existing rewrite because we want to chain further rewrites onto the
15936 // already rewritten value. Otherwise returns \p S.
15937 auto GetMaybeRewritten = [&](const SCEV *S) {
15938 return RewriteMap.lookup_or(S, S);
15939 };
15940
15941 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15942 // create this form when combining two checks of the form (X u< C2 + C1) and
15943 // (X >=u C1).
15944 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15945 const SCEV *MatchLHS,
15946 const SCEV *MatchRHS) {
15947 const SCEVConstant *C1;
15948 const SCEVUnknown *LHSUnknown;
15949 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15950 if (!match(MatchLHS,
15951 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15952 !C2)
15953 return false;
15954
15955 auto ExactRegion =
15956 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15957 .sub(C1->getAPInt());
15958
15959 // Tighten the raw range with what we already know about LHSUnknown
15960 // from prior guards recorded in RewriteMap, or from SCEV's own range
15961 // analysis.
15962 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15963 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15965
15966 // Bail if the guard is inconsistent with prior facts, or if the range
15967 // is still not a monotonic non-wrapping interval after tightening.
15968 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15969 ExactRegion.isFullSet())
15970 return false;
15971
15972 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15973 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15974 const SCEV *ClampedLHS =
15975 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15976 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15977 return true;
15978 };
15979 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15980 return;
15981
15982 // Do not apply information for constants or if RHS contains an AddRec.
15984 return;
15985
15986 // If RHS is SCEVUnknown, make sure the information is applied to it.
15988 std::swap(LHS, RHS);
15990 }
15991
15992 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15993 // Apply divisibility information when computing the constant multiple.
15994 const APInt &DividesBy =
15995 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15996
15997 // Collect rewrites for LHS and its transitive operands based on the
15998 // condition.
15999 // For min/max expressions, also apply the guard to its operands:
16000 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16001 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16002 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16003 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16004
16005 // We cannot express strict predicates in SCEV, so instead we replace them
16006 // with non-strict ones against plus or minus one of RHS depending on the
16007 // predicate.
16008 const SCEV *One = SE.getOne(RHS->getType());
16009 switch (Predicate) {
16010 case CmpInst::ICMP_ULT:
16011 if (RHS->getType()->isPointerTy())
16012 return;
16013 RHS = SE.getUMaxExpr(RHS, One);
16014 [[fallthrough]];
16015 case CmpInst::ICMP_SLT: {
16016 RHS = SE.getMinusSCEV(RHS, One);
16017 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16018 break;
16019 }
16020 case CmpInst::ICMP_UGT:
16021 case CmpInst::ICMP_SGT:
16022 RHS = SE.getAddExpr(RHS, One);
16023 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16024 break;
16025 case CmpInst::ICMP_ULE:
16026 case CmpInst::ICMP_SLE:
16027 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16028 break;
16029 case CmpInst::ICMP_UGE:
16030 case CmpInst::ICMP_SGE:
16031 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16032 break;
16033 default:
16034 break;
16035 }
16036
16037 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16038 SmallPtrSet<const SCEV *, 16> Visited;
16039
16040 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16041 append_range(Worklist, S->operands());
16042 };
16043
16044 while (!Worklist.empty()) {
16045 const SCEV *From = Worklist.pop_back_val();
16046 if (isa<SCEVConstant>(From))
16047 continue;
16048 if (!Visited.insert(From).second)
16049 continue;
16050 const SCEV *FromRewritten = GetMaybeRewritten(From);
16051 const SCEV *To = nullptr;
16052
16053 switch (Predicate) {
16054 case CmpInst::ICMP_ULT:
16055 case CmpInst::ICMP_ULE:
16056 To = SE.getUMinExpr(FromRewritten, RHS);
16057 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16058 EnqueueOperands(UMax);
16059 break;
16060 case CmpInst::ICMP_SLT:
16061 case CmpInst::ICMP_SLE:
16062 To = SE.getSMinExpr(FromRewritten, RHS);
16063 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16064 EnqueueOperands(SMax);
16065 break;
16066 case CmpInst::ICMP_UGT:
16067 case CmpInst::ICMP_UGE:
16068 To = SE.getUMaxExpr(FromRewritten, RHS);
16069 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16070 EnqueueOperands(UMin);
16071 break;
16072 case CmpInst::ICMP_SGT:
16073 case CmpInst::ICMP_SGE:
16074 To = SE.getSMaxExpr(FromRewritten, RHS);
16075 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16076 EnqueueOperands(SMin);
16077 break;
16078 case CmpInst::ICMP_EQ:
16080 To = RHS;
16081 break;
16082 case CmpInst::ICMP_NE:
16083 if (match(RHS, m_scev_Zero())) {
16084 const SCEV *OneAlignedUp =
16085 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16086 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16087 } else {
16088 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16089 // but creating the subtraction eagerly is expensive. Track the
16090 // inequalities in a separate map, and materialize the rewrite lazily
16091 // when encountering a suitable subtraction while re-writing.
16092 if (LHS->getType()->isPointerTy()) {
16093 LHS = SE.getPtrToAddrExpr(LHS);
16094 RHS = SE.getPtrToAddrExpr(RHS);
16096 break;
16097 }
16098 const SCEVConstant *C;
16099 const SCEV *A, *B;
16102 RHS = A;
16103 LHS = B;
16104 }
16105 if (LHS > RHS)
16106 std::swap(LHS, RHS);
16107 Guards.NotEqual.insert({LHS, RHS});
16108 continue;
16109 }
16110 break;
16111 default:
16112 break;
16113 }
16114
16115 if (To)
16116 AddRewrite(From, FromRewritten, To);
16117 }
16118 };
16119
16121 // First, collect information from assumptions dominating the loop.
16122 for (auto &AssumeVH : SE.AC.assumptions()) {
16123 if (!AssumeVH)
16124 continue;
16125 auto *AssumeI = cast<CallInst>(AssumeVH);
16126 if (!SE.DT.dominates(AssumeI, Block))
16127 continue;
16128 Terms.emplace_back(AssumeI->getOperand(0), true);
16129 }
16130
16131 // Second, collect information from llvm.experimental.guards dominating the loop.
16132 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16133 SE.F.getParent(), Intrinsic::experimental_guard);
16134 if (GuardDecl)
16135 for (const auto *GU : GuardDecl->users())
16136 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16137 if (Guard->getFunction() == Block->getParent() &&
16138 SE.DT.dominates(Guard, Block))
16139 Terms.emplace_back(Guard->getArgOperand(0), true);
16140
16141 // Third, collect conditions from dominating branches. Starting at the loop
16142 // predecessor, climb up the predecessor chain, as long as there are
16143 // predecessors that can be found that have unique successors leading to the
16144 // original header. If there is no such predecessor, continue at the
16145 // immediate dominator.
16146 // TODO: share this logic with isLoopEntryGuardedByCond.
16147 unsigned NumCollectedConditions = 0;
16148 unsigned NumDomTreeSteps = 0;
16150 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16151 for (;; Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16152 if (!Pair.first) {
16153 // At the first block without a unique predecessor, try to build
16154 // conditions for its phis by merging those of their incoming blocks.
16155 if (!NumDomTreeSteps && Depth < MaxLoopGuardCollectionDepth) {
16156 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16157 for (auto &Phi : Pair.second->phis())
16158 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16159 }
16160 const DomTreeNode *IDom = SE.DT.getNode(Pair.second)->getIDom();
16161 if (!IDom || ++NumDomTreeSteps > MaxGuardDomTreeSteps)
16162 break;
16163 Pair.first = IDom->getBlock();
16164 continue;
16165 }
16166 VisitedBlocks.insert(Pair.second);
16167 const CondBrInst *LoopEntryPredicate =
16168 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16169 if (!LoopEntryPredicate)
16170 continue;
16171
16172 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16173 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16174 NumCollectedConditions++;
16175
16176 // If we are recursively collecting guards stop after 2
16177 // conditions to limit compile-time impact for now.
16178 if (Depth > 0 && NumCollectedConditions == 2)
16179 break;
16180 }
16181
16182 // Now apply the information from the collected conditions to
16183 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16184 // earliest conditions is processed first, except guards with divisibility
16185 // information, which are moved to the back. This ensures the SCEVs with the
16186 // shortest dependency chains are constructed first.
16188 GuardsToProcess;
16189 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16190 SmallVector<Value *, 8> Worklist;
16191 SmallPtrSet<Value *, 8> Visited;
16192 Worklist.push_back(Term);
16193 while (!Worklist.empty()) {
16194 Value *Cond = Worklist.pop_back_val();
16195 if (!Visited.insert(Cond).second)
16196 continue;
16197
16198 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16199 auto Predicate =
16200 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16201 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16202 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16203 // If LHS is a constant, apply information to the other expression.
16204 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16205 // can improve results.
16206 if (isa<SCEVConstant>(LHS)) {
16207 std::swap(LHS, RHS);
16209 }
16210 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16211 continue;
16212 }
16213
16214 Value *L, *R;
16215 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16216 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16217 Worklist.push_back(L);
16218 Worklist.push_back(R);
16219 }
16220 }
16221 }
16222
16223 // Process divisibility guards in reverse order to populate DivGuards early.
16224 DenseMap<const SCEV *, APInt> Multiples;
16225 LoopGuards DivGuards(SE);
16226 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16227 if (!isDivisibilityGuard(LHS, RHS, SE))
16228 continue;
16229 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16230 Multiples, SE);
16231 }
16232
16233 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16234 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16235
16236 // Apply divisibility information last. This ensures it is applied to the
16237 // outermost expression after other rewrites for the given value.
16238 for (const auto &[K, Divisor] : Multiples) {
16239 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16240 Guards.RewriteMap[K] =
16242 Guards.rewrite(K), Divisor, SE),
16243 DivisorSCEV),
16244 DivisorSCEV);
16245 ExprsToRewrite.push_back(K);
16246 }
16247
16248 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16249 // the replacement expressions are contained in the ranges of the replaced
16250 // expressions.
16251 Guards.PreserveNUW = true;
16252 Guards.PreserveNSW = true;
16253 for (const SCEV *Expr : ExprsToRewrite) {
16254 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16255 Guards.PreserveNUW &=
16256 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16257 Guards.PreserveNSW &=
16258 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16259 }
16260
16261 // Now that all rewrite information is collect, rewrite the collected
16262 // expressions with the information in the map. This applies information to
16263 // sub-expressions.
16264 if (ExprsToRewrite.size() > 1) {
16265 for (const SCEV *Expr : ExprsToRewrite) {
16266 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16267 Guards.RewriteMap.erase(Expr);
16268 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16269 }
16270 }
16271}
16272
16274 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16275 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16276 /// replacement is loop invariant in the loop of the AddRec.
16277 class SCEVLoopGuardRewriter
16278 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16281
16282 SCEVFlags FlagMask = SCEV::FlagNone;
16283
16284 public:
16285 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16286 const ScalarEvolution::LoopGuards &Guards)
16287 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16288 NotEqual(Guards.NotEqual) {
16289 if (Guards.PreserveNUW)
16290 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16291 if (Guards.PreserveNSW)
16292 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16293 }
16294
16295 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16296
16297 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16298 return Map.lookup_or(Expr, Expr);
16299 }
16300
16301 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16302 if (const SCEV *S = Map.lookup(Expr))
16303 return S;
16305 Expr);
16306 }
16307
16308 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16309 if (const SCEV *S = Map.lookup(Expr))
16310 return S;
16311
16312 // If we didn't find the extact ZExt expr in the map, check if there's
16313 // an entry for a smaller ZExt we can use instead.
16314 Type *Ty = Expr->getType();
16315 const SCEV *Op = Expr->getOperand(0);
16316 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16317 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16318 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16319 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16320 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16321 if (const SCEV *S = Map.lookup(NarrowExt))
16322 return SE.getZeroExtendExpr(S, Ty);
16323 Bitwidth = Bitwidth / 2;
16324 }
16325
16327 Expr);
16328 }
16329
16330 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16331 if (const SCEV *S = Map.lookup(Expr))
16332 return S;
16334 Expr);
16335 }
16336
16337 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16338 if (const SCEV *S = Map.lookup(Expr))
16339 return S;
16341 }
16342
16343 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16344 if (const SCEV *S = Map.lookup(Expr))
16345 return S;
16347 }
16348
16349 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16350 if (const SCEV *S = Map.lookup(Expr))
16351 return S;
16352
16353 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16354 // return UMax(S, 1).
16355 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16356 SCEVUse LHS, RHS;
16357 if (MatchBinarySub(S, LHS, RHS)) {
16358 if (LHS > RHS)
16359 std::swap(LHS, RHS);
16360 if (NotEqual.contains({LHS, RHS})) {
16361 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16362 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16363 return SE.getUMaxExpr(OneAlignedUp, S);
16364 }
16365 }
16366 return nullptr;
16367 };
16368
16369 // Check if Expr itself is a subtraction pattern with guard info.
16370 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16371 return Rewritten;
16372
16373 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16374 // (Const + A + B). There may be guard info for A + B, and if so, apply
16375 // it.
16376 // TODO: Could more generally apply guards to Add sub-expressions.
16377 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16378 if (Expr->getNumOperands() == 3) {
16379 const SCEV *Add =
16380 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16381 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16382 return SE.getAddExpr(
16383 Expr->getOperand(0), Rewritten,
16384 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16385 if (const SCEV *S = Map.lookup(Add))
16386 return SE.getAddExpr(Expr->getOperand(0), S);
16387 }
16388
16389 // For expressions of the form (Const + A), check if we have guard info
16390 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16391 // sure we don't lose information when rewriting expressions based on
16392 // back-edge taken counts in some cases.
16393 if (Expr->getNumOperands() == 2) {
16394 const SCEV *S = nullptr;
16395 // Handle (-1 + 1 + A) without constructing SCEVs.
16396 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16397 S = Map.lookup(Expr->getOperand(1));
16398 } else {
16399 const SCEV *NewC =
16400 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16401 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16402 }
16403 if (S)
16404 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16405 }
16406 }
16408 bool Changed = false;
16409 for (SCEVUse Op : Expr->operands()) {
16410 Operands.push_back(
16412 Changed |= Op != Operands.back();
16413 }
16414 // We are only replacing operands with equivalent values, so transfer the
16415 // flags from the original expression.
16416 return !Changed ? Expr
16417 : SE.getAddExpr(Operands,
16419 Expr->getNoWrapFlags(), FlagMask));
16420 }
16421
16422 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16424 bool Changed = false;
16425 for (SCEVUse Op : Expr->operands()) {
16426 Operands.push_back(
16428 Changed |= Op != Operands.back();
16429 }
16430 // We are only replacing operands with equivalent values, so transfer the
16431 // flags from the original expression.
16432 return !Changed ? Expr
16433 : SE.getMulExpr(Operands,
16435 Expr->getNoWrapFlags(), FlagMask));
16436 }
16437 };
16438
16439 if (RewriteMap.empty() && NotEqual.empty())
16440 return Expr;
16441
16442 SCEVLoopGuardRewriter Rewriter(SE, *this);
16443 return Rewriter.visit(Expr);
16444}
16445
16446const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16447 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16448 return applyLoopGuards(Expr, Guards);
16449}
16450
16452 LoopGuards &Guards) {
16453 // Loop guards never rewrite constants and AddRecs, so there is no need to
16454 // collect pending guards for them.
16456 return Expr;
16457 if (Guards.PendingLoop)
16458 Guards.collectPending();
16459 return Guards.rewrite(Expr);
16460}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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:682
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool hasNoUnsignedWrap(BinaryOperator &I)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
SI optimize exec mask operations pre RA
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
This file contains some templates that are useful if you are working with the STL at all.
This file provides utility classes that use RAII to save and restore values.
bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, SCEVTypes RootKind)
static cl::opt< unsigned > MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, cl::desc("Max coefficients in AddRec during evolving"), cl::init(8))
static cl::opt< unsigned > RangeIterThreshold("scev-range-iter-threshold", cl::Hidden, cl::desc("Threshold for switching to iteratively computing SCEV ranges"), cl::init(32))
static const Loop * isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI)
static unsigned getConstantTripCount(const SCEVConstant *ExitCount)
static int CompareValueComplexity(const LoopInfo *const LI, Value *LV, Value *RV, unsigned Depth)
Compare the two values LV and RV in terms of their "complexity" where "complexity" is a partial (and ...
static const SCEV * getNextSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static void PushLoopPHIs(const Loop *L, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push PHI nodes in the header of the given loop onto the given Worklist.
static void insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static bool IsKnownPredicateViaAddRecMonotonicity(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true because one of them is an AddRec that is known not to go below its own start val...
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L, const TargetLibraryInfo *TLI)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static bool canConstantFold(const Instruction *I, const TargetLibraryInfo *TLI)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, const TargetLibraryInfo *TLI, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static SCEVFlags getNoWrapFlagsForGEP(GEPOperator *GEP, const SCEV *Accum, ScalarEvolution &SE)
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static 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 CollectAddOperandsWithScales(SmallDenseMap< const SCEV *, 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 bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static SCEVFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEVFlags Flags)
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static int CompareSCEVComplexity(const LoopInfo *const LI, SCEVUse LHS, SCEVUse RHS, DominatorTree &DT)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool canConstantEvolve(Instruction *I, const Loop *L, const TargetLibraryInfo *TLI)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static cl::opt< unsigned > MaxGuardDomTreeSteps("scalar-evolution-max-guard-dom-tree-steps", cl::Hidden, cl::desc("Maximum number of immediate dominator steps taken when " "collecting loop guards"), cl::init(8))
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CtxI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitAddExpr(const SCEVAddExpr *Expr)
const SCEV * visit(const SCEV *S)
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:357
unsigned countTrailingZeros() const
Definition APInt.h:1667
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:337
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
AnalysisUsage & addRequiredTransitive()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
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:463
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
bool isSingleElement() const
Return true if this set contains exactly one member.
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 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:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
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:762
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:678
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:793
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:779
void swap(DenseMapBase &RHS)
Definition DenseMap.h:977
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a single (scalar) element from a VectorType value.
This instruction extracts a struct member or array element value from an aggregate value.
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:123
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
void AddInteger(signed I)
Definition FoldingSet.h:190
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionPass(char &pid)
Definition Pass.h:314
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This instruction inserts a single (scalar) element into a VectorType value.
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
unsigned getLoopDepth(const BlockT *BB) const
Return the loop nesting level of the specified block.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:68
Metadata node.
Definition Metadata.h:1081
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI SCEVUse getExitValue(ScalarEvolution &SE) const
Return the value of this recurrences when its loop exits, i.e.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(SCEVFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
SCEVFlags getNoWrapFlags(SCEVFlags Mask=FlagsNoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr)
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEVFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
static constexpr auto FlagsNoWrapMask
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize, Type *Ty)
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * getCanonical() const
Return the canonical SCEV.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
static constexpr auto FlagNone
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LoopGuards collectOnDemand(const Loop *L, ScalarEvolution &SE)
Return loop guards for loop L, which are collected on first use.
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
static bool hasFlags(SCEVFlags Flags, SCEVFlags TestFlags)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getZeroExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< SCEVUse > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static SCEVFlags setFlags(SCEVFlags Flags, SCEVFlags OnFlags)
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetValues(ArrayRef< Value * > Values)
Batched forgetValue: invalidates all Values in one shared def-use walk, avoiding the redundant re-tra...
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, SCEVUse Op, Type *Ty)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI SCEVUse getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEVFlagsPair Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Check that S is a multiple of M.
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
static SCEVFlags clearFlags(SCEVFlags Flags, SCEVFlags OffFlags)
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
static SCEVFlags maskFlags(SCEVFlags Flags, SCEVFlags Mask)
Convenient SCEVFlags manipulation.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI const SCEV * getZeroExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
LLVM_ABI std::optional< SCEVFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getAnyExtendExpr(SCEVUse Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getSignExtendExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI SCEVUse getSCEVAtExit(const SCEV *S, const Loop *L, const BasicBlock *ExitingBlock)
Return the SCEV expression at the specified loop exit.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEVFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI const SCEV * getSignExtendExprImpl(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI std::optional< APInt > SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, unsigned RangeWidth)
Let q(n) = An^2 + Bn + C, and BW = bit width of the value range (e.g.
Definition APInt.cpp:2850
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ BinaryOp
One of the operands is a binary op.
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2127
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:381
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
SCEVFlags
SCEVFlags are bitfield indices into SCEV's SubclassData.
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
The no-wrap flags to apply when creating a SCEV expression, to the expression and use respectively.
SCEVFlags ExprFlags
Flags applied directly to a SCEV expression, must be valid wherever the expression is valid.
SCEVFlags UseFlags
Flags only applied to a SCEVUse.
static SCEVUseT getCommon(SCEVUseT A, SCEVUseT B)
SCEVPtrT getPointer() const
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.