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
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
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
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 BaseNW = GEP->getNoWrapFlags();
3767 GEPNoWrapFlags OffsetNW = GEP->getNoWrapFlags();
3768 if (BaseNW != GEPNoWrapFlags::none()) {
3769 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3770 // but to do that, we have to ensure that said flag is valid in the entire
3771 // defined scope of the SCEV.
3772 // TODO: non-instructions have global scope. We might be able to prove
3773 // some global scope cases
3774 auto *GEPI = dyn_cast<Instruction>(GEP);
3775 if (!GEPI || !isSCEVExprNeverPoison(GEPI)) {
3776 BaseNW = OffsetNW = GEPNoWrapFlags::none();
3777 } else if (any_of(IndexExprs, [&](const SCEVUse &IndexExpr) {
3778 const SCEV *Idx = IndexExpr;
3779 return !isa<SCEVConstant>(Idx) &&
3780 !isGuaranteedToTransferExecutionTo(
3781 getDefiningScopeBound({Idx}), GEPI);
3782 })) {
3783 // The offset flags should not take into account the base pointer
3784 // defining scope, as the offset only depends on the indices. Thus,
3785 // derive the scope bound for the offset flags from each index operand
3786 // individually.
3787 OffsetNW = GEPNoWrapFlags::none();
3788 }
3789 }
3790
3791 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), BaseNW,
3792 OffsetNW);
3793}
3794
3796 ArrayRef<SCEVUse> IndexExprs,
3797 Type *SrcElementTy,
3798 GEPNoWrapFlags BaseNW,
3799 GEPNoWrapFlags OffsetNW) {
3800 SCEVFlags OffsetWrap = SCEV::FlagNone;
3801 if (OffsetNW.hasNoUnsignedSignedWrap())
3802 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3803 if (OffsetNW.hasNoUnsignedWrap())
3804 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3805
3806 Type *CurTy = BaseExpr->getType();
3807 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3808 bool FirstIter = true;
3810 for (SCEVUse IndexExpr : IndexExprs) {
3811 // Compute the (potentially symbolic) offset in bytes for this index.
3812 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3813 // For a struct, add the member offset.
3814 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3815 unsigned FieldNo = Index->getZExtValue();
3816 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3817 Offsets.push_back(FieldOffset);
3818
3819 // Update CurTy to the type of the field at Index.
3820 CurTy = STy->getTypeAtIndex(Index);
3821 } else {
3822 // Update CurTy to its element type.
3823 if (FirstIter) {
3824 assert(isa<PointerType>(CurTy) &&
3825 "The first index of a GEP indexes a pointer");
3826 CurTy = SrcElementTy;
3827 FirstIter = false;
3828 } else {
3829 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
3830 }
3831 // For an array, add the element offset, explicitly scaled.
3832 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3833 // Getelementptr indices are signed.
3834 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3835
3836 // Multiply the index by the element size to compute the element offset.
3837 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3838 Offsets.push_back(LocalOffset);
3839 }
3840 }
3841
3842 // Handle degenerate case of GEP without offsets.
3843 if (Offsets.empty())
3844 return BaseExpr;
3845
3846 // Add the offsets together, assuming nsw if inbounds.
3847 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3848 // Add the base address and the offset. We cannot use the nsw flag, as the
3849 // base address is unsigned. However, if we know that the offset is
3850 // non-negative, we can use nuw.
3851 bool NUW = BaseNW.hasNoUnsignedWrap() ||
3853 SCEVFlags BaseWrap = NUW ? SCEV::FlagNUW : SCEV::FlagNone;
3854 const SCEV *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3855 assert(BaseExpr->getType() == GEPExpr->getType() &&
3856 "GEP should not change type mid-flight.");
3857 return GEPExpr;
3858}
3859
3860SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3862 const Loop *L) {
3863 assert((SCEVType != scAddRecExpr || L) &&
3864 "L must be passed to find existing AddRecs");
3866 ID.AddInteger(SCEVType);
3867 for (SCEVUse Op : Ops)
3868 ID.AddPointer(Op.getOpaqueValue());
3869 if (L)
3870 ID.AddPointer(L);
3872 return UniqueSCEVs.lookup(ID, Token);
3873}
3874
3875const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3876 SCEVFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagNone;
3877 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3878}
3879
3882 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
3883 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3884 if (Ops.size() == 1) return Ops[0];
3885#ifndef NDEBUG
3886 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3887 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
3888 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3889 "Operand types don't match!");
3890 assert(Ops[0]->getType()->isPointerTy() ==
3891 Ops[i]->getType()->isPointerTy() &&
3892 "min/max should be consistently pointerish");
3893 }
3894#endif
3895
3896 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3897 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3898
3900 *this, LI, DT, Ops,
3901 [&](const APInt &C1, const APInt &C2) {
3902 switch (Kind) {
3903 case scSMaxExpr:
3904 return APIntOps::smax(C1, C2);
3905 case scSMinExpr:
3906 return APIntOps::smin(C1, C2);
3907 case scUMaxExpr:
3908 return APIntOps::umax(C1, C2);
3909 case scUMinExpr:
3910 return APIntOps::umin(C1, C2);
3911 default:
3912 llvm_unreachable("Unknown SCEV min/max opcode");
3913 }
3914 },
3915 [&](const APInt &C) {
3916 // identity
3917 if (IsMax)
3918 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3919 else
3920 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3921 },
3922 [&](const APInt &C) {
3923 // absorber
3924 if (IsMax)
3925 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
3926 else
3927 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
3928 });
3929 if (Folded)
3930 return Folded;
3931
3932 // Check if we have created the same expression before.
3933 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
3934 return S;
3935 }
3936
3937 // Find the first operation of the same kind
3938 unsigned Idx = 0;
3939 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3940 ++Idx;
3941
3942 // Check to see if one of the operands is of the same kind. If so, expand its
3943 // operands onto our operand list, and recurse to simplify.
3944 if (Idx < Ops.size()) {
3945 bool DeletedAny = false;
3946 while (Ops[Idx]->getSCEVType() == Kind) {
3947 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3948 Ops.erase(Ops.begin()+Idx);
3949 append_range(Ops, SMME->operands());
3950 DeletedAny = true;
3951 }
3952
3953 if (DeletedAny)
3954 return getMinMaxExpr(Kind, Ops);
3955 }
3956
3957 // Okay, check to see if the same value occurs in the operand list twice. If
3958 // so, delete one. Since we sorted the list, these values are required to
3959 // be adjacent.
3964 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3965 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3966 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3967 if (SCEVUse Common = SCEVUse::getCommon(Ops[i], Ops[i + 1]))
3968 Ops[i] = Ops[i + 1] = Common;
3969 if (Ops[i] == Ops[i + 1] ||
3970 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3971 // X op Y op Y --> X op Y
3972 // X op Y --> X, if we know X, Y are ordered appropriately
3973 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3974 --i;
3975 --e;
3976 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3977 Ops[i + 1])) {
3978 // X op Y --> Y, if we know X, Y are ordered appropriately
3979 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3980 --i;
3981 --e;
3982 }
3983 }
3984
3985 if (Ops.size() == 1) return Ops[0];
3986
3987 assert(!Ops.empty() && "Reduced smax down to nothing!");
3988
3989 // Okay, it looks like we really DO need an expr. Check to see if we
3990 // already have one, otherwise create a new one.
3992 ID.AddInteger(Kind);
3993 for (SCEVUse Op : Ops)
3994 ID.AddPointer(Op.getOpaqueValue());
3996 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
3997 if (ExistingSCEV)
3998 return ExistingSCEV;
3999 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4001 SCEV *S = new (SCEVAllocator)
4002 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4003
4004 UniqueSCEVs.insert(S, Token);
4005 S->computeAndSetCanonical(*this);
4006 registerUser(S, Ops);
4007 return S;
4008}
4009
4010namespace {
4011
4012class SCEVSequentialMinMaxDeduplicatingVisitor final
4013 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4014 std::optional<const SCEV *>> {
4015 using RetVal = std::optional<const SCEV *>;
4016
4017 ScalarEvolution &SE;
4018 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4019 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4021
4022 bool canRecurseInto(SCEVTypes Kind) const {
4023 // We can only recurse into the SCEV expression of the same effective type
4024 // as the type of our root SCEV expression.
4025 return RootKind == Kind || NonSequentialRootKind == Kind;
4026 };
4027
4028 RetVal visit(const SCEV *S) {
4029 // Has the whole operand been seen already?
4030 if (!SeenOps.insert(S).second)
4031 return std::nullopt;
4033 SCEVTypes Kind = S->getSCEVType();
4034
4035 if (!canRecurseInto(Kind))
4036 return S;
4037
4038 auto *NAry = cast<SCEVNAryExpr>(S);
4039 SmallVector<SCEVUse> NewOps;
4040 bool Changed = visit(Kind, NAry->operands(), NewOps);
4041
4042 if (!Changed)
4043 return S;
4044 if (NewOps.empty())
4045 return std::nullopt;
4046
4048 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4049 : SE.getMinMaxExpr(Kind, NewOps);
4050 }
4051 return S;
4052 }
4053
4054public:
4055 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4056 SCEVTypes RootKind)
4057 : SE(SE), RootKind(RootKind),
4058 NonSequentialRootKind(
4059 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4060 RootKind)) {}
4061
4062 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4063 SmallVectorImpl<SCEVUse> &NewOps) {
4064 bool Changed = false;
4066 Ops.reserve(OrigOps.size());
4067
4068 for (const SCEV *Op : OrigOps) {
4069 RetVal NewOp = visit(Op);
4070 if (NewOp != Op)
4071 Changed = true;
4072 if (NewOp)
4073 Ops.emplace_back(*NewOp);
4074 }
4075
4076 if (Changed)
4077 NewOps = std::move(Ops);
4078 return Changed;
4079 }
4080};
4081
4082} // namespace
4083
4085 switch (Kind) {
4086 case scConstant:
4087 case scVScale:
4088 case scTruncate:
4089 case scZeroExtend:
4090 case scSignExtend:
4091 case scPtrToAddr:
4092 case scAddExpr:
4093 case scMulExpr:
4094 case scUDivExpr:
4095 case scAddRecExpr:
4096 case scUMaxExpr:
4097 case scSMaxExpr:
4098 case scUMinExpr:
4099 case scSMinExpr:
4100 case scUnknown:
4101 // If any operand is poison, the whole expression is poison.
4102 return true;
4104 // FIXME: if the *first* operand is poison, the whole expression is poison.
4105 return false; // Pessimistically, say that it does not propagate poison.
4106 case scCouldNotCompute:
4107 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4108 }
4109 llvm_unreachable("Unknown SCEV kind!");
4110}
4111
4112namespace {
4113// The only way poison may be introduced in a SCEV expression is from a
4114// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4115// not SCEVConstant). Notably, SCEVFlags on SCEV nodes can *not*
4116// introduce poison -- they encode guaranteed, non-speculated knowledge.
4117//
4118// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4119// with the notable exception of umin_seq, where only poison from the first
4120// operand is (unconditionally) propagated.
4121struct SCEVPoisonCollector {
4122 bool LookThroughMaybePoisonBlocking;
4123 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4124 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4125 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4126
4127 bool follow(const SCEV *S) {
4128 if (!LookThroughMaybePoisonBlocking &&
4130 return false;
4131
4132 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4133 if (!isGuaranteedNotToBePoison(SU->getValue()))
4134 MaybePoison.insert(SU);
4135 }
4136 return true;
4137 }
4138 bool isDone() const { return false; }
4139};
4140} // namespace
4141
4142/// Return true if V is poison given that AssumedPoison is already poison.
4143static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4144 // First collect all SCEVs that might result in AssumedPoison to be poison.
4145 // We need to look through potentially poison-blocking operations here,
4146 // because we want to find all SCEVs that *might* result in poison, not only
4147 // those that are *required* to.
4148 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4149 visitAll(AssumedPoison, PC1);
4150
4151 // AssumedPoison is never poison. As the assumption is false, the implication
4152 // is true. Don't bother walking the other SCEV in this case.
4153 if (PC1.MaybePoison.empty())
4154 return true;
4155
4156 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4157 // as well. We cannot look through potentially poison-blocking operations
4158 // here, as their arguments only *may* make the result poison.
4159 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4160 visitAll(S, PC2);
4161
4162 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4163 // it will also make S poison by being part of PC2.MaybePoison.
4164 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4165}
4166
4168 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4169 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4170 visitAll(S, PC);
4171 for (const SCEVUnknown *SU : PC.MaybePoison)
4172 Result.insert(SU->getValue());
4173}
4174
4176 const SCEV *S, Instruction *I,
4177 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4178 // If the instruction cannot be poison, it's always safe to reuse.
4180 return true;
4181
4182 // Otherwise, it is possible that I is more poisonous that S. Collect the
4183 // poison-contributors of S, and then check whether I has any additional
4184 // poison-contributors. Poison that is contributed through poison-generating
4185 // flags is handled by dropping those flags instead.
4187 getPoisonGeneratingValues(PoisonVals, S);
4188
4189 SmallVector<Value *> Worklist;
4191 Worklist.push_back(I);
4192 unsigned NumVisitedInsts = 0;
4193 const unsigned InstLimit = std::max<unsigned>(16, S->getExpressionSize());
4194 while (!Worklist.empty()) {
4195 Value *V = Worklist.pop_back_val();
4196 if (!Visited.insert(V).second)
4197 continue;
4198
4199 // Either the value can't be poison, or the S would also be poison if it
4200 // is.
4201 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4202 continue;
4203
4204 // Avoid walking large instruction graphs.
4205 if (++NumVisitedInsts > InstLimit)
4206 return false;
4207
4208 auto *I = dyn_cast<Instruction>(V);
4209 if (!I)
4210 return false;
4211
4212 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4213 // can't replace an arbitrary add with disjoint or, even if we drop the
4214 // flag. We would need to convert the or into an add.
4215 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4216 if (PDI->isDisjoint())
4217 return false;
4218
4219 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4220 // because SCEV currently assumes it can't be poison. Remove this special
4221 // case once we proper model when vscale can be poison.
4222 if (auto *II = dyn_cast<IntrinsicInst>(I);
4223 II && II->getIntrinsicID() == Intrinsic::vscale)
4224 continue;
4225
4226 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4227 return false;
4228
4229 // If the instruction can't create poison, we can recurse to its operands.
4230 if (I->hasPoisonGeneratingAnnotations())
4231 DropPoisonGeneratingInsts.push_back(I);
4232
4233 llvm::append_range(Worklist, I->operands());
4234 }
4235 return true;
4236}
4237
4238const SCEV *
4241 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4242 "Not a SCEVSequentialMinMaxExpr!");
4243 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4244 if (Ops.size() == 1)
4245 return Ops[0];
4246#ifndef NDEBUG
4247 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4248 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4249 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4250 "Operand types don't match!");
4251 assert(Ops[0]->getType()->isPointerTy() ==
4252 Ops[i]->getType()->isPointerTy() &&
4253 "min/max should be consistently pointerish");
4254 }
4255#endif
4256
4257 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4258 // so we can *NOT* do any kind of sorting of the expressions!
4259
4260 // Check if we have created the same expression before.
4261 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4262 return S;
4263
4264 // FIXME: there are *some* simplifications that we can do here.
4265
4266 // Keep only the first instance of an operand.
4267 {
4268 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4269 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4270 if (Changed)
4271 return getSequentialMinMaxExpr(Kind, Ops);
4272 }
4273
4274 // Check to see if one of the operands is of the same kind. If so, expand its
4275 // operands onto our operand list, and recurse to simplify.
4276 {
4277 unsigned Idx = 0;
4278 bool DeletedAny = false;
4279 while (Idx < Ops.size()) {
4280 if (Ops[Idx]->getSCEVType() != Kind) {
4281 ++Idx;
4282 continue;
4283 }
4284 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4285 Ops.erase(Ops.begin() + Idx);
4286 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4287 SMME->operands().end());
4288 DeletedAny = true;
4289 }
4290
4291 if (DeletedAny)
4292 return getSequentialMinMaxExpr(Kind, Ops);
4293 }
4294
4295 const SCEV *SaturationPoint;
4297 switch (Kind) {
4299 SaturationPoint = getZero(Ops[0]->getType());
4300 Pred = ICmpInst::ICMP_ULE;
4301 break;
4302 default:
4303 llvm_unreachable("Not a sequential min/max type.");
4304 }
4305
4306 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4307 if (!isGuaranteedNotToCauseUB(Ops[i]))
4308 continue;
4309 // We can replace %x umin_seq %y with %x umin %y if either:
4310 // * %y being poison implies %x is also poison.
4311 // * %x cannot be the saturating value (e.g. zero for umin).
4312 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4313 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4314 SaturationPoint)) {
4315 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4316 Ops[i - 1] = getMinMaxExpr(
4318 SeqOps);
4319 Ops.erase(Ops.begin() + i);
4320 return getSequentialMinMaxExpr(Kind, Ops);
4321 }
4322 // Fold %x umin_seq %y to %x if %x ule %y.
4323 // TODO: We might be able to prove the predicate for a later operand.
4324 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4325 Ops.erase(Ops.begin() + i);
4326 return getSequentialMinMaxExpr(Kind, Ops);
4327 }
4328 }
4329
4330 // Okay, it looks like we really DO need an expr. Check to see if we
4331 // already have one, otherwise create a new one.
4333 ID.AddInteger(Kind);
4334 for (SCEVUse Op : Ops)
4335 ID.AddPointer(Op.getOpaqueValue());
4337 const SCEV *ExistingSCEV = UniqueSCEVs.lookup(ID, Token);
4338 if (ExistingSCEV)
4339 return ExistingSCEV;
4340
4341 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4343 SCEV *S = new (SCEVAllocator)
4344 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4345
4346 UniqueSCEVs.insert(S, Token);
4347 S->computeAndSetCanonical(*this);
4348 registerUser(S, Ops);
4349 return S;
4350}
4351
4356
4360
4365
4369
4374
4378
4380 bool Sequential) {
4381 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4382 return getUMinExpr(Ops, Sequential);
4383}
4384
4390
4391const SCEV *
4393 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4394 if (Size.isScalable())
4395 Res = getMulExpr(Res, getVScale(IntTy));
4396 return Res;
4397}
4398
4400 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4401}
4402
4404 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4405}
4406
4408 StructType *STy,
4409 unsigned FieldNo) {
4410 // We can bypass creating a target-independent constant expression and then
4411 // folding it back into a ConstantInt. This is just a compile-time
4412 // optimization.
4413 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4414 assert(!SL->getSizeInBits().isScalable() &&
4415 "Cannot get offset for structure containing scalable vector types");
4416 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4417}
4418
4420 // Don't attempt to do anything other than create a SCEVUnknown object
4421 // here. createSCEV only calls getUnknown after checking for all other
4422 // interesting possibilities, and any other code that calls getUnknown
4423 // is doing so in order to hide a value from SCEV canonicalization.
4424
4427 ID.AddPointer(V);
4429 if (SCEV *S = UniqueSCEVs.lookup(ID, Token)) {
4430 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4431 "Stale SCEVUnknown in uniquing map!");
4432 return S;
4433 }
4434 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4435 FirstUnknown, NextUnknownOrderID++);
4436 FirstUnknown = cast<SCEVUnknown>(S);
4437 UniqueSCEVs.insert(S, Token);
4438 S->computeAndSetCanonical(*this);
4439 return S;
4440}
4441
4442//===----------------------------------------------------------------------===//
4443// Basic SCEV Analysis and PHI Idiom Recognition Code
4444//
4445
4446/// Test if values of the given type are analyzable within the SCEV
4447/// framework. This primarily includes integer types, and it can optionally
4448/// include pointer types if the ScalarEvolution class has access to
4449/// target-specific information.
4451 // Integers and pointers are always SCEVable.
4452 return Ty->isIntOrPtrTy();
4453}
4454
4455/// Return the size in bits of the specified type, for which isSCEVable must
4456/// return true.
4458 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4459 if (Ty->isPointerTy())
4461 return getDataLayout().getTypeSizeInBits(Ty);
4462}
4463
4464/// Return a type with the same bitwidth as the given type and which represents
4465/// how SCEV will treat the given type, for which isSCEVable must return
4466/// true. For pointer types, this is the pointer index sized integer type.
4468 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4469
4470 if (Ty->isIntegerTy())
4471 return Ty;
4472
4473 // The only other support type is pointer.
4474 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4475 return getDataLayout().getIndexType(Ty);
4476}
4477
4479 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4480}
4481
4483 const SCEV *B) {
4484 /// For a valid use point to exist, the defining scope of one operand
4485 /// must dominate the other.
4486 bool PreciseA, PreciseB;
4487 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4488 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4489 if (!PreciseA || !PreciseB)
4490 // Can't tell.
4491 return false;
4492 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4493 DT.dominates(ScopeB, ScopeA);
4494}
4495
4497 return CouldNotCompute.get();
4498}
4499
4500bool ScalarEvolution::checkValidity(const SCEV *S) const {
4501 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4502 auto *SU = dyn_cast<SCEVUnknown>(S);
4503 return SU && SU->getValue() == nullptr;
4504 });
4505
4506 return !ContainsNulls;
4507}
4508
4510 HasRecMapType::iterator I = HasRecMap.find(S);
4511 if (I != HasRecMap.end())
4512 return I->second;
4513
4514 bool FoundAddRec =
4515 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4516 HasRecMap.insert({S, FoundAddRec});
4517 return FoundAddRec;
4518}
4519
4520/// Return the ValueOffsetPair set for \p S. \p S can be represented
4521/// by the value and offset from any ValueOffsetPair in the set.
4522ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4523 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4524 if (SI == ExprValueMap.end())
4525 return {};
4526 return SI->second;
4527}
4528
4529/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4530/// cannot be used separately. eraseValueFromMap should be used to remove
4531/// V from ValueExprMap and ExprValueMap at the same time.
4532void ScalarEvolution::eraseValueFromMap(Value *V) {
4533 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4534 if (I != ValueExprMap.end()) {
4535 auto EVIt = ExprValueMap.find(I->second);
4536 assert(is_contained(EVIt->second, V) && "Value not in ExprValueMap?");
4537 llvm::erase(EVIt->second, V);
4538 ValueExprMap.erase(I);
4539 }
4540}
4541
4542void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4543 // A recursive query may have already computed the SCEV. It should be
4544 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4545 // inferred nowrap flags.
4546 if (ValueExprMap.insert({SCEVCallbackVH(V, this), S}).second)
4547 ExprValueMap[S].push_back(V);
4548}
4549
4550/// Return an existing SCEV if it exists, otherwise analyze the expression and
4551/// create a new one.
4553 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4554
4555 if (const SCEV *S = getExistingSCEV(V))
4556 return S;
4557 return createSCEVIter(V);
4558}
4559
4561 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4562
4563 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4564 if (I != ValueExprMap.end()) {
4565 const SCEV *S = I->second;
4566 assert(checkValidity(S) &&
4567 "existing SCEV has not been properly invalidated");
4568 return S;
4569 }
4570 return nullptr;
4571}
4572
4573/// Return a SCEV corresponding to -V = -1*V
4575 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4576 return getConstant(
4577 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4578
4579 Type *Ty = V->getType();
4580 Ty = getEffectiveSCEVType(Ty);
4581 return getMulExpr(V, getMinusOne(Ty), Flags);
4582}
4583
4584/// If Expr computes ~A, return A else return nullptr
4585static const SCEV *MatchNotExpr(const SCEV *Expr) {
4586 const SCEV *MulOp;
4587 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4588 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4589 return MulOp;
4590 return nullptr;
4591}
4592
4593/// Return a SCEV corresponding to ~V = -1-V
4595 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4596
4597 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4598 return getConstant(
4599 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4600
4601 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4602 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4603 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4604 SmallVector<SCEVUse, 2> MatchedOperands;
4605 for (const SCEV *Operand : MME->operands()) {
4606 const SCEV *Matched = MatchNotExpr(Operand);
4607 if (!Matched)
4608 return (const SCEV *)nullptr;
4609 MatchedOperands.push_back(Matched);
4610 }
4611 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4612 MatchedOperands);
4613 };
4614 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4615 return Replaced;
4616 }
4617
4618 Type *Ty = V->getType();
4619 Ty = getEffectiveSCEVType(Ty);
4620 return getMinusSCEV(getMinusOne(Ty), V);
4621}
4622
4624 assert(P->getType()->isPointerTy());
4625
4626 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4627 // The base of an AddRec is the first operand.
4628 SmallVector<SCEVUse> Ops{AddRec->operands()};
4629 Ops[0] = removePointerBase(Ops[0]);
4630 // Don't try to transfer nowrap flags for now. We could in some cases
4631 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4632 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagNone);
4633 }
4634 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4635 // The base of an Add is the pointer operand.
4636 SmallVector<SCEVUse> Ops{Add->operands()};
4637 SCEVUse *PtrOp = nullptr;
4638 for (SCEVUse &AddOp : Ops) {
4639 if (AddOp->getType()->isPointerTy()) {
4640 assert(!PtrOp && "Cannot have multiple pointer ops");
4641 PtrOp = &AddOp;
4642 }
4643 }
4644 *PtrOp = removePointerBase(*PtrOp);
4645 // Don't try to transfer nowrap flags for now. We could in some cases
4646 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4647 return getAddExpr(Ops);
4648 }
4649 // Any other expression must be a pointer base.
4650 return getZero(P->getType());
4651}
4652
4654 SCEVFlags Flags, unsigned Depth) {
4655 // Fast path: X - X --> 0.
4656 if (SCEVUse::getCommon(LHS, RHS))
4657 return getZero(LHS->getType());
4658
4659 // If we subtract two pointers with different pointer bases, bail.
4660 // Eventually, we're going to add an assertion to getMulExpr that we
4661 // can't multiply by a pointer.
4662 if (RHS->getType()->isPointerTy()) {
4663 if (!LHS->getType()->isPointerTy() ||
4664 getPointerBase(LHS) != getPointerBase(RHS))
4665 return getCouldNotCompute();
4666 LHS = removePointerBase(LHS);
4667 RHS = removePointerBase(RHS);
4668 }
4669
4670 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4671 // makes it so that we cannot make much use of NUW.
4672 auto AddFlags = SCEV::FlagNone;
4673 const bool RHSIsNotMinSigned =
4675 if (hasFlags(Flags, SCEV::FlagNSW)) {
4676 // Let M be the minimum representable signed value. Then (-1)*RHS
4677 // signed-wraps if and only if RHS is M. That can happen even for
4678 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4679 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4680 // (-1)*RHS, we need to prove that RHS != M.
4681 //
4682 // If LHS is non-negative and we know that LHS - RHS does not
4683 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4684 // either by proving that RHS > M or that LHS >= 0.
4685 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4686 AddFlags = SCEV::FlagNSW;
4687 }
4688 }
4689
4690 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4691 // RHS is NSW and LHS >= 0.
4692 //
4693 // The difficulty here is that the NSW flag may have been proven
4694 // relative to a loop that is to be found in a recurrence in LHS and
4695 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4696 // larger scope than intended.
4697 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagNone;
4698
4699 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4700}
4701
4703 unsigned Depth) {
4704 Type *SrcTy = V->getType();
4705 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4706 "Cannot truncate or zero extend with non-integer arguments!");
4707 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4708 return V; // No conversion
4709 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4710 return getTruncateExpr(V, Ty, Depth);
4711 return getZeroExtendExpr(V, Ty, Depth);
4712}
4713
4715 unsigned Depth) {
4716 Type *SrcTy = V->getType();
4717 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4718 "Cannot truncate or zero extend with non-integer arguments!");
4719 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4720 return V; // No conversion
4721 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4722 return getTruncateExpr(V, Ty, Depth);
4723 return getSignExtendExpr(V, Ty, Depth);
4724}
4725
4727 Type *SrcTy = V->getType();
4728 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4729 "Cannot noop or zero extend with non-integer arguments!");
4731 "getNoopOrZeroExtend cannot truncate!");
4732 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4733 return V; // No conversion
4734 return getZeroExtendExpr(V, Ty);
4735}
4736
4738 Type *SrcTy = V->getType();
4739 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4740 "Cannot noop or sign extend with non-integer arguments!");
4742 "getNoopOrSignExtend cannot truncate!");
4743 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4744 return V; // No conversion
4745 return getSignExtendExpr(V, Ty);
4746}
4747
4749 Type *SrcTy = V->getType();
4750 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4751 "Cannot noop or any extend with non-integer arguments!");
4753 "getNoopOrAnyExtend cannot truncate!");
4754 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4755 return V; // No conversion
4756 return getAnyExtendExpr(V, Ty);
4757}
4758
4760 Type *SrcTy = V->getType();
4761 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4762 "Cannot truncate or noop with non-integer arguments!");
4764 "getTruncateOrNoop cannot extend!");
4765 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4766 return V; // No conversion
4767 return getTruncateExpr(V, Ty);
4768}
4769
4771 const SCEV *RHS) {
4772 const SCEV *PromotedLHS = LHS;
4773 const SCEV *PromotedRHS = RHS;
4774
4775 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4776 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4777 else
4778 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4779
4780 return getUMaxExpr(PromotedLHS, PromotedRHS);
4781}
4782
4784 const SCEV *RHS,
4785 bool Sequential) {
4786 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4787 return getUMinFromMismatchedTypes(Ops, Sequential);
4788}
4789
4790const SCEV *
4792 bool Sequential) {
4793 assert(!Ops.empty() && "At least one operand must be!");
4794 // Trivial case.
4795 if (Ops.size() == 1)
4796 return Ops[0];
4797
4798 // Find the max type first.
4799 Type *MaxType = nullptr;
4800 for (SCEVUse S : Ops)
4801 if (MaxType)
4802 MaxType = getWiderType(MaxType, S->getType());
4803 else
4804 MaxType = S->getType();
4805 assert(MaxType && "Failed to find maximum type!");
4806
4807 // Extend all ops to max type.
4808 SmallVector<SCEVUse, 2> PromotedOps;
4809 for (SCEVUse S : Ops)
4810 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4811
4812 // Generate umin.
4813 return getUMinExpr(PromotedOps, Sequential);
4814}
4815
4817 // A pointer operand may evaluate to a nonpointer expression, such as null.
4818 if (!V->getType()->isPointerTy())
4819 return V;
4820
4821 while (true) {
4822 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
4823 V = AddRec->getStart();
4824 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
4825 const SCEV *PtrOp = nullptr;
4826 for (const SCEV *AddOp : Add->operands()) {
4827 if (AddOp->getType()->isPointerTy()) {
4828 assert(!PtrOp && "Cannot have multiple pointer ops");
4829 PtrOp = AddOp;
4830 }
4831 }
4832 assert(PtrOp && "Must have pointer op");
4833 V = PtrOp;
4834 } else // Not something we can look further into.
4835 return V;
4836 }
4837}
4838
4839/// Push users of the given Instruction onto the given Worklist.
4843 // Push the def-use children onto the Worklist stack.
4844 for (User *U : I->users()) {
4845 auto *UserInsn = cast<Instruction>(U);
4846 if (Visited.insert(UserInsn).second)
4847 Worklist.push_back(UserInsn);
4848 }
4849}
4850
4851namespace {
4852
4853/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4854/// expression in case its Loop is L. If it is not L then
4855/// if IgnoreOtherLoops is true then use AddRec itself
4856/// otherwise rewrite cannot be done.
4857/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4858class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4859public:
4860 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4861 bool IgnoreOtherLoops = true) {
4862 SCEVInitRewriter Rewriter(L, SE);
4863 const SCEV *Result = Rewriter.visit(S);
4864 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4865 return SE.getCouldNotCompute();
4866 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4867 ? SE.getCouldNotCompute()
4868 : Result;
4869 }
4870
4871 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4872 if (!SE.isLoopInvariant(Expr, L))
4873 SeenLoopVariantSCEVUnknown = true;
4874 return Expr;
4875 }
4876
4877 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4878 // Only re-write AddRecExprs for this loop.
4879 if (Expr->getLoop() == L)
4880 return Expr->getStart();
4881 SeenOtherLoops = true;
4882 return Expr;
4883 }
4884
4885 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4886
4887 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4888
4889private:
4890 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4891 : SCEVRewriteVisitor(SE), L(L) {}
4892
4893 const Loop *L;
4894 bool SeenLoopVariantSCEVUnknown = false;
4895 bool SeenOtherLoops = false;
4896};
4897
4898/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4899/// increment expression in case its Loop is L. If it is not L then
4900/// use AddRec itself.
4901/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4902class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4903public:
4904 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4905 SCEVPostIncRewriter Rewriter(L, SE);
4906 const SCEV *Result = Rewriter.visit(S);
4907 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4908 ? SE.getCouldNotCompute()
4909 : Result;
4910 }
4911
4912 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4913 if (!SE.isLoopInvariant(Expr, L))
4914 SeenLoopVariantSCEVUnknown = true;
4915 return Expr;
4916 }
4917
4918 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4919 // Only re-write AddRecExprs for this loop.
4920 if (Expr->getLoop() == L)
4921 return Expr->getPostIncExpr(SE);
4922 SeenOtherLoops = true;
4923 return Expr;
4924 }
4925
4926 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4927
4928 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4929
4930private:
4931 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4932 : SCEVRewriteVisitor(SE), L(L) {}
4933
4934 const Loop *L;
4935 bool SeenLoopVariantSCEVUnknown = false;
4936 bool SeenOtherLoops = false;
4937};
4938
4939/// This class evaluates the compare condition by matching it against the
4940/// condition of loop latch. If there is a match we assume a true value
4941/// for the condition while building SCEV nodes.
4942class SCEVBackedgeConditionFolder
4943 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4944public:
4945 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4946 ScalarEvolution &SE) {
4947 bool IsPosBECond = false;
4948 Value *BECond = nullptr;
4949 if (BasicBlock *Latch = L->getLoopLatch()) {
4950 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
4951 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4952 "Both outgoing branches should not target same header!");
4953 BECond = BI->getCondition();
4954 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4955 } else {
4956 return S;
4957 }
4958 }
4959 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4960 return Rewriter.visit(S);
4961 }
4962
4963 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4964 const SCEV *Result = Expr;
4965 bool InvariantF = SE.isLoopInvariant(Expr, L);
4966
4967 if (!InvariantF) {
4969 switch (I->getOpcode()) {
4970 case Instruction::Select: {
4971 SelectInst *SI = cast<SelectInst>(I);
4972 std::optional<const SCEV *> Res =
4973 compareWithBackedgeCondition(SI->getCondition());
4974 if (Res) {
4975 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
4976 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4977 }
4978 break;
4979 }
4980 default: {
4981 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4982 if (Res)
4983 Result = *Res;
4984 break;
4985 }
4986 }
4987 }
4988 return Result;
4989 }
4990
4991private:
4992 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4993 bool IsPosBECond, ScalarEvolution &SE)
4994 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4995 IsPositiveBECond(IsPosBECond) {}
4996
4997 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4998
4999 const Loop *L;
5000 /// Loop back condition.
5001 Value *BackedgeCond = nullptr;
5002 /// Set to true if loop back is on positive branch condition.
5003 bool IsPositiveBECond;
5004};
5005
5006std::optional<const SCEV *>
5007SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5008
5009 // If value matches the backedge condition for loop latch,
5010 // then return a constant evolution node based on loopback
5011 // branch taken.
5012 if (BackedgeCond == IC)
5013 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5015 return std::nullopt;
5016}
5017
5018class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5019public:
5020 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5021 ScalarEvolution &SE) {
5022 SCEVShiftRewriter Rewriter(L, SE);
5023 const SCEV *Result = Rewriter.visit(S);
5024 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5025 }
5026
5027 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5028 // Only allow AddRecExprs for this loop.
5029 if (!SE.isLoopInvariant(Expr, L))
5030 Valid = false;
5031 return Expr;
5032 }
5033
5034 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5035 if (Expr->getLoop() == L && Expr->isAffine())
5036 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5037 Valid = false;
5038 return Expr;
5039 }
5040
5041 bool isValid() { return Valid; }
5042
5043private:
5044 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5045 : SCEVRewriteVisitor(SE), L(L) {}
5046
5047 const Loop *L;
5048 bool Valid = true;
5049};
5050
5051} // end anonymous namespace
5052
5053void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5054 if (!AR->isAffine())
5055 return;
5056
5057 // Force computation of ranges, which will also perform range-based flag
5058 // inference.
5059 if (!AR->hasNoSignedWrap())
5060 (void)getSignedRange(AR);
5061
5062 if (!AR->hasNoUnsignedWrap())
5063 (void)getUnsignedRange(AR);
5064
5065 if (!AR->hasNoSelfWrap()) {
5066 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5067 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5068 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5069 const APInt &BECountAP = BECountMax->getAPInt();
5070 unsigned NoOverflowBitWidth =
5071 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5072 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5073 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5074 }
5075 }
5076}
5077
5079ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5081
5082 if (AR->hasNoSignedWrap())
5083 return Result;
5084
5085 if (!AR->isAffine())
5086 return Result;
5087
5088 // This function can be expensive, only try to prove NSW once per AddRec.
5089 if (!SignedWrapViaInductionTried.insert(AR).second)
5090 return Result;
5091
5092 const SCEV *Step = AR->getStepRecurrence(*this);
5093 const Loop *L = AR->getLoop();
5094
5095 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5096 // Note that this serves two purposes: It filters out loops that are
5097 // simply not analyzable, and it covers the case where this code is
5098 // being called from within backedge-taken count analysis, such that
5099 // attempting to ask for the backedge-taken count would likely result
5100 // in infinite recursion. In the later case, the analysis code will
5101 // cope with a conservative value, and it will take care to purge
5102 // that value once it has finished.
5103 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5104
5105 // Normally, in the cases we can prove no-overflow via a
5106 // backedge guarding condition, we can also compute a backedge
5107 // taken count for the loop. The exceptions are assumptions and
5108 // guards present in the loop -- SCEV is not great at exploiting
5109 // these to compute max backedge taken counts, but can still use
5110 // these to prove lack of overflow. Use this fact to avoid
5111 // doing extra work that may not pay off.
5112
5113 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5114 AC.assumptions().empty())
5115 return Result;
5116
5117 // If the backedge is guarded by a comparison with the pre-inc value the
5118 // addrec is safe. Also, if the entry is guarded by a comparison with the
5119 // start value and the backedge is guarded by a comparison with the post-inc
5120 // value, the addrec is safe.
5122 const SCEV *OverflowLimit =
5123 getSignedOverflowLimitForStep(Step, &Pred, this);
5124 if (OverflowLimit &&
5125 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5126 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5127 Result = setFlags(Result, SCEV::FlagNSW);
5128 }
5129 return Result;
5130}
5132ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5134
5135 if (AR->hasNoUnsignedWrap())
5136 return Result;
5137
5138 if (!AR->isAffine())
5139 return Result;
5140
5141 // This function can be expensive, only try to prove NUW once per AddRec.
5142 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5143 return Result;
5144
5145 const SCEV *Step = AR->getStepRecurrence(*this);
5146 const Loop *L = AR->getLoop();
5147
5148 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5149 // Note that this serves two purposes: It filters out loops that are
5150 // simply not analyzable, and it covers the case where this code is
5151 // being called from within backedge-taken count analysis, such that
5152 // attempting to ask for the backedge-taken count would likely result
5153 // in infinite recursion. In the later case, the analysis code will
5154 // cope with a conservative value, and it will take care to purge
5155 // that value once it has finished.
5156 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5157
5158 // Normally, in the cases we can prove no-overflow via a
5159 // backedge guarding condition, we can also compute a backedge
5160 // taken count for the loop. The exceptions are assumptions and
5161 // guards present in the loop -- SCEV is not great at exploiting
5162 // these to compute max backedge taken counts, but can still use
5163 // these to prove lack of overflow. Use this fact to avoid
5164 // doing extra work that may not pay off.
5165
5166 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5167 AC.assumptions().empty())
5168 return Result;
5169
5170 // If the backedge is guarded by a comparison with the pre-inc value the
5171 // addrec is safe. Also, if the entry is guarded by a comparison with the
5172 // start value and the backedge is guarded by a comparison with the post-inc
5173 // value, the addrec is safe.
5174 if (isKnownPositive(Step)) {
5176 const SCEV *OverflowLimit =
5177 getUnsignedOverflowLimitForStep(Step, &Pred, this);
5178 if (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5179 isKnownOnEveryIteration(Pred, AR, OverflowLimit))
5180 Result = setFlags(Result, SCEV::FlagNUW);
5181 }
5182 return Result;
5183}
5184
5185namespace {
5186
5187/// Represents an abstract binary operation. This may exist as a
5188/// normal instruction or constant expression, or may have been
5189/// derived from an expression tree.
5190struct BinaryOp {
5191 unsigned Opcode;
5192 Value *LHS;
5193 Value *RHS;
5194 bool IsNSW = false;
5195 bool IsNUW = false;
5196
5197 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5198 /// constant expression.
5199 Operator *Op = nullptr;
5200
5201 explicit BinaryOp(Operator *Op)
5202 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5203 Op(Op) {
5204 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5205 IsNSW = OBO->hasNoSignedWrap();
5206 IsNUW = OBO->hasNoUnsignedWrap();
5207 }
5208 }
5209
5210 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5211 bool IsNUW = false)
5212 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5213};
5214
5215} // end anonymous namespace
5216
5217/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5218static std::optional<BinaryOp> MatchBinaryOp(Value *V,
5219 const DominatorTree &DT) {
5220 auto *Op = dyn_cast<Operator>(V);
5221 if (!Op)
5222 return std::nullopt;
5223
5224 // Implementation detail: all the cleverness here should happen without
5225 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5226 // SCEV expressions when possible, and we should not break that.
5227
5228 switch (Op->getOpcode()) {
5229 case Instruction::Add:
5230 case Instruction::Sub:
5231 case Instruction::Mul:
5232 case Instruction::UDiv:
5233 case Instruction::URem:
5234 case Instruction::And:
5235 case Instruction::AShr:
5236 case Instruction::Shl:
5237 return BinaryOp(Op);
5238
5239 case Instruction::Or: {
5240 // Convert or disjoint into add nuw nsw.
5241 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5242 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5243 /*IsNSW=*/true, /*IsNUW=*/true);
5244 // Keep the reference to the original instruction so that we can later
5245 // check whether it can produce poison value or not.
5246 BinOp.Op = Op;
5247 return BinOp;
5248 }
5249 return BinaryOp(Op);
5250 }
5251
5252 case Instruction::Xor:
5253 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5254 // If the RHS of the xor is a signmask, then this is just an add.
5255 // Instcombine turns add of signmask into xor as a strength reduction step.
5256 if (RHSC->getValue().isSignMask())
5257 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5258 // Binary `xor` is a bit-wise `add`.
5259 if (V->getType()->isIntegerTy(1))
5260 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5261 return BinaryOp(Op);
5262
5263 case Instruction::LShr:
5264 // Turn logical shift right of a constant into a unsigned divide.
5265 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5266 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5267
5268 // If the shift count is not less than the bitwidth, the result of
5269 // the shift is undefined. Don't try to analyze it, because the
5270 // resolution chosen here may differ from the resolution chosen in
5271 // other parts of the compiler.
5272 if (SA->getValue().ult(BitWidth)) {
5273 Constant *X =
5274 ConstantInt::get(SA->getContext(),
5275 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5276 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5277 }
5278 }
5279 return BinaryOp(Op);
5280
5281 case Instruction::ExtractValue: {
5282 auto *EVI = cast<ExtractValueInst>(Op);
5283 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5284 break;
5285
5286 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5287 if (!WO)
5288 break;
5289
5290 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5291 bool Signed = WO->isSigned();
5292 // TODO: Should add nuw/nsw flags for mul as well.
5293 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5294 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5295
5296 // Now that we know that all uses of the arithmetic-result component of
5297 // CI are guarded by the overflow check, we can go ahead and pretend
5298 // that the arithmetic is non-overflowing.
5299 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5300 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5301 }
5302
5303 default:
5304 break;
5305 }
5306
5307 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5308 // semantics as a Sub, return a binary sub expression.
5309 if (auto *II = dyn_cast<IntrinsicInst>(V))
5310 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5311 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5312
5313 return std::nullopt;
5314}
5315
5316/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5317/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5318/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5319/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5320/// follows one of the following patterns:
5321/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5322/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5323/// If the SCEV expression of \p Op conforms with one of the expected patterns
5324/// we return the type of the truncation operation, and indicate whether the
5325/// truncated type should be treated as signed/unsigned by setting
5326/// \p Signed to true/false, respectively.
5327static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5328 bool &Signed, ScalarEvolution &SE) {
5329 // The case where Op == SymbolicPHI (that is, with no type conversions on
5330 // the way) is handled by the regular add recurrence creating logic and
5331 // would have already been triggered in createAddRecForPHI. Reaching it here
5332 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5333 // because one of the other operands of the SCEVAddExpr updating this PHI is
5334 // not invariant).
5335 //
5336 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5337 // this case predicates that allow us to prove that Op == SymbolicPHI will
5338 // be added.
5339 if (Op == SymbolicPHI)
5340 return nullptr;
5341
5342 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5343 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5344 if (SourceBits != NewBits)
5345 return nullptr;
5346
5347 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5348 Signed = true;
5349 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5350 }
5351 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5352 Signed = false;
5353 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5354 }
5355 return nullptr;
5356}
5357
5358static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5359 if (!PN->getType()->isIntegerTy())
5360 return nullptr;
5361 const Loop *L = LI.getLoopFor(PN->getParent());
5362 if (!L || L->getHeader() != PN->getParent())
5363 return nullptr;
5364 return L;
5365}
5366
5367// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5368// computation that updates the phi follows the following pattern:
5369// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5370// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5371// If so, try to see if it can be rewritten as an AddRecExpr under some
5372// Predicates. If successful, return them as a pair. Also cache the results
5373// of the analysis.
5374//
5375// Example usage scenario:
5376// Say the Rewriter is called for the following SCEV:
5377// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5378// where:
5379// %X = phi i64 (%Start, %BEValue)
5380// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5381// and call this function with %SymbolicPHI = %X.
5382//
5383// The analysis will find that the value coming around the backedge has
5384// the following SCEV:
5385// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5386// Upon concluding that this matches the desired pattern, the function
5387// will return the pair {NewAddRec, SmallPredsVec} where:
5388// NewAddRec = {%Start,+,%Step}
5389// SmallPredsVec = {P1, P2, P3} as follows:
5390// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5391// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5392// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5393// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5394// under the predicates {P1,P2,P3}.
5395// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5396// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5397//
5398// TODO's:
5399//
5400// 1) Extend the Induction descriptor to also support inductions that involve
5401// casts: When needed (namely, when we are called in the context of the
5402// vectorizer induction analysis), a Set of cast instructions will be
5403// populated by this method, and provided back to isInductionPHI. This is
5404// needed to allow the vectorizer to properly record them to be ignored by
5405// the cost model and to avoid vectorizing them (otherwise these casts,
5406// which are redundant under the runtime overflow checks, will be
5407// vectorized, which can be costly).
5408//
5409// 2) Support additional induction/PHISCEV patterns: We also want to support
5410// inductions where the sext-trunc / zext-trunc operations (partly) occur
5411// after the induction update operation (the induction increment):
5412//
5413// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5414// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5415//
5416// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5417// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5418//
5419// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5420std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5421ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5423
5424 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5425 // return an AddRec expression under some predicate.
5426
5427 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5428 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5429 assert(L && "Expecting an integer loop header phi");
5430
5431 // The loop may have multiple entrances or multiple exits; we can analyze
5432 // this phi as an addrec if it has a unique entry value and a unique
5433 // backedge value.
5434 Value *BEValueV = nullptr, *StartValueV = nullptr;
5435 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5436 Value *V = PN->getIncomingValue(i);
5437 if (L->contains(PN->getIncomingBlock(i))) {
5438 if (!BEValueV) {
5439 BEValueV = V;
5440 } else if (BEValueV != V) {
5441 BEValueV = nullptr;
5442 break;
5443 }
5444 } else if (!StartValueV) {
5445 StartValueV = V;
5446 } else if (StartValueV != V) {
5447 StartValueV = nullptr;
5448 break;
5449 }
5450 }
5451 if (!BEValueV || !StartValueV)
5452 return std::nullopt;
5453
5454 const SCEV *BEValue = getSCEV(BEValueV);
5455
5456 // If the value coming around the backedge is an add with the symbolic
5457 // value we just inserted, possibly with casts that we can ignore under
5458 // an appropriate runtime guard, then we found a simple induction variable!
5459 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5460 if (!Add)
5461 return std::nullopt;
5462
5463 // If there is a single occurrence of the symbolic value, possibly
5464 // casted, replace it with a recurrence.
5465 unsigned FoundIndex = Add->getNumOperands();
5466 Type *TruncTy = nullptr;
5467 bool Signed;
5468 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5469 if ((TruncTy =
5470 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5471 if (FoundIndex == e) {
5472 FoundIndex = i;
5473 break;
5474 }
5475
5476 if (FoundIndex == Add->getNumOperands())
5477 return std::nullopt;
5478
5479 // Create an add with everything but the specified operand.
5481 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5482 if (i != FoundIndex)
5483 Ops.push_back(Add->getOperand(i));
5484 const SCEV *Accum = getAddExpr(Ops);
5485
5486 // The runtime checks will not be valid if the step amount is
5487 // varying inside the loop.
5488 if (!isLoopInvariant(Accum, L))
5489 return std::nullopt;
5490
5491 // *** Part2: Create the predicates
5492
5493 // Analysis was successful: we have a phi-with-cast pattern for which we
5494 // can return an AddRec expression under the following predicates:
5495 //
5496 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5497 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5498 // P2: An Equal predicate that guarantees that
5499 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5500 // P3: An Equal predicate that guarantees that
5501 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5502 //
5503 // As we next prove, the above predicates guarantee that:
5504 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5505 //
5506 //
5507 // More formally, we want to prove that:
5508 // Expr(i+1) = Start + (i+1) * Accum
5509 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5510 //
5511 // Given that:
5512 // 1) Expr(0) = Start
5513 // 2) Expr(1) = Start + Accum
5514 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5515 // 3) Induction hypothesis (step i):
5516 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5517 //
5518 // Proof:
5519 // Expr(i+1) =
5520 // = Start + (i+1)*Accum
5521 // = (Start + i*Accum) + Accum
5522 // = Expr(i) + Accum
5523 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5524 // :: from step i
5525 //
5526 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5527 //
5528 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5529 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5530 // + Accum :: from P3
5531 //
5532 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5533 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5534 //
5535 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5536 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5537 //
5538 // By induction, the same applies to all iterations 1<=i<n:
5539 //
5540
5541 // Create a truncated addrec for which we will add a no overflow check (P1).
5542 const SCEV *StartVal = getSCEV(StartValueV);
5543 const SCEV *PHISCEV =
5544 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5545 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagNone);
5546
5547 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5548 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5549 // will be constant.
5550 //
5551 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5552 // add P1.
5553 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5557 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5558 Predicates.push_back(AddRecPred);
5559 }
5560
5561 // Create the Equal Predicates P2,P3:
5562
5563 // It is possible that the predicates P2 and/or P3 are computable at
5564 // compile time due to StartVal and/or Accum being constants.
5565 // If either one is, then we can check that now and escape if either P2
5566 // or P3 is false.
5567
5568 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5569 // for each of StartVal and Accum
5570 auto getExtendedExpr = [&](const SCEV *Expr,
5571 bool CreateSignExtend) -> const SCEV * {
5572 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5573 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5574 const SCEV *ExtendedExpr =
5575 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5576 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5577 return ExtendedExpr;
5578 };
5579
5580 // Given:
5581 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5582 // = getExtendedExpr(Expr)
5583 // Determine whether the predicate P: Expr == ExtendedExpr
5584 // is known to be false at compile time
5585 auto PredIsKnownFalse = [&](const SCEV *Expr,
5586 const SCEV *ExtendedExpr) -> bool {
5587 return Expr != ExtendedExpr &&
5588 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5589 };
5590
5591 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5592 if (PredIsKnownFalse(StartVal, StartExtended)) {
5593 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5594 return std::nullopt;
5595 }
5596
5597 // The Step is always Signed (because the overflow checks are either
5598 // NSSW or NUSW)
5599 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5600 if (PredIsKnownFalse(Accum, AccumExtended)) {
5601 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5602 return std::nullopt;
5603 }
5604
5605 auto AppendPredicate = [&](const SCEV *Expr,
5606 const SCEV *ExtendedExpr) -> void {
5607 if (Expr != ExtendedExpr &&
5608 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5609 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5610 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5611 Predicates.push_back(Pred);
5612 }
5613 };
5614
5615 AppendPredicate(StartVal, StartExtended);
5616 AppendPredicate(Accum, AccumExtended);
5617
5618 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5619 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5620 // into NewAR if it will also add the runtime overflow checks specified in
5621 // Predicates.
5622 const SCEV *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagNone);
5623
5624 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5625 std::make_pair(NewAR, Predicates);
5626 // Remember the result of the analysis for this SCEV at this locayyytion.
5627 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5628 return PredRewrite;
5629}
5630
5631std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5633 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5634 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5635 if (!L)
5636 return std::nullopt;
5637
5638 // Check to see if we already analyzed this PHI.
5639 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5640 if (I != PredicatedSCEVRewrites.end()) {
5641 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5642 I->second;
5643 // Analysis was done before and failed to create an AddRec:
5644 if (Rewrite.first == SymbolicPHI)
5645 return std::nullopt;
5646 // Analysis was done before and succeeded to create an AddRec under
5647 // a predicate:
5648 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5649 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5650 return Rewrite;
5651 }
5652
5653 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5654 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5655
5656 // Record in the cache that the analysis failed
5657 if (!Rewrite) {
5659 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5660 return std::nullopt;
5661 }
5662
5663 return Rewrite;
5664}
5665
5666// FIXME: This utility is currently required because the Rewriter currently
5667// does not rewrite this expression:
5668// {0, +, (sext ix (trunc iy to ix) to iy)}
5669// into {0, +, %step},
5670// even when the following Equal predicate exists:
5671// "%step == (sext ix (trunc iy to ix) to iy)".
5673 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5674 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5675 if (AR1 == AR2)
5676 return true;
5677
5678 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5679 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5680 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5681 if (Expr1 != Expr2 &&
5682 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5683 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5684 return false;
5685 return true;
5686 };
5687
5688 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5689 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5690 return false;
5691 return true;
5692}
5693
5695 ScalarEvolution &SE) {
5696 SCEVFlags Flags = SCEV::FlagNone;
5697 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
5698 // If the increment has any nowrap flags, then we know the address
5699 // space cannot be wrapped around.
5700 if (NW != GEPNoWrapFlags::none())
5702 // If the GEP is nuw or nusw with non-negative offset, we know that
5703 // no unsigned wrap occurs. We cannot set the nsw flag as only the
5704 // offset is treated as signed, while the base is unsigned.
5705 if (NW.hasNoUnsignedWrap() ||
5706 (NW.hasNoUnsignedSignedWrap() && SE.isKnownNonNegative(Accum)))
5708
5709 return Flags;
5710}
5711
5712/// A helper function for createAddRecFromPHI to handle simple cases.
5713///
5714/// This function tries to find an AddRec expression for the simplest (yet most
5715/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5716/// If it fails, createAddRecFromPHI will use a more general, but slow,
5717/// technique for finding the AddRec expression.
5718const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5719 Value *BEValueV,
5720 Value *StartValueV) {
5721 const Loop *L = LI.getLoopFor(PN->getParent());
5722 assert(L && L->getHeader() == PN->getParent());
5723 assert(BEValueV && StartValueV);
5724
5725 const SCEV *Accum = nullptr;
5727 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5728 if (BO->Opcode != Instruction::Add)
5729 return nullptr;
5730
5731 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5732 Accum = getSCEV(BO->RHS);
5733 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5734 Accum = getSCEV(BO->LHS);
5735
5736 if (!Accum)
5737 return nullptr;
5738
5739 if (BO->IsNUW)
5740 Flags = setFlags(Flags, SCEV::FlagNUW);
5741 if (BO->IsNSW)
5742 Flags = setFlags(Flags, SCEV::FlagNSW);
5743 } else {
5744 // Handle pointer induction variable: PN = PHI(Start, gep PN,
5745 // LoopInvariant).
5746 auto *GEP = dyn_cast<GEPOperator>(BEValueV);
5747 if (!GEP || GEP->getPointerOperand() != PN || GEP->getNumIndices() != 1)
5748 return nullptr;
5749 Value *Idx = *GEP->idx_begin();
5750 if (!L->isLoopInvariant(Idx))
5751 return nullptr;
5752
5753 Type *IntIdxTy = getEffectiveSCEVType(GEP->getType());
5754 Accum = getMulExpr(getTruncateOrSignExtend(getSCEV(Idx), IntIdxTy),
5755 getSizeOfExpr(IntIdxTy, GEP->getSourceElementType()));
5756 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5757 }
5758
5759 const SCEV *StartVal = getSCEV(StartValueV);
5760 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5761 insertValueToMap(PN, PHISCEV);
5762
5763 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5764 inferNoWrapViaConstantRanges(AR);
5765
5766 // We can add Flags to the post-inc expression only if we
5767 // know that it is *undefined behavior* for BEValueV to
5768 // overflow.
5769 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5770 assert(isLoopInvariant(Accum, L) &&
5771 "Accum is defined outside L, but is not invariant?");
5772 if (isAddRecNeverPoison(BEInst, L))
5773 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5774 }
5775
5776 return PHISCEV;
5777}
5778
5779const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5780 const Loop *L = LI.getLoopFor(PN->getParent());
5781 if (!L || L->getHeader() != PN->getParent())
5782 return nullptr;
5783
5784 // The loop may have multiple entrances or multiple exits; we can analyze
5785 // this phi as an addrec if it has a unique entry value and a unique
5786 // backedge value.
5787 Value *BEValueV = nullptr, *StartValueV = nullptr;
5788 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5789 Value *V = PN->getIncomingValue(i);
5790 if (L->contains(PN->getIncomingBlock(i))) {
5791 if (!BEValueV) {
5792 BEValueV = V;
5793 } else if (BEValueV != V) {
5794 BEValueV = nullptr;
5795 break;
5796 }
5797 } else if (!StartValueV) {
5798 StartValueV = V;
5799 } else if (StartValueV != V) {
5800 StartValueV = nullptr;
5801 break;
5802 }
5803 }
5804 if (!BEValueV || !StartValueV)
5805 return nullptr;
5806
5807 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5808 "PHI node already processed?");
5809
5810 // First, try to find AddRec expression without creating a fictituos symbolic
5811 // value for PN.
5812 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5813 return S;
5814
5815 // Handle PHI node value symbolically.
5816 const SCEV *SymbolicName = getUnknown(PN);
5817 insertValueToMap(PN, SymbolicName);
5818
5819 // Using this symbolic name for the PHI, analyze the value coming around
5820 // the back-edge.
5821 const SCEV *BEValue = getSCEV(BEValueV);
5822
5823 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5824 // has a special value for the first iteration of the loop.
5825
5826 // If the value coming around the backedge is an add with the symbolic
5827 // value we just inserted, then we found a simple induction variable!
5828 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5829 // If there is a single occurrence of the symbolic value, replace it
5830 // with a recurrence.
5831 unsigned FoundIndex = Add->getNumOperands();
5832 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5833 if (Add->getOperand(i) == SymbolicName)
5834 if (FoundIndex == e) {
5835 FoundIndex = i;
5836 break;
5837 }
5838
5839 if (FoundIndex != Add->getNumOperands()) {
5840 // Create an add with everything but the specified operand.
5842 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5843 if (i != FoundIndex)
5844 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5845 L, *this));
5846 const SCEV *Accum = getAddExpr(Ops);
5847
5848 // This is not a valid addrec if the step amount is varying each
5849 // loop iteration, but is not itself an addrec in this loop.
5850 if (isLoopInvariant(Accum, L) ||
5851 (isa<SCEVAddRecExpr>(Accum) &&
5852 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5854
5855 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5856 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5857 if (BO->IsNUW)
5858 Flags = setFlags(Flags, SCEV::FlagNUW);
5859 if (BO->IsNSW)
5860 Flags = setFlags(Flags, SCEV::FlagNSW);
5861 }
5862 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5863 if (GEP->getOperand(0) == PN)
5864 Flags = getNoWrapFlagsForGEP(GEP, Accum, *this);
5865
5866 // We cannot transfer nuw and nsw flags from subtraction
5867 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5868 // for instance.
5869 }
5870
5871 const SCEV *StartVal = getSCEV(StartValueV);
5872 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5873
5874 // Okay, for the entire analysis of this edge we assumed the PHI
5875 // to be symbolic. We now need to go back and purge all of the
5876 // entries for the scalars that use the symbolic expression.
5877 forgetMemoizedResults({SymbolicName});
5878 insertValueToMap(PN, PHISCEV);
5879
5880 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5881 inferNoWrapViaConstantRanges(AR);
5882
5883 // We can add Flags to the post-inc expression only if we
5884 // know that it is *undefined behavior* for BEValueV to
5885 // overflow.
5886 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5887 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5888 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5889
5890 return PHISCEV;
5891 }
5892 }
5893 } else {
5894 // Otherwise, this could be a loop like this:
5895 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5896 // In this case, j = {1,+,1} and BEValue is j.
5897 // Because the other in-value of i (0) fits the evolution of BEValue
5898 // i really is an addrec evolution.
5899 //
5900 // We can generalize this saying that i is the shifted value of BEValue
5901 // by one iteration:
5902 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5903
5904 // Do not allow refinement in rewriting of BEValue.
5905 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5906 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5907 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
5908 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
5909 const SCEV *StartVal = getSCEV(StartValueV);
5910 if (Start == StartVal) {
5911 // Okay, for the entire analysis of this edge we assumed the PHI
5912 // to be symbolic. We now need to go back and purge all of the
5913 // entries for the scalars that use the symbolic expression.
5914 forgetMemoizedResults({SymbolicName});
5915 insertValueToMap(PN, Shifted);
5916 return Shifted;
5917 }
5918 }
5919 }
5920
5921 // Remove the temporary PHI node SCEV that has been inserted while intending
5922 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5923 // as it will prevent later (possibly simpler) SCEV expressions to be added
5924 // to the ValueExprMap.
5925 eraseValueFromMap(PN);
5926
5927 return nullptr;
5928}
5929
5930// Try to match a control flow sequence that branches out at BI and merges back
5931// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5932// match.
5934 Value *&C, Value *&LHS, Value *&RHS) {
5935 C = BI->getCondition();
5936
5937 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5938 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5939
5940 Use &LeftUse = Merge->getOperandUse(0);
5941 Use &RightUse = Merge->getOperandUse(1);
5942
5943 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5944 LHS = LeftUse;
5945 RHS = RightUse;
5946 return true;
5947 }
5948
5949 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5950 LHS = RightUse;
5951 RHS = LeftUse;
5952 return true;
5953 }
5954
5955 return false;
5956}
5957
5959 Value *&Cond, Value *&LHS,
5960 Value *&RHS) {
5961 auto IsReachable =
5962 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5963 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5964 // Try to match
5965 //
5966 // br %cond, label %left, label %right
5967 // left:
5968 // br label %merge
5969 // right:
5970 // br label %merge
5971 // merge:
5972 // V = phi [ %x, %left ], [ %y, %right ]
5973 //
5974 // as "select %cond, %x, %y"
5975
5976 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5977 assert(IDom && "At least the entry block should dominate PN");
5978
5979 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
5980 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
5981 }
5982 return false;
5983}
5984
5985const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5986 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5987 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
5990 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5991
5992 return nullptr;
5993}
5994
5996 BinaryOperator *CommonInst = nullptr;
5997 // Check if instructions are identical.
5998 for (Value *Incoming : PN->incoming_values()) {
5999 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6000 if (!IncomingInst)
6001 return nullptr;
6002 if (CommonInst) {
6003 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6004 return nullptr; // Not identical, give up
6005 } else {
6006 // Remember binary operator
6007 CommonInst = IncomingInst;
6008 }
6009 }
6010 return CommonInst;
6011}
6012
6013/// Returns SCEV for the first operand of a phi if all phi operands have
6014/// identical opcodes and operands
6015/// eg.
6016/// a: %add = %a + %b
6017/// br %c
6018/// b: %add1 = %a + %b
6019/// br %c
6020/// c: %phi = phi [%add, a], [%add1, b]
6021/// scev(%phi) => scev(%add)
6022const SCEV *
6023ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6024 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6025 if (!CommonInst)
6026 return nullptr;
6027
6028 // Check if SCEV exprs for instructions are identical.
6029 const SCEV *CommonSCEV = getSCEV(CommonInst);
6030 bool SCEVExprsIdentical =
6032 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6033 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6034}
6035
6036const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6037 if (const SCEV *S = createAddRecFromPHI(PN))
6038 return S;
6039
6040 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6041 // phi node for X.
6042 if (Value *V = simplifyInstruction(
6043 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6044 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6045 return getSCEV(V);
6046
6047 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6048 return S;
6049
6050 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6051 return S;
6052
6053 // If it's not a loop phi, we can't handle it yet.
6054 return getUnknown(PN);
6055}
6056
6057bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6058 SCEVTypes RootKind) {
6059 struct FindClosure {
6060 const SCEV *OperandToFind;
6061 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6062 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6063
6064 bool Found = false;
6065
6066 bool canRecurseInto(SCEVTypes Kind) const {
6067 // We can only recurse into the SCEV expression of the same effective type
6068 // as the type of our root SCEV expression, and into zero-extensions.
6069 return RootKind == Kind || NonSequentialRootKind == Kind ||
6070 scZeroExtend == Kind;
6071 };
6072
6073 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6074 : OperandToFind(OperandToFind), RootKind(RootKind),
6075 NonSequentialRootKind(
6077 RootKind)) {}
6078
6079 bool follow(const SCEV *S) {
6080 Found = S == OperandToFind;
6081
6082 return !isDone() && canRecurseInto(S->getSCEVType());
6083 }
6084
6085 bool isDone() const { return Found; }
6086 };
6087
6088 FindClosure FC(OperandToFind, RootKind);
6089 visitAll(Root, FC);
6090 return FC.Found;
6091}
6092
6093std::optional<const SCEV *>
6094ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6095 ICmpInst *Cond,
6096 Value *TrueVal,
6097 Value *FalseVal) {
6098 // Try to match some simple smax or umax patterns.
6099 auto *ICI = Cond;
6100
6101 Value *LHS = ICI->getOperand(0);
6102 Value *RHS = ICI->getOperand(1);
6103
6104 switch (ICI->getPredicate()) {
6105 case ICmpInst::ICMP_SLT:
6106 case ICmpInst::ICMP_SLE:
6107 case ICmpInst::ICMP_ULT:
6108 case ICmpInst::ICMP_ULE:
6109 std::swap(LHS, RHS);
6110 [[fallthrough]];
6111 case ICmpInst::ICMP_SGT:
6112 case ICmpInst::ICMP_SGE:
6113 case ICmpInst::ICMP_UGT:
6114 case ICmpInst::ICMP_UGE:
6115 // a > b ? a+x : b+x -> max(a, b)+x
6116 // a > b ? b+x : a+x -> min(a, b)+x
6118 bool Signed = ICI->isSigned();
6119 const SCEV *LA = getSCEV(TrueVal);
6120 const SCEV *RA = getSCEV(FalseVal);
6121 const SCEV *LS = getSCEV(LHS);
6122 const SCEV *RS = getSCEV(RHS);
6123 if (LA->getType()->isPointerTy()) {
6124 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6125 // Need to make sure we can't produce weird expressions involving
6126 // negated pointers.
6127 if (LA == LS && RA == RS)
6128 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6129 if (LA == RS && RA == LS)
6130 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6131 }
6132 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6133 if (Op->getType()->isPointerTy()) {
6136 return Op;
6137 }
6138 if (Signed)
6139 Op = getNoopOrSignExtend(Op, Ty);
6140 else
6141 Op = getNoopOrZeroExtend(Op, Ty);
6142 return Op;
6143 };
6144 LS = CoerceOperand(LS);
6145 RS = CoerceOperand(RS);
6147 break;
6148 const SCEV *LDiff = getMinusSCEV(LA, LS);
6149 const SCEV *RDiff = getMinusSCEV(RA, RS);
6150 if (LDiff == RDiff)
6151 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6152 LDiff);
6153 LDiff = getMinusSCEV(LA, RS);
6154 RDiff = getMinusSCEV(RA, LS);
6155 if (LDiff == RDiff)
6156 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6157 LDiff);
6158 }
6159 break;
6160 case ICmpInst::ICMP_NE:
6161 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6162 std::swap(TrueVal, FalseVal);
6163 [[fallthrough]];
6164 case ICmpInst::ICMP_EQ:
6165 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6168 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6169 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6170 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6171 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6172 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6173 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6174 return getAddExpr(getUMaxExpr(X, C), Y);
6175 }
6176 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6177 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6178 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6179 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6181 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6182 const SCEV *X = getSCEV(LHS);
6183 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6184 X = ZExt->getOperand();
6185 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6186 const SCEV *FalseValExpr = getSCEV(FalseVal);
6187 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6188 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6189 /*Sequential=*/true);
6190 }
6191 }
6192 break;
6193 default:
6194 break;
6195 }
6196
6197 return std::nullopt;
6198}
6199
6200static std::optional<const SCEV *>
6202 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6203 assert(CondExpr->getType()->isIntegerTy(1) &&
6204 TrueExpr->getType() == FalseExpr->getType() &&
6205 TrueExpr->getType()->isIntegerTy(1) &&
6206 "Unexpected operands of a select.");
6207
6208 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6209 // --> C + (umin_seq cond, x - C)
6210 //
6211 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6212 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6213 // --> C + (umin_seq ~cond, x - C)
6214
6215 // FIXME: while we can't legally model the case where both of the hands
6216 // are fully variable, we only require that the *difference* is constant.
6217 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6218 return std::nullopt;
6219
6220 const SCEV *X, *C;
6221 if (isa<SCEVConstant>(TrueExpr)) {
6222 CondExpr = SE->getNotSCEV(CondExpr);
6223 X = FalseExpr;
6224 C = TrueExpr;
6225 } else {
6226 X = TrueExpr;
6227 C = FalseExpr;
6228 }
6229 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6230 /*Sequential=*/true));
6231}
6232
6233static std::optional<const SCEV *>
6235 Value *FalseVal) {
6236 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6237 return std::nullopt;
6238
6239 const auto *SECond = SE->getSCEV(Cond);
6240 const auto *SETrue = SE->getSCEV(TrueVal);
6241 const auto *SEFalse = SE->getSCEV(FalseVal);
6242 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6243}
6244
6245const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6246 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6247 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6248 assert(TrueVal->getType() == FalseVal->getType() &&
6249 V->getType() == TrueVal->getType() &&
6250 "Types of select hands and of the result must match.");
6251
6252 // For now, only deal with i1-typed `select`s.
6253 if (!V->getType()->isIntegerTy(1))
6254 return getUnknown(V);
6255
6256 if (std::optional<const SCEV *> S =
6257 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6258 return *S;
6259
6260 return getUnknown(V);
6261}
6262
6263const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6264 Value *TrueVal,
6265 Value *FalseVal) {
6266 // Handle "constant" branch or select. This can occur for instance when a
6267 // loop pass transforms an inner loop and moves on to process the outer loop.
6268 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6269 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6270
6271 if (auto *I = dyn_cast<Instruction>(V)) {
6272 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6273 if (std::optional<const SCEV *> S =
6274 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6275 TrueVal, FalseVal))
6276 return *S;
6277 }
6278 }
6279
6280 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6281}
6282
6283/// Expand GEP instructions into add and multiply operations. This allows them
6284/// to be analyzed by regular SCEV code.
6285const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6286 assert(GEP->getSourceElementType()->isSized() &&
6287 "GEP source element type must be sized");
6288
6289 SmallVector<SCEVUse, 4> IndexExprs;
6290 for (Value *Index : GEP->indices())
6291 IndexExprs.push_back(getSCEV(Index));
6292 return getGEPExpr(GEP, IndexExprs);
6293}
6294
6295APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6296 const Instruction *CtxI) {
6298 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6299 return TrailingZeros >= BitWidth
6301 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6302 };
6303 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6304 // The result is GCD of all operands results.
6305 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6306 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6308 Res, getConstantMultiple(N->getOperand(I), CtxI));
6309 return Res;
6310 };
6311
6312 switch (S->getSCEVType()) {
6313 case scConstant:
6314 return cast<SCEVConstant>(S)->getAPInt();
6315 case scPtrToAddr:
6316 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6317 case scUDivExpr:
6318 case scVScale:
6319 return APInt(BitWidth, 1);
6320 case scTruncate: {
6321 // Only multiples that are a power of 2 will hold after truncation.
6322 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6323 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6324 return GetShiftedByZeros(TZ);
6325 }
6326 case scZeroExtend: {
6327 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6328 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6329 }
6330 case scSignExtend: {
6331 // Only multiples that are a power of 2 will hold after sext.
6332 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6333 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6334 return GetShiftedByZeros(TZ);
6335 }
6336 case scMulExpr: {
6337 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6338 if (M->hasNoUnsignedWrap()) {
6339 // The result is the product of all operand results.
6340 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6341 for (const SCEV *Operand : M->operands().drop_front())
6342 Res = Res * getConstantMultiple(Operand, CtxI);
6343 return Res;
6344 }
6345
6346 // If there are no wrap guarentees, find the trailing zeros, which is the
6347 // sum of trailing zeros for all its operands.
6348 uint32_t TZ = 0;
6349 for (const SCEV *Operand : M->operands())
6350 TZ += getMinTrailingZeros(Operand, CtxI);
6351 return GetShiftedByZeros(TZ);
6352 }
6353 case scAddExpr:
6354 case scAddRecExpr: {
6355 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6356 if (N->hasNoUnsignedWrap())
6357 return GetGCDMultiple(N);
6358 // Find the trailing bits, which is the minimum of its operands.
6359 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6360 for (const SCEV *Operand : N->operands().drop_front())
6361 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6362 return GetShiftedByZeros(TZ);
6363 }
6364 case scUMaxExpr:
6365 case scSMaxExpr:
6366 case scUMinExpr:
6367 case scSMinExpr:
6369 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6370 case scUnknown: {
6371 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6372 // the point their underlying IR instruction has been defined. If CtxI was
6373 // not provided, use:
6374 // * the first instruction in the entry block if it is an argument
6375 // * the instruction itself otherwise.
6376 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6377 if (!CtxI) {
6378 if (isa<Argument>(U->getValue()))
6379 CtxI = &*F.getEntryBlock().begin();
6380 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6381 CtxI = I;
6382 }
6383 unsigned Known =
6384 computeKnownBits(U->getValue(),
6385 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6386 .allowEphemerals(true))
6387 .countMinTrailingZeros();
6388 return GetShiftedByZeros(Known);
6389 }
6390 case scCouldNotCompute:
6391 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6392 }
6393 llvm_unreachable("Unknown SCEV kind!");
6394}
6395
6397 const Instruction *CtxI) {
6398 // Skip looking up and updating the cache if there is a context instruction,
6399 // as the result will only be valid in the specified context.
6400 if (CtxI)
6401 return getConstantMultipleImpl(S, CtxI);
6402
6403 auto I = ConstantMultipleCache.find(S);
6404 if (I != ConstantMultipleCache.end())
6405 return I->second;
6406
6407 APInt Result = getConstantMultipleImpl(S, CtxI);
6408 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6409 assert(InsertPair.second && "Should insert a new key");
6410 return InsertPair.first->second;
6411}
6412
6414 APInt Multiple = getConstantMultiple(S);
6415 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6416}
6417
6419 const Instruction *CtxI) {
6420 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6421 (unsigned)getTypeSizeInBits(S->getType()));
6422}
6423
6424/// Helper method to assign a range to V from metadata present in the IR.
6425static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6427 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6428 return getConstantRangeFromMetadata(*MD);
6429 if (const auto *CB = dyn_cast<CallBase>(V))
6430 if (std::optional<ConstantRange> Range = CB->getRange())
6431 return Range;
6432 }
6433 if (auto *A = dyn_cast<Argument>(V))
6434 if (std::optional<ConstantRange> Range = A->getRange())
6435 return Range;
6436
6437 return std::nullopt;
6438}
6439
6441 SCEVFlags NWFlags = Flags & SCEV::FlagsNoWrapMask;
6442 if (AddRec->getNoWrapFlags(NWFlags) != NWFlags) {
6443 AddRec->setNoWrapFlags(NWFlags);
6444 UnsignedRanges.erase(AddRec);
6445 SignedRanges.erase(AddRec);
6446 ConstantMultipleCache.erase(AddRec);
6447 }
6448}
6449
6450ConstantRange ScalarEvolution::
6451getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6452 const DataLayout &DL = getDataLayout();
6453
6454 unsigned BitWidth = getTypeSizeInBits(U->getType());
6455 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6456
6457 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6458 // use information about the trip count to improve our available range. Note
6459 // that the trip count independent cases are already handled by known bits.
6460 // WARNING: The definition of recurrence used here is subtly different than
6461 // the one used by AddRec (and thus most of this file). Step is allowed to
6462 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6463 // and other addrecs in the same loop (for non-affine addrecs). The code
6464 // below intentionally handles the case where step is not loop invariant.
6465 auto *P = dyn_cast<PHINode>(U->getValue());
6466 if (!P)
6467 return FullSet;
6468
6469 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6470 // even the values that are not available in these blocks may come from them,
6471 // and this leads to false-positive recurrence test.
6472 for (auto *Pred : predecessors(P->getParent()))
6473 if (!DT.isReachableFromEntry(Pred))
6474 return FullSet;
6475
6476 BinaryOperator *BO;
6477 Value *Start, *Step;
6478 if (!matchSimpleRecurrence(P, BO, Start, Step))
6479 return FullSet;
6480
6481 // If we found a recurrence in reachable code, we must be in a loop. Note
6482 // that BO might be in some subloop of L, and that's completely okay.
6483 auto *L = LI.getLoopFor(P->getParent());
6484 assert(L && L->getHeader() == P->getParent());
6485 if (!L->contains(BO->getParent()))
6486 // NOTE: This bailout should be an assert instead. However, asserting
6487 // the condition here exposes a case where LoopFusion is querying SCEV
6488 // with malformed loop information during the midst of the transform.
6489 // There doesn't appear to be an obvious fix, so for the moment bailout
6490 // until the caller issue can be fixed. PR49566 tracks the bug.
6491 return FullSet;
6492
6493 // TODO: Extend to other opcodes such as mul, and div
6494 switch (BO->getOpcode()) {
6495 default:
6496 return FullSet;
6497 case Instruction::AShr:
6498 case Instruction::LShr:
6499 case Instruction::Shl:
6500 break;
6501 };
6502
6503 if (BO->getOperand(0) != P)
6504 // TODO: Handle the power function forms some day.
6505 return FullSet;
6506
6507 unsigned TC = getSmallConstantMaxTripCount(L);
6508 if (!TC || TC >= BitWidth)
6509 return FullSet;
6510
6511 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6512 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6513 assert(KnownStart.getBitWidth() == BitWidth &&
6514 KnownStep.getBitWidth() == BitWidth);
6515
6516 // Compute total shift amount, being careful of overflow and bitwidths.
6517 auto MaxShiftAmt = KnownStep.getMaxValue();
6518 APInt TCAP(BitWidth, TC-1);
6519 bool Overflow = false;
6520 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6521 if (Overflow)
6522 return FullSet;
6523
6524 switch (BO->getOpcode()) {
6525 default:
6526 llvm_unreachable("filtered out above");
6527 case Instruction::AShr: {
6528 // For each ashr, three cases:
6529 // shift = 0 => unchanged value
6530 // saturation => 0 or -1
6531 // other => a value closer to zero (of the same sign)
6532 // Thus, the end value is closer to zero than the start.
6533 auto KnownEnd = KnownBits::ashr(KnownStart,
6534 KnownBits::makeConstant(TotalShift));
6535 if (KnownStart.isNonNegative())
6536 // Analogous to lshr (simply not yet canonicalized)
6537 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6538 KnownStart.getMaxValue() + 1);
6539 if (KnownStart.isNegative())
6540 // End >=u Start && End <=s Start
6541 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6542 KnownEnd.getMaxValue() + 1);
6543 break;
6544 }
6545 case Instruction::LShr: {
6546 // For each lshr, three cases:
6547 // shift = 0 => unchanged value
6548 // saturation => 0
6549 // other => a smaller positive number
6550 // Thus, the low end of the unsigned range is the last value produced.
6551 auto KnownEnd = KnownBits::lshr(KnownStart,
6552 KnownBits::makeConstant(TotalShift));
6553 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6554 KnownStart.getMaxValue() + 1);
6555 }
6556 case Instruction::Shl: {
6557 // Iff no bits are shifted out, value increases on every shift.
6558 auto KnownEnd = KnownBits::shl(KnownStart,
6559 KnownBits::makeConstant(TotalShift));
6560 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6561 return ConstantRange(KnownStart.getMinValue(),
6562 KnownEnd.getMaxValue() + 1);
6563 break;
6564 }
6565 };
6566 return FullSet;
6567}
6568
6569// The goal of this function is to check if recursively visiting the operands
6570// of this PHI might lead to an infinite loop. If we do see such a loop,
6571// there's no good way to break it, so we avoid analyzing such cases.
6572//
6573// getRangeRef previously used a visited set to avoid infinite loops, but this
6574// caused other issues: the result was dependent on the order of getRangeRef
6575// calls, and the interaction with createSCEVIter could cause a stack overflow
6576// in some cases (see issue #148253).
6577//
6578// FIXME: The way this is implemented is overly conservative; this checks
6579// for a few obviously safe patterns, but anything that doesn't lead to
6580// recursion is fine.
6582 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6584 return true;
6585
6586 if (all_of(PHI->operands(),
6587 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6588 return true;
6589
6590 return false;
6591}
6592
6593const ConstantRange &
6594ScalarEvolution::getRangeRefIter(const SCEV *S,
6595 ScalarEvolution::RangeSignHint SignHint) {
6596 DenseMap<const SCEV *, ConstantRange> &Cache =
6597 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6598 : SignedRanges;
6599 SmallVector<SCEVUse> WorkList;
6600 SmallPtrSet<const SCEV *, 8> Seen;
6601
6602 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6603 // SCEVUnknown PHI node.
6604 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6605 if (!Seen.insert(Expr).second)
6606 return;
6607 if (Cache.contains(Expr))
6608 return;
6609 switch (Expr->getSCEVType()) {
6610 case scUnknown:
6612 break;
6613 [[fallthrough]];
6614 case scConstant:
6615 case scVScale:
6616 case scTruncate:
6617 case scZeroExtend:
6618 case scSignExtend:
6619 case scPtrToAddr:
6620 case scAddExpr:
6621 case scMulExpr:
6622 case scUDivExpr:
6623 case scAddRecExpr:
6624 case scUMaxExpr:
6625 case scSMaxExpr:
6626 case scUMinExpr:
6627 case scSMinExpr:
6629 WorkList.push_back(Expr);
6630 break;
6631 case scCouldNotCompute:
6632 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6633 }
6634 };
6635 AddToWorklist(S);
6636
6637 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6638 for (unsigned I = 0; I != WorkList.size(); ++I) {
6639 const SCEV *P = WorkList[I];
6640 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6641 // If it is not a `SCEVUnknown`, just recurse into operands.
6642 if (!UnknownS) {
6643 for (const SCEV *Op : P->operands())
6644 AddToWorklist(Op);
6645 continue;
6646 }
6647 // `SCEVUnknown`'s require special treatment.
6648 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6649 if (!RangeRefPHIAllowedOperands(DT, P))
6650 continue;
6651 for (auto &Op : reverse(P->operands()))
6652 AddToWorklist(getSCEV(Op));
6653 }
6654 }
6655
6656 if (!WorkList.empty()) {
6657 // Use getRangeRef to compute ranges for items in the worklist in reverse
6658 // order. This will force ranges for earlier operands to be computed before
6659 // their users in most cases.
6660 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6661 getRangeRef(P, SignHint);
6662 }
6663 }
6664
6665 return getRangeRef(S, SignHint, 0);
6666}
6667
6668const APInt *ScalarEvolution::getConstantAPIntOrNull(const SCEV *S) {
6669 if (const auto *C = dyn_cast<SCEVConstant>(S))
6670 return &C->getAPInt();
6671 return nullptr;
6672}
6673
6674/// Determine the range for a particular SCEV. If SignHint is
6675/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6676/// with a "cleaner" unsigned (resp. signed) representation.
6677const ConstantRange &ScalarEvolution::getRangeRef(
6678 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6679 DenseMap<const SCEV *, ConstantRange> &Cache =
6680 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6681 : SignedRanges;
6683 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6685
6686 // See if we've computed this range already.
6687 auto I = Cache.find(S);
6688 if (I != Cache.end())
6689 return I->second;
6690
6691 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6692 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6693
6694 // Switch to iteratively computing the range for S, if it is part of a deeply
6695 // nested expression.
6697 return getRangeRefIter(S, SignHint);
6698
6699 unsigned BitWidth = getTypeSizeInBits(S->getType());
6700 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6701 using OBO = OverflowingBinaryOperator;
6702
6703 // If the value has known zeros, the maximum value will have those known zeros
6704 // as well.
6705 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6706 APInt Multiple = getNonZeroConstantMultiple(S);
6707 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6708 if (!Remainder.isZero())
6709 ConservativeResult =
6710 ConstantRange(APInt::getMinValue(BitWidth),
6711 APInt::getMaxValue(BitWidth) - Remainder + 1);
6712 }
6713 else {
6714 uint32_t TZ = getMinTrailingZeros(S);
6715 if (TZ != 0) {
6716 ConservativeResult = ConstantRange(
6718 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6719 }
6720 }
6721
6722 switch (S->getSCEVType()) {
6723 case scConstant:
6724 llvm_unreachable("Already handled above.");
6725 case scVScale:
6726 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6727 case scTruncate: {
6728 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6729 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6730 return setRange(
6731 Trunc, SignHint,
6732 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6733 }
6734 case scZeroExtend: {
6735 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6736 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6737 return setRange(
6738 ZExt, SignHint,
6739 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6740 }
6741 case scSignExtend: {
6742 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6743 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6744 return setRange(
6745 SExt, SignHint,
6746 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6747 }
6748 case scPtrToAddr: {
6749 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6750 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6751 return setRange(Cast, SignHint, X);
6752 }
6753 case scAddExpr: {
6754 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6755 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6756 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6757 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6758 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6759 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6760 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6761 ConservativeResult =
6762 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6763 }
6764 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6765 unsigned WrapType = OBO::AnyWrap;
6766 if (Add->hasNoSignedWrap())
6767 WrapType |= OBO::NoSignedWrap;
6768 if (Add->hasNoUnsignedWrap())
6769 WrapType |= OBO::NoUnsignedWrap;
6770 for (const SCEV *Op : drop_begin(Add->operands()))
6771 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6772 RangeType);
6773 return setRange(Add, SignHint,
6774 ConservativeResult.intersectWith(X, RangeType));
6775 }
6776 case scMulExpr: {
6777 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6778 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6779 for (const SCEV *Op : drop_begin(Mul->operands()))
6780 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6781 return setRange(Mul, SignHint,
6782 ConservativeResult.intersectWith(X, RangeType));
6783 }
6784 case scUDivExpr: {
6785 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6786 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6787 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6788 return setRange(UDiv, SignHint,
6789 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6790 }
6791 case scAddRecExpr: {
6792 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6793 // If there's no unsigned wrap, the value will never be less than its
6794 // initial value.
6795 if (AddRec->hasNoUnsignedWrap()) {
6796 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6797 if (!UnsignedMinValue.isZero())
6798 ConservativeResult = ConservativeResult.intersectWith(
6799 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6800 }
6801
6802 // If there's no signed wrap, and all the operands except initial value have
6803 // the same sign or zero, the value won't ever be:
6804 // 1: smaller than initial value if operands are non negative,
6805 // 2: bigger than initial value if operands are non positive.
6806 // For both cases, value can not cross signed min/max boundary.
6807 if (AddRec->hasNoSignedWrap()) {
6808 bool AllNonNeg = true;
6809 bool AllNonPos = true;
6810 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6811 if (!isKnownNonNegative(AddRec->getOperand(i)))
6812 AllNonNeg = false;
6813 if (!isKnownNonPositive(AddRec->getOperand(i)))
6814 AllNonPos = false;
6815 }
6816 if (AllNonNeg)
6817 ConservativeResult = ConservativeResult.intersectWith(
6820 RangeType);
6821 else if (AllNonPos)
6822 ConservativeResult = ConservativeResult.intersectWith(
6824 getSignedRangeMax(AddRec->getStart()) +
6825 1),
6826 RangeType);
6827 }
6828
6829 // TODO: non-affine addrec
6830 if (AddRec->isAffine()) {
6831 const SCEV *MaxBEScev =
6833 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6834 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6835
6836 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6837 // MaxBECount's active bits are all <= AddRec's bit width.
6838 if (MaxBECount.getBitWidth() > BitWidth &&
6839 MaxBECount.getActiveBits() <= BitWidth)
6840 MaxBECount = MaxBECount.trunc(BitWidth);
6841 else if (MaxBECount.getBitWidth() < BitWidth)
6842 MaxBECount = MaxBECount.zext(BitWidth);
6843
6844 if (MaxBECount.getBitWidth() == BitWidth) {
6845 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
6846 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6847 ConservativeResult =
6848 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
6849 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
6850
6851 auto RangeFromFactoring = getRangeViaFactoring(
6852 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
6853 ConservativeResult =
6854 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
6855 }
6856 }
6857
6858 // Now try symbolic BE count and more powerful methods.
6860 const SCEV *SymbolicMaxBECount =
6862 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
6863 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
6864 AddRec->hasNoSelfWrap()) {
6865 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
6866 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
6867 ConservativeResult =
6868 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
6869 }
6870 }
6871 }
6872
6873 return setRange(AddRec, SignHint, std::move(ConservativeResult));
6874 }
6875 case scUMaxExpr:
6876 case scSMaxExpr:
6877 case scUMinExpr:
6878 case scSMinExpr:
6879 case scSequentialUMinExpr: {
6881 switch (S->getSCEVType()) {
6882 case scUMaxExpr:
6883 ID = Intrinsic::umax;
6884 break;
6885 case scSMaxExpr:
6886 ID = Intrinsic::smax;
6887 break;
6888 case scUMinExpr:
6890 ID = Intrinsic::umin;
6891 break;
6892 case scSMinExpr:
6893 ID = Intrinsic::smin;
6894 break;
6895 default:
6896 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
6897 }
6898
6899 const auto *NAry = cast<SCEVNAryExpr>(S);
6900 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
6901 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
6902 X = X.intrinsic(
6903 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
6904 return setRange(S, SignHint,
6905 ConservativeResult.intersectWith(X, RangeType));
6906 }
6907 case scUnknown: {
6908 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6909 Value *V = U->getValue();
6910
6911 // Check if the IR explicitly contains !range metadata.
6912 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
6913 if (MDRange)
6914 ConservativeResult =
6915 ConservativeResult.intersectWith(*MDRange, RangeType);
6916
6917 // Use facts about recurrences in the underlying IR. Note that add
6918 // recurrences are AddRecExprs and thus don't hit this path. This
6919 // primarily handles shift recurrences.
6920 auto CR = getRangeForUnknownRecurrence(U);
6921 ConservativeResult = ConservativeResult.intersectWith(CR);
6922
6923 // See if ValueTracking can give us a useful range.
6924 const DataLayout &DL = getDataLayout();
6925 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
6926 if (Known.getBitWidth() != BitWidth)
6927 Known = Known.zextOrTrunc(BitWidth);
6928
6929 // ValueTracking may be able to compute a tighter result for the number of
6930 // sign bits than for the value of those sign bits.
6931 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
6932 if (U->getType()->isPointerTy()) {
6933 // NS counts the sign bits of the whole pointer; drop those above the
6934 // index bits.
6935 unsigned PtrIdxDiff =
6936 DL.getPointerTypeSizeInBits(U->getType()) - BitWidth;
6937 NS = NS > PtrIdxDiff ? NS - PtrIdxDiff : 1;
6938 }
6939
6940 if (NS > 1) {
6941 // If we know any of the sign bits, we know all of the sign bits.
6942 if (!Known.Zero.getHiBits(NS).isZero())
6943 Known.Zero.setHighBits(NS);
6944 if (!Known.One.getHiBits(NS).isZero())
6945 Known.One.setHighBits(NS);
6946 }
6947
6948 if (Known.getMinValue() != Known.getMaxValue() + 1)
6949 ConservativeResult = ConservativeResult.intersectWith(
6950 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
6951 RangeType);
6952 if (NS > 1)
6953 ConservativeResult = ConservativeResult.intersectWith(
6954 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
6955 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
6956 RangeType);
6957
6958 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
6959 // Strengthen the range if the underlying IR value is a
6960 // global/alloca/heap allocation using the size of the object.
6961 bool CanBeNull;
6962 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
6963 DL, CanBeNull, /*CanBeFreed=*/nullptr);
6964 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
6965 // The highest address the object can start is DerefBytes bytes before
6966 // the end (unsigned max value). If this value is not a multiple of the
6967 // alignment, the last possible start value is the next lowest multiple
6968 // of the alignment. Note: The computations below cannot overflow,
6969 // because if they would there's no possible start address for the
6970 // object.
6971 APInt MaxVal =
6972 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
6973 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
6974 uint64_t Rem = MaxVal.urem(Align);
6975 MaxVal -= APInt(BitWidth, Rem);
6976 APInt MinVal = APInt::getZero(BitWidth);
6977 if (llvm::isKnownNonZero(V, DL))
6978 MinVal = Align;
6979 ConservativeResult = ConservativeResult.intersectWith(
6980 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
6981 }
6982 }
6983
6984 // A range of Phi is a subset of union of all ranges of its input.
6985 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
6986 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
6987 // AddRecs; return the range for the corresponding AddRec.
6988 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
6989 return getRangeRef(AR, SignHint, Depth + 1);
6990
6991 // Make sure that we do not run over cycled Phis.
6992 if (RangeRefPHIAllowedOperands(DT, Phi)) {
6993 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
6994
6995 for (const auto &Op : Phi->operands()) {
6996 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
6997 RangeFromOps = RangeFromOps.unionWith(OpRange);
6998 // No point to continue if we already have a full set.
6999 if (RangeFromOps.isFullSet())
7000 break;
7001 }
7002 ConservativeResult =
7003 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7004 }
7005 }
7006
7007 // vscale can't be equal to zero
7008 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7009 if (II->getIntrinsicID() == Intrinsic::vscale) {
7010 ConstantRange Disallowed = APInt::getZero(BitWidth);
7011 ConservativeResult = ConservativeResult.difference(Disallowed);
7012 }
7013
7014 return setRange(U, SignHint, std::move(ConservativeResult));
7015 }
7016 case scCouldNotCompute:
7017 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7018 }
7019
7020 return setRange(S, SignHint, std::move(ConservativeResult));
7021}
7022
7023// Given a StartRange, Step and MaxBECount for an expression compute a range of
7024// values that the expression can take. Initially, the expression has a value
7025// from StartRange and then is changed by Step up to MaxBECount times. Signed
7026// argument defines if we treat Step as signed or unsigned. The second return
7027// value indicates that no wrapping occurred.
7028static std::pair<ConstantRange, bool>
7030 const APInt &MaxBECount, bool Signed) {
7031 unsigned BitWidth = Step.getBitWidth();
7032 assert(BitWidth == StartRange.getBitWidth() &&
7033 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7034 // If either Step or MaxBECount is 0, then the expression won't change, and we
7035 // just need to return the initial range.
7036 if (Step == 0 || MaxBECount == 0)
7037 return {StartRange, true};
7038
7039 // If we don't know anything about the initial value (i.e. StartRange is
7040 // FullRange), then we don't know anything about the final range either.
7041 // Return FullRange.
7042 if (StartRange.isFullSet())
7043 return {ConstantRange::getFull(BitWidth), false};
7044
7045 // If Step is signed and negative, then we use its absolute value, but we also
7046 // note that we're moving in the opposite direction.
7047 bool Descending = Signed && Step.isNegative();
7048
7049 if (Signed)
7050 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7051 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7052 // This equations hold true due to the well-defined wrap-around behavior of
7053 // APInt.
7054 Step = Step.abs();
7055
7056 // Check if Offset is more than full span of BitWidth. If it is, the
7057 // expression is guaranteed to overflow.
7058 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7059 return {ConstantRange::getFull(BitWidth), false};
7060
7061 // Offset is by how much the expression can change. Checks above guarantee no
7062 // overflow here.
7063 APInt Offset = Step * MaxBECount;
7064
7065 // Minimum value of the final range will match the minimal value of StartRange
7066 // if the expression is increasing and will be decreased by Offset otherwise.
7067 // Maximum value of the final range will match the maximal value of StartRange
7068 // if the expression is decreasing and will be increased by Offset otherwise.
7069 APInt StartLower = StartRange.getLower();
7070 APInt StartUpper = StartRange.getUpper() - 1;
7071 bool Overflow;
7072 APInt MovedBoundary;
7073 if (Signed) {
7074 // This does not use sadd_ov, as we want to check overflow for a signed
7075 // start with an unsigned offset.
7076 if (Descending) {
7077 MovedBoundary = StartLower - std::move(Offset);
7078 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7079 } else {
7080 MovedBoundary = StartUpper + std::move(Offset);
7081 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7082 }
7083 } else {
7084 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7085 Overflow |= StartRange.isWrappedSet();
7086 }
7087
7088 // It's possible that the new minimum/maximum value will fall into the initial
7089 // range (due to wrap around). This means that the expression can take any
7090 // value in this bitwidth, and we have to return full range.
7091 if (StartRange.contains(MovedBoundary))
7092 return {ConstantRange::getFull(BitWidth), false};
7093
7094 APInt NewLower =
7095 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7096 APInt NewUpper =
7097 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7098 NewUpper += 1;
7099
7100 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7101 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7102 !Overflow};
7103}
7104
7105std::pair<ConstantRange, SCEVFlags>
7106ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7107 const APInt &MaxBECount) {
7108 assert(getTypeSizeInBits(Start->getType()) ==
7109 getTypeSizeInBits(Step->getType()) &&
7110 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7111 "mismatched bit widths");
7112
7113 // First, consider step signed.
7114 ConstantRange StartSRange = getSignedRange(Start);
7115 ConstantRange StepSRange = getSignedRange(Step);
7116
7117 // If Step can be both positive and negative, we need to find ranges for the
7118 // maximum absolute step values in both directions and union them.
7119 auto [SR, NSW] = getRangeForAffineARHelper(
7120 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7121 // A singleton step has identical signed bounds, so the second computation
7122 // would produce the same range and no-wrap result.
7123 if (!StepSRange.isSingleElement()) {
7124 auto [SRMax, NSWMax] = getRangeForAffineARHelper(
7125 StepSRange.getSignedMax(), StartSRange, MaxBECount, /*Signed=*/true);
7126 SR = SR.unionWith(SRMax);
7127 NSW &= NSWMax;
7128 }
7129
7130 // Next, consider step unsigned.
7131 auto [UR, NUW] = getRangeForAffineARHelper(
7132 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7133 /*Signed=*/false);
7134
7136 if (NUW)
7138 if (NSW)
7140
7141 // Finally, intersect signed and unsigned ranges.
7142 return {SR.intersectWith(UR, ConstantRange::Smallest), Flags};
7143}
7144
7145ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7146 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7147 ScalarEvolution::RangeSignHint SignHint) {
7148 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7149 assert(AddRec->hasNoSelfWrap() &&
7150 "This only works for non-self-wrapping AddRecs!");
7151 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7152 const SCEV *Step = AddRec->getStepRecurrence(*this);
7153 // Only deal with constant step to save compile time.
7154 if (!isa<SCEVConstant>(Step))
7155 return ConstantRange::getFull(BitWidth);
7156 // Let's make sure that we can prove that we do not self-wrap during
7157 // MaxBECount iterations. We need this because MaxBECount is a maximum
7158 // iteration count estimate, and we might infer nw from some exit for which we
7159 // do not know max exit count (or any other side reasoning).
7160 // TODO: Turn into assert at some point.
7161 if (getTypeSizeInBits(MaxBECount->getType()) >
7162 getTypeSizeInBits(AddRec->getType()))
7163 return ConstantRange::getFull(BitWidth);
7164 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7165 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7166 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7167 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7168 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7169 MaxItersWithoutWrap))
7170 return ConstantRange::getFull(BitWidth);
7171
7172 ICmpInst::Predicate LEPred =
7174 ICmpInst::Predicate GEPred =
7176 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7177
7178 // We know that there is no self-wrap. Let's take Start and End values and
7179 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7180 // the iteration. They either lie inside the range [Min(Start, End),
7181 // Max(Start, End)] or outside it:
7182 //
7183 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7184 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7185 //
7186 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7187 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7188 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7189 // Start <= End and step is positive, or Start >= End and step is negative.
7190 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7191 ConstantRange StartRange = getRangeRef(Start, SignHint);
7192 ConstantRange EndRange = getRangeRef(End, SignHint);
7193 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7194 // If they already cover full iteration space, we will know nothing useful
7195 // even if we prove what we want to prove.
7196 if (RangeBetween.isFullSet())
7197 return RangeBetween;
7198 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7199 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7200 : RangeBetween.isWrappedSet();
7201 if (IsWrappedSet)
7202 return ConstantRange::getFull(BitWidth);
7203
7204 if (isKnownPositive(Step) &&
7205 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7206 return RangeBetween;
7207 if (isKnownNegative(Step) &&
7208 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7209 return RangeBetween;
7210 return ConstantRange::getFull(BitWidth);
7211}
7212
7213ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7214 const SCEV *Step,
7215 const APInt &MaxBECount) {
7216 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7217 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7218
7219 unsigned BitWidth = MaxBECount.getBitWidth();
7220 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7221 getTypeSizeInBits(Step->getType()) == BitWidth &&
7222 "mismatched bit widths");
7223
7224 struct SelectPattern {
7225 Value *Condition = nullptr;
7226 APInt TrueValue;
7227 APInt FalseValue;
7228
7229 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7230 const SCEV *S) {
7231 std::optional<unsigned> CastOp;
7232 APInt Offset(BitWidth, 0);
7233
7235 "Should be!");
7236
7237 // Peel off a constant offset. In the future we could consider being
7238 // smarter here and handle {Start+Step,+,Step} too.
7239 const APInt *Off;
7240 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7241 Offset = *Off;
7242
7243 // Peel off a cast operation
7244 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7245 CastOp = SCast->getSCEVType();
7246 S = SCast->getOperand();
7247 }
7248
7249 using namespace llvm::PatternMatch;
7250
7251 auto *SU = dyn_cast<SCEVUnknown>(S);
7252 const APInt *TrueVal, *FalseVal;
7253 if (!SU ||
7254 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7255 m_APInt(FalseVal)))) {
7256 Condition = nullptr;
7257 return;
7258 }
7259
7260 TrueValue = *TrueVal;
7261 FalseValue = *FalseVal;
7262
7263 // Re-apply the cast we peeled off earlier
7264 if (CastOp)
7265 switch (*CastOp) {
7266 default:
7267 llvm_unreachable("Unknown SCEV cast type!");
7268
7269 case scTruncate:
7270 TrueValue = TrueValue.trunc(BitWidth);
7271 FalseValue = FalseValue.trunc(BitWidth);
7272 break;
7273 case scZeroExtend:
7274 TrueValue = TrueValue.zext(BitWidth);
7275 FalseValue = FalseValue.zext(BitWidth);
7276 break;
7277 case scSignExtend:
7278 TrueValue = TrueValue.sext(BitWidth);
7279 FalseValue = FalseValue.sext(BitWidth);
7280 break;
7281 }
7282
7283 // Re-apply the constant offset we peeled off earlier
7284 TrueValue += Offset;
7285 FalseValue += Offset;
7286 }
7287
7288 bool isRecognized() { return Condition != nullptr; }
7289 };
7290
7291 SelectPattern StartPattern(*this, BitWidth, Start);
7292 if (!StartPattern.isRecognized())
7293 return ConstantRange::getFull(BitWidth);
7294
7295 SelectPattern StepPattern(*this, BitWidth, Step);
7296 if (!StepPattern.isRecognized())
7297 return ConstantRange::getFull(BitWidth);
7298
7299 if (StartPattern.Condition != StepPattern.Condition) {
7300 // We don't handle this case today; but we could, by considering four
7301 // possibilities below instead of two. I'm not sure if there are cases where
7302 // that will help over what getRange already does, though.
7303 return ConstantRange::getFull(BitWidth);
7304 }
7305
7306 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7307 // construct arbitrary general SCEV expressions here. This function is called
7308 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7309 // say) can end up caching a suboptimal value.
7310
7311 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7312 // C2352 and C2512 (otherwise it isn't needed).
7313
7314 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7315 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7316 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7317 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7318
7319 ConstantRange TrueRange =
7320 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7321 ConstantRange FalseRange =
7322 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7323
7324 return TrueRange.unionWith(FalseRange);
7325}
7326
7327SCEVFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7328 if (isa<ConstantExpr>(V))
7329 return SCEV::FlagNone;
7330 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7331
7332 // Return early if there are no flags to propagate to the SCEV.
7334 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7335 PDI && PDI->isDisjoint()) {
7337 } else {
7338 if (BinOp->hasNoUnsignedWrap())
7340 if (BinOp->hasNoSignedWrap())
7342 }
7343 if (Flags == SCEV::FlagNone)
7344 return SCEV::FlagNone;
7345
7346 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagNone;
7347}
7348
7349const Instruction *
7350ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7351 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7352 return &*AddRec->getLoop()->getHeader()->begin();
7353 if (auto *U = dyn_cast<SCEVUnknown>(S))
7354 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7355 return I;
7356 return nullptr;
7357}
7358
7359const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7360 bool &Precise) {
7361 Precise = true;
7362 // Do a bounded search of the def relation of the requested SCEVs.
7363 SmallPtrSet<const SCEV *, 16> Visited;
7364 SmallVector<SCEVUse> Worklist;
7365 auto pushOp = [&](const SCEV *S) {
7366 if (!Visited.insert(S).second)
7367 return;
7368 // Threshold of 30 here is arbitrary.
7369 if (Visited.size() > 30) {
7370 Precise = false;
7371 return;
7372 }
7373 Worklist.push_back(S);
7374 };
7375
7376 for (SCEVUse S : Ops)
7377 pushOp(S);
7378
7379 const Instruction *Bound = nullptr;
7380 while (!Worklist.empty()) {
7381 SCEVUse S = Worklist.pop_back_val();
7382 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7383 if (!Bound || DT.dominates(Bound, DefI))
7384 Bound = DefI;
7385 } else {
7386 for (SCEVUse Op : S->operands())
7387 pushOp(Op);
7388 }
7389 }
7390 return Bound ? Bound : &*F.getEntryBlock().begin();
7391}
7392
7393const Instruction *
7394ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7395 bool Discard;
7396 return getDefiningScopeBound(Ops, Discard);
7397}
7398
7399bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7400 const Instruction *B) {
7401 if (A->getParent() == B->getParent() &&
7403 B->getIterator()))
7404 return true;
7405
7406 auto *BLoop = LI.getLoopFor(B->getParent());
7407 if (BLoop && BLoop->getHeader() == B->getParent() &&
7408 BLoop->getLoopPreheader() == A->getParent() &&
7410 A->getParent()->end()) &&
7411 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7412 B->getIterator()))
7413 return true;
7414 return false;
7415}
7416
7418 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7419 visitAll(Op, PC);
7420 return PC.MaybePoison.empty();
7421}
7422
7423bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7424 return !SCEVExprContains(Op, [this](const SCEV *S) {
7425 const SCEV *Op1;
7426 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7427 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7428 // is a non-zero constant, we have to assume the UDiv may be UB.
7429 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7430 });
7431}
7432
7433bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7434 // Only proceed if we can prove that I does not yield poison.
7436 return false;
7437
7438 // At this point we know that if I is executed, then it does not wrap
7439 // according to at least one of NSW or NUW. If I is not executed, then we do
7440 // not know if the calculation that I represents would wrap. Multiple
7441 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7442 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7443 // derived from other instructions that map to the same SCEV. We cannot make
7444 // that guarantee for cases where I is not executed. So we need to find a
7445 // upper bound on the defining scope for the SCEV, and prove that I is
7446 // executed every time we enter that scope. When the bounding scope is a
7447 // loop (the common case), this is equivalent to proving I executes on every
7448 // iteration of that loop.
7449 SmallVector<SCEVUse> SCEVOps;
7450 for (const Use &Op : I->operands()) {
7451 // I could be an extractvalue from a call to an overflow intrinsic.
7452 // TODO: We can do better here in some cases.
7453 if (isSCEVable(Op->getType()))
7454 SCEVOps.push_back(getSCEV(Op));
7455 }
7456 auto *DefI = getDefiningScopeBound(SCEVOps);
7457 return isGuaranteedToTransferExecutionTo(DefI, I);
7458}
7459
7460bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7461 // If we know that \c I can never be poison period, then that's enough.
7462 if (isSCEVExprNeverPoison(I))
7463 return true;
7464
7465 // If the loop only has one exit, then we know that, if the loop is entered,
7466 // any instruction dominating that exit will be executed. If any such
7467 // instruction would result in UB, the addrec cannot be poison.
7468 //
7469 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7470 // also handles uses outside the loop header (they just need to dominate the
7471 // single exit).
7472
7473 auto *ExitingBB = L->getExitingBlock();
7474 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7475 return false;
7476
7477 SmallPtrSet<const Value *, 16> KnownPoison;
7479
7480 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7481 // things that are known to be poison under that assumption go on the
7482 // Worklist.
7483 KnownPoison.insert(I);
7484 Worklist.push_back(I);
7485
7486 while (!Worklist.empty()) {
7487 const Instruction *Poison = Worklist.pop_back_val();
7488
7489 for (const Use &U : Poison->uses()) {
7490 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7491 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7492 DT.dominates(PoisonUser->getParent(), ExitingBB))
7493 return true;
7494
7495 if (propagatesPoison(U) && L->contains(PoisonUser))
7496 if (KnownPoison.insert(PoisonUser).second)
7497 Worklist.push_back(PoisonUser);
7498 }
7499 }
7500
7501 return false;
7502}
7503
7504ScalarEvolution::LoopProperties
7505ScalarEvolution::getLoopProperties(const Loop *L) {
7506 using LoopProperties = ScalarEvolution::LoopProperties;
7507
7508 auto Itr = LoopPropertiesCache.find(L);
7509 if (Itr == LoopPropertiesCache.end()) {
7510 auto HasSideEffects = [](Instruction *I) {
7511 if (auto *SI = dyn_cast<StoreInst>(I))
7512 return !SI->isSimple();
7513
7514 if (I->mayThrow())
7515 return true;
7516
7517 // Non-volatile memset / memcpy do not count as side-effect for forward
7518 // progress.
7519 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7520 return false;
7521
7522 // Droppable intrinsics only model a memory write; they are not progress.
7523 if (I->isDroppable())
7524 return false;
7525
7526 return I->mayWriteToMemory();
7527 };
7528
7529 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7530 /*HasNoSideEffects*/ true};
7531
7532 for (auto *BB : L->getBlocks())
7533 for (auto &I : *BB) {
7535 LP.HasNoAbnormalExits = false;
7536 if (HasSideEffects(&I))
7537 LP.HasNoSideEffects = false;
7538 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7539 break; // We're already as pessimistic as we can get.
7540 }
7541
7542 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7543 assert(InsertPair.second && "We just checked!");
7544 Itr = InsertPair.first;
7545 }
7546
7547 return Itr->second;
7548}
7549
7551 // A mustprogress loop without side effects must be finite.
7552 // TODO: The check used here is very conservative. It's only *specific*
7553 // side effects which are well defined in infinite loops.
7554 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7555}
7556
7557const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7558 // Worklist item with a Value and a bool indicating whether all operands have
7559 // been visited already.
7562
7563 Stack.emplace_back(V, false);
7564 while (!Stack.empty()) {
7565 auto E = Stack.back();
7566 Value *CurV = E.getPointer();
7567
7568 if (getExistingSCEV(CurV)) {
7569 Stack.pop_back();
7570 continue;
7571 }
7572
7574 const SCEV *CreatedSCEV = nullptr;
7575 // If all operands have been visited already, create the SCEV.
7576 if (E.getInt()) {
7577 CreatedSCEV = createSCEV(CurV);
7578 } else {
7579 // Otherwise get the operands we need to create SCEV's for before creating
7580 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7581 // just use it.
7582 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7583 }
7584
7585 if (CreatedSCEV) {
7586 insertValueToMap(CurV, CreatedSCEV);
7587 Stack.pop_back();
7588 } else {
7589 Stack.back().setInt(true);
7590 // Queue its operands which need to be constructed.
7591 for (Value *Op : Ops)
7592 Stack.emplace_back(Op, false);
7593 }
7594 }
7595
7596 return getExistingSCEV(V);
7597}
7598
7599const SCEV *
7600ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7601 if (!isSCEVable(V->getType()))
7602 return getUnknown(V);
7603
7604 if (Instruction *I = dyn_cast<Instruction>(V)) {
7605 // Don't attempt to analyze instructions in blocks that aren't
7606 // reachable. Such instructions don't matter, and they aren't required
7607 // to obey basic rules for definitions dominating uses which this
7608 // analysis depends on.
7609 if (!DT.isReachableFromEntry(I->getParent()))
7610 return getUnknown(PoisonValue::get(V->getType()));
7611 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7612 return getConstant(CI);
7613 else if (isa<GlobalAlias>(V))
7614 return getUnknown(V);
7615 else if (!isa<ConstantExpr>(V))
7616 return getUnknown(V);
7617
7619 if (auto BO = MatchBinaryOp(U, DT)) {
7620 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7621 switch (BO->Opcode) {
7622 case Instruction::Add:
7623 case Instruction::Mul: {
7624 // For additions and multiplications, traverse add/mul chains for which we
7625 // can potentially create a single SCEV, to reduce the number of
7626 // get{Add,Mul}Expr calls.
7627 do {
7628 if (BO->Op) {
7629 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7630 Ops.push_back(BO->Op);
7631 break;
7632 }
7633 }
7634 Ops.push_back(BO->RHS);
7635 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7636 if (!NewBO ||
7637 (BO->Opcode == Instruction::Add &&
7638 (NewBO->Opcode != Instruction::Add &&
7639 NewBO->Opcode != Instruction::Sub)) ||
7640 (BO->Opcode == Instruction::Mul &&
7641 NewBO->Opcode != Instruction::Mul)) {
7642 Ops.push_back(BO->LHS);
7643 break;
7644 }
7645 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7646 // requires a SCEV for the LHS.
7647 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7648 auto *I = dyn_cast<Instruction>(BO->Op);
7649 if (I && programUndefinedIfPoison(I)) {
7650 Ops.push_back(BO->LHS);
7651 break;
7652 }
7653 }
7654 BO = NewBO;
7655 } while (true);
7656 return nullptr;
7657 }
7658 case Instruction::Sub:
7659 case Instruction::UDiv:
7660 case Instruction::URem:
7661 break;
7662 case Instruction::AShr:
7663 case Instruction::Shl:
7664 case Instruction::Xor:
7665 if (!IsConstArg)
7666 return nullptr;
7667 break;
7668 case Instruction::And:
7669 case Instruction::Or:
7670 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7671 return nullptr;
7672 break;
7673 case Instruction::LShr:
7674 return getUnknown(V);
7675 default:
7676 llvm_unreachable("Unhandled binop");
7677 break;
7678 }
7679
7680 Ops.push_back(BO->LHS);
7681 Ops.push_back(BO->RHS);
7682 return nullptr;
7683 }
7684
7685 switch (U->getOpcode()) {
7686 case Instruction::Trunc:
7687 case Instruction::ZExt:
7688 case Instruction::SExt:
7689 case Instruction::PtrToAddr:
7690 case Instruction::PtrToInt:
7691 Ops.push_back(U->getOperand(0));
7692 return nullptr;
7693
7694 case Instruction::BitCast:
7695 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7696 Ops.push_back(U->getOperand(0));
7697 return nullptr;
7698 }
7699 return getUnknown(V);
7700
7701 case Instruction::SDiv:
7702 case Instruction::SRem:
7703 Ops.push_back(U->getOperand(0));
7704 Ops.push_back(U->getOperand(1));
7705 return nullptr;
7706
7707 case Instruction::GetElementPtr:
7708 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7709 "GEP source element type must be sized");
7710 llvm::append_range(Ops, U->operands());
7711 return nullptr;
7712
7713 case Instruction::IntToPtr:
7714 return getUnknown(V);
7715
7716 case Instruction::PHI:
7717 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7718 // relevant nodes for each of them.
7719 //
7720 // The first is just to call simplifyInstruction, and get something back
7721 // that isn't a PHI.
7722 if (Value *V = simplifyInstruction(
7723 cast<PHINode>(U),
7724 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7725 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7726 assert(V);
7727 Ops.push_back(V);
7728 return nullptr;
7729 }
7730 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7731 // operands which all perform the same operation, but haven't been
7732 // CSE'ed for whatever reason.
7733 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7734 assert(BO);
7735 Ops.push_back(BO);
7736 return nullptr;
7737 }
7738 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7739 // is equivalent to a select, and analyzes it like a select.
7740 {
7741 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7743 assert(Cond);
7744 assert(LHS);
7745 assert(RHS);
7746 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7747 Ops.push_back(CondICmp->getOperand(0));
7748 Ops.push_back(CondICmp->getOperand(1));
7749 }
7750 Ops.push_back(Cond);
7751 Ops.push_back(LHS);
7752 Ops.push_back(RHS);
7753 return nullptr;
7754 }
7755 }
7756 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7757 // so just construct it recursively.
7758 //
7759 // In addition to getNodeForPHI, also construct nodes which might be needed
7760 // by getRangeRef.
7762 for (Value *V : cast<PHINode>(U)->operands())
7763 Ops.push_back(V);
7764 return nullptr;
7765 }
7766 return nullptr;
7767
7768 case Instruction::Select: {
7769 // Check if U is a select that can be simplified to a SCEVUnknown.
7770 auto CanSimplifyToUnknown = [this, U]() {
7771 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7772 return false;
7773
7774 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7775 if (!ICI)
7776 return false;
7777 Value *LHS = ICI->getOperand(0);
7778 Value *RHS = ICI->getOperand(1);
7779 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7780 ICI->getPredicate() == CmpInst::ICMP_NE) {
7782 return true;
7783 } else if (getTypeSizeInBits(LHS->getType()) >
7784 getTypeSizeInBits(U->getType()))
7785 return true;
7786 return false;
7787 };
7788 if (CanSimplifyToUnknown())
7789 return getUnknown(U);
7790
7791 llvm::append_range(Ops, U->operands());
7792 return nullptr;
7793 break;
7794 }
7795 case Instruction::Call:
7796 case Instruction::Invoke:
7797 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7798 Ops.push_back(RV);
7799 return nullptr;
7800 }
7801
7802 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7803 switch (II->getIntrinsicID()) {
7804 case Intrinsic::abs:
7805 Ops.push_back(II->getArgOperand(0));
7806 return nullptr;
7807 case Intrinsic::umax:
7808 case Intrinsic::umin:
7809 case Intrinsic::smax:
7810 case Intrinsic::smin:
7811 case Intrinsic::usub_sat:
7812 case Intrinsic::uadd_sat:
7813 Ops.push_back(II->getArgOperand(0));
7814 Ops.push_back(II->getArgOperand(1));
7815 return nullptr;
7816 case Intrinsic::start_loop_iterations:
7817 case Intrinsic::annotation:
7818 case Intrinsic::ptr_annotation:
7819 Ops.push_back(II->getArgOperand(0));
7820 return nullptr;
7821 default:
7822 break;
7823 }
7824 }
7825 break;
7826 }
7827
7828 return nullptr;
7829}
7830
7831const SCEV *ScalarEvolution::createSCEV(Value *V) {
7832 if (!isSCEVable(V->getType()))
7833 return getUnknown(V);
7834
7835 if (Instruction *I = dyn_cast<Instruction>(V)) {
7836 // Don't attempt to analyze instructions in blocks that aren't
7837 // reachable. Such instructions don't matter, and they aren't required
7838 // to obey basic rules for definitions dominating uses which this
7839 // analysis depends on.
7840 if (!DT.isReachableFromEntry(I->getParent()))
7841 return getUnknown(PoisonValue::get(V->getType()));
7842 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7843 return getConstant(CI);
7844 else if (isa<GlobalAlias>(V))
7845 return getUnknown(V);
7846 else if (!isa<ConstantExpr>(V))
7847 return getUnknown(V);
7848
7849 const SCEV *LHS;
7850 const SCEV *RHS;
7851
7853 if (auto BO = MatchBinaryOp(U, DT)) {
7854 switch (BO->Opcode) {
7855 case Instruction::Add: {
7856 // The simple thing to do would be to just call getSCEV on both operands
7857 // and call getAddExpr with the result. However if we're looking at a
7858 // bunch of things all added together, this can be quite inefficient,
7859 // because it leads to N-1 getAddExpr calls for N ultimate operands.
7860 // Instead, gather up all the operands and make a single getAddExpr call.
7861 // LLVM IR canonical form means we need only traverse the left operands.
7863 do {
7864 if (BO->Op) {
7865 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7866 AddOps.push_back(OpSCEV);
7867 break;
7868 }
7869
7870 // If a NUW or NSW flag can be applied to the SCEV for this
7871 // addition, then compute the SCEV for this addition by itself
7872 // with a separate call to getAddExpr. We need to do that
7873 // instead of pushing the operands of the addition onto AddOps,
7874 // since the flags are only known to apply to this particular
7875 // addition - they may not apply to other additions that can be
7876 // formed with operands from AddOps.
7877 const SCEV *RHS = getSCEV(BO->RHS);
7878 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7879 if (Flags != SCEV::FlagNone) {
7880 const SCEV *LHS = getSCEV(BO->LHS);
7881 if (BO->Opcode == Instruction::Sub)
7882 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
7883 else
7884 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
7885 break;
7886 }
7887 }
7888
7889 if (BO->Opcode == Instruction::Sub)
7890 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
7891 else
7892 AddOps.push_back(getSCEV(BO->RHS));
7893
7894 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7895 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
7896 NewBO->Opcode != Instruction::Sub)) {
7897 AddOps.push_back(getSCEV(BO->LHS));
7898 break;
7899 }
7900 BO = NewBO;
7901 } while (true);
7902
7903 return getAddExpr(AddOps);
7904 }
7905
7906 case Instruction::Mul: {
7908 do {
7909 if (BO->Op) {
7910 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
7911 MulOps.push_back(OpSCEV);
7912 break;
7913 }
7914
7915 SCEVFlags Flags = getNoWrapFlagsFromUB(BO->Op);
7916 if (Flags != SCEV::FlagNone) {
7917 LHS = getSCEV(BO->LHS);
7918 RHS = getSCEV(BO->RHS);
7919 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
7920 break;
7921 }
7922 }
7923
7924 MulOps.push_back(getSCEV(BO->RHS));
7925 auto NewBO = MatchBinaryOp(BO->LHS, DT);
7926 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
7927 MulOps.push_back(getSCEV(BO->LHS));
7928 break;
7929 }
7930 BO = NewBO;
7931 } while (true);
7932
7933 return getMulExpr(MulOps);
7934 }
7935 case Instruction::UDiv:
7936 LHS = getSCEV(BO->LHS);
7937 RHS = getSCEV(BO->RHS);
7938 return getUDivExpr(LHS, RHS);
7939 case Instruction::URem:
7940 LHS = getSCEV(BO->LHS);
7941 RHS = getSCEV(BO->RHS);
7942 return getURemExpr(LHS, RHS);
7943 case Instruction::Sub: {
7945 if (BO->Op)
7946 Flags = getNoWrapFlagsFromUB(BO->Op);
7947
7948 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
7949 // operand. While we don't model ptrtoint directly in SCEV, the
7950 // difference between two pointer addresses is well-defined.
7951 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
7952 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
7953 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
7954 if (HasPtrLHS || HasPtrRHS) {
7955 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
7956 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
7957 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
7958 // useful structure.
7959 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
7960 bool BothPtr) -> const SCEV * {
7961 if (!HasPtr)
7962 return getSCEV(OrigOp);
7963 const SCEV *PtrSCEV = getSCEV(PtrOp);
7964 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
7965 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
7966 if (!isa<SCEVCouldNotCompute>(Addr) &&
7967 getTypeSizeInBits(OrigOp->getType()) <=
7968 getTypeSizeInBits(Addr->getType()))
7969 return getTruncateOrNoop(Addr, OrigOp->getType());
7970 }
7971 return getSCEV(OrigOp);
7972 };
7973 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
7974 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
7975 return getMinusSCEV(L, R, Flags);
7976 }
7977
7978 LHS = getSCEV(BO->LHS);
7979 RHS = getSCEV(BO->RHS);
7980 return getMinusSCEV(LHS, RHS, Flags);
7981 }
7982 case Instruction::And:
7983 // For an expression like x&255 that merely masks off the high bits,
7984 // use zext(trunc(x)) as the SCEV expression.
7985 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
7986 if (CI->isZero())
7987 return getSCEV(BO->RHS);
7988 if (CI->isMinusOne())
7989 return getSCEV(BO->LHS);
7990 const APInt &A = CI->getValue();
7991
7992 // Instcombine's ShrinkDemandedConstant may strip bits out of
7993 // constants, obscuring what would otherwise be a low-bits mask.
7994 // Use computeKnownBits to compute what ShrinkDemandedConstant
7995 // knew about to reconstruct a low-bits mask value.
7996 unsigned LZ = A.countl_zero();
7997 unsigned TZ = A.countr_zero();
7998 unsigned BitWidth = A.getBitWidth();
7999 KnownBits Known(BitWidth);
8000 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8001
8002 APInt EffectiveMask =
8003 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8004 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8005 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8006 const SCEV *LHS = getSCEV(BO->LHS);
8007 const SCEV *ShiftedLHS = nullptr;
8008 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8009 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8010 // For an expression like (x * 8) & 8, simplify the multiply.
8011 unsigned MulZeros = OpC->getAPInt().countr_zero();
8012 unsigned GCD = std::min(MulZeros, TZ);
8013 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8015 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8016 append_range(MulOps, LHSMul->operands().drop_front());
8017 const SCEV *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8018 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8019 }
8020 }
8021 if (!ShiftedLHS)
8022 ShiftedLHS = getUDivExpr(LHS, MulCount);
8023 return getMulExpr(
8025 getTruncateExpr(ShiftedLHS,
8026 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8027 BO->LHS->getType()),
8028 MulCount);
8029 }
8030 }
8031 // Binary `and` is a bit-wise `umin`.
8032 if (BO->LHS->getType()->isIntegerTy(1)) {
8033 LHS = getSCEV(BO->LHS);
8034 RHS = getSCEV(BO->RHS);
8035 return getUMinExpr(LHS, RHS);
8036 }
8037 break;
8038
8039 case Instruction::Or:
8040 // Binary `or` is a bit-wise `umax`.
8041 if (BO->LHS->getType()->isIntegerTy(1)) {
8042 LHS = getSCEV(BO->LHS);
8043 RHS = getSCEV(BO->RHS);
8044 return getUMaxExpr(LHS, RHS);
8045 }
8046 break;
8047
8048 case Instruction::Xor:
8049 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8050 // If the RHS of xor is -1, then this is a not operation.
8051 if (CI->isMinusOne())
8052 return getNotSCEV(getSCEV(BO->LHS));
8053
8054 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8055 // This is a variant of the check for xor with -1, and it handles
8056 // the case where instcombine has trimmed non-demanded bits out
8057 // of an xor with -1.
8058 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8059 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8060 if (LBO->getOpcode() == Instruction::And &&
8061 LCI->getValue() == CI->getValue())
8062 if (const SCEVZeroExtendExpr *Z =
8064 Type *UTy = BO->LHS->getType();
8065 const SCEV *Z0 = Z->getOperand();
8066 Type *Z0Ty = Z0->getType();
8067 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8068
8069 // If C is a low-bits mask, the zero extend is serving to
8070 // mask off the high bits. Complement the operand and
8071 // re-apply the zext.
8072 if (CI->getValue().isMask(Z0TySize))
8073 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8074
8075 // If C is a single bit, it may be in the sign-bit position
8076 // before the zero-extend. In this case, represent the xor
8077 // using an add, which is equivalent, and re-apply the zext.
8078 APInt Trunc = CI->getValue().trunc(Z0TySize);
8079 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8080 Trunc.isSignMask())
8081 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8082 UTy);
8083 }
8084 }
8085 break;
8086
8087 case Instruction::Shl:
8088 // Turn shift left of a constant amount into a multiply.
8089 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8090 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8091
8092 // If the shift count is not less than the bitwidth, the result of
8093 // the shift is undefined. Don't try to analyze it, because the
8094 // resolution chosen here may differ from the resolution chosen in
8095 // other parts of the compiler.
8096 if (SA->getValue().uge(BitWidth))
8097 break;
8098
8099 // We can safely preserve the nuw flag in all cases. It's also safe to
8100 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8101 // requires special handling. It can be preserved as long as we're not
8102 // left shifting by bitwidth - 1.
8103 auto Flags = SCEV::FlagNone;
8104 if (BO->Op) {
8105 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8106 if (any(MulFlags & SCEV::FlagNSW) &&
8107 (any(MulFlags & SCEV::FlagNUW) ||
8108 SA->getValue().ult(BitWidth - 1)))
8110 if (any(MulFlags & SCEV::FlagNUW))
8112 }
8113
8114 ConstantInt *X = ConstantInt::get(
8115 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8116 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8117 }
8118 break;
8119
8120 case Instruction::AShr:
8121 // AShr X, C, where C is a constant.
8122 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8123 if (!CI)
8124 break;
8125
8126 Type *OuterTy = BO->LHS->getType();
8128 // If the shift count is not less than the bitwidth, the result of
8129 // the shift is undefined. Don't try to analyze it, because the
8130 // resolution chosen here may differ from the resolution chosen in
8131 // other parts of the compiler.
8132 if (CI->getValue().uge(BitWidth))
8133 break;
8134
8135 if (CI->isZero())
8136 return getSCEV(BO->LHS); // shift by zero --> noop
8137
8138 uint64_t AShrAmt = CI->getZExtValue();
8139 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8140
8141 Operator *L = dyn_cast<Operator>(BO->LHS);
8142 const SCEV *AddTruncateExpr = nullptr;
8143 ConstantInt *ShlAmtCI = nullptr;
8144 const SCEV *AddConstant = nullptr;
8145
8146 if (L && L->getOpcode() == Instruction::Add) {
8147 // X = Shl A, n
8148 // Y = Add X, c
8149 // Z = AShr Y, m
8150 // n, c and m are constants.
8151
8152 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8153 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8154 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8155 if (AddOperandCI) {
8156 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8157 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8158 // since we truncate to TruncTy, the AddConstant should be of the
8159 // same type, so create a new Constant with type same as TruncTy.
8160 // Also, the Add constant should be shifted right by AShr amount.
8161 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8162 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8163 // we model the expression as sext(add(trunc(A), c << n)), since the
8164 // sext(trunc) part is already handled below, we create a
8165 // AddExpr(TruncExp) which will be used later.
8166 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8167 }
8168 }
8169 } else if (L && L->getOpcode() == Instruction::Shl) {
8170 // X = Shl A, n
8171 // Y = AShr X, m
8172 // Both n and m are constant.
8173
8174 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8175 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8176 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8177 }
8178
8179 if (AddTruncateExpr && ShlAmtCI) {
8180 // We can merge the two given cases into a single SCEV statement,
8181 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8182 // a simpler case. The following code handles the two cases:
8183 //
8184 // 1) For a two-shift sext-inreg, i.e. n = m,
8185 // use sext(trunc(x)) as the SCEV expression.
8186 //
8187 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8188 // expression. We already checked that ShlAmt < BitWidth, so
8189 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8190 // ShlAmt - AShrAmt < Amt.
8191 const APInt &ShlAmt = ShlAmtCI->getValue();
8192 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8193 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8194 ShlAmtCI->getZExtValue() - AShrAmt);
8195 const SCEV *CompositeExpr =
8196 getMulExpr(AddTruncateExpr, getConstant(Mul));
8197 if (L->getOpcode() != Instruction::Shl)
8198 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8199
8200 return getSignExtendExpr(CompositeExpr, OuterTy);
8201 }
8202 }
8203 break;
8204 }
8205 }
8206
8207 switch (U->getOpcode()) {
8208 case Instruction::Trunc:
8209 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8210
8211 case Instruction::ZExt:
8212 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8213
8214 case Instruction::SExt:
8215 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
8216 // The NSW flag of a subtract does not always survive the conversion to
8217 // A + (-1)*B. By pushing sign extension onto its operands we are much
8218 // more likely to preserve NSW and allow later AddRec optimisations.
8219 //
8220 // NOTE: This is effectively duplicating this logic from getSignExtend:
8221 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8222 // but by that point the NSW information has potentially been lost.
8223 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8224 Type *Ty = U->getType();
8225 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8226 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8227 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8228 }
8229 }
8230 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8231
8232 case Instruction::BitCast:
8233 // BitCasts are no-op casts so we just eliminate the cast.
8234 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8235 return getSCEV(U->getOperand(0));
8236 break;
8237
8238 case Instruction::PtrToAddr: {
8239 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8240 if (isa<SCEVCouldNotCompute>(IntOp))
8241 return getUnknown(V);
8242 return IntOp;
8243 }
8244
8245 case Instruction::PtrToInt:
8246 // SCEV only models ptrtoaddr.
8247 return getUnknown(V);
8248
8249 case Instruction::IntToPtr:
8250 // Just don't deal with inttoptr casts.
8251 return getUnknown(V);
8252
8253 case Instruction::SDiv:
8254 // If both operands are non-negative, this is just an udiv.
8255 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8256 isKnownNonNegative(getSCEV(U->getOperand(1))))
8257 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8258 break;
8259
8260 case Instruction::SRem:
8261 // If both operands are non-negative, this is just an urem.
8262 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8263 isKnownNonNegative(getSCEV(U->getOperand(1))))
8264 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8265 break;
8266
8267 case Instruction::GetElementPtr:
8268 return createNodeForGEP(cast<GEPOperator>(U));
8269
8270 case Instruction::PHI:
8271 return createNodeForPHI(cast<PHINode>(U));
8272
8273 case Instruction::Select:
8274 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8275 U->getOperand(2));
8276
8277 case Instruction::Call:
8278 case Instruction::Invoke:
8279 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8280 return getSCEV(RV);
8281
8282 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8283 switch (II->getIntrinsicID()) {
8284 case Intrinsic::abs:
8285 return getAbsExpr(
8286 getSCEV(II->getArgOperand(0)),
8287 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8288 case Intrinsic::umax:
8289 LHS = getSCEV(II->getArgOperand(0));
8290 RHS = getSCEV(II->getArgOperand(1));
8291 return getUMaxExpr(LHS, RHS);
8292 case Intrinsic::umin:
8293 LHS = getSCEV(II->getArgOperand(0));
8294 RHS = getSCEV(II->getArgOperand(1));
8295 return getUMinExpr(LHS, RHS);
8296 case Intrinsic::smax:
8297 LHS = getSCEV(II->getArgOperand(0));
8298 RHS = getSCEV(II->getArgOperand(1));
8299 return getSMaxExpr(LHS, RHS);
8300 case Intrinsic::smin:
8301 LHS = getSCEV(II->getArgOperand(0));
8302 RHS = getSCEV(II->getArgOperand(1));
8303 return getSMinExpr(LHS, RHS);
8304 case Intrinsic::usub_sat: {
8305 const SCEV *X = getSCEV(II->getArgOperand(0));
8306 const SCEV *Y = getSCEV(II->getArgOperand(1));
8307 const SCEV *ClampedY = getUMinExpr(X, Y);
8308 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8309 }
8310 case Intrinsic::uadd_sat: {
8311 const SCEV *X = getSCEV(II->getArgOperand(0));
8312 const SCEV *Y = getSCEV(II->getArgOperand(1));
8313 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8314 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8315 }
8316 case Intrinsic::start_loop_iterations:
8317 case Intrinsic::annotation:
8318 case Intrinsic::ptr_annotation:
8319 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8320 // just eqivalent to the first operand for SCEV purposes.
8321 return getSCEV(II->getArgOperand(0));
8322 case Intrinsic::vscale:
8323 return getVScale(II->getType());
8324 default:
8325 break;
8326 }
8327 }
8328 break;
8329 }
8330
8331 return getUnknown(V);
8332}
8333
8334//===----------------------------------------------------------------------===//
8335// Iteration Count Computation Code
8336//
8337
8339 if (isa<SCEVCouldNotCompute>(ExitCount))
8340 return getCouldNotCompute();
8341
8342 auto *ExitCountType = ExitCount->getType();
8343 assert(ExitCountType->isIntegerTy());
8344 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8345 1 + ExitCountType->getScalarSizeInBits());
8346 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8347}
8348
8350 Type *EvalTy,
8351 const Loop *L) {
8352 if (isa<SCEVCouldNotCompute>(ExitCount))
8353 return getCouldNotCompute();
8354
8355 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8356 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8357
8358 auto CanAddOneWithoutOverflow = [&]() {
8359 ConstantRange ExitCountRange =
8360 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8361 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8362 return true;
8363
8364 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8365 getMinusOne(ExitCount->getType()));
8366 };
8367
8368 // If we need to zero extend the backedge count, check if we can add one to
8369 // it prior to zero extending without overflow. Provided this is safe, it
8370 // allows better simplification of the +1.
8371 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8372 return getZeroExtendExpr(
8373 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8374
8375 // Get the total trip count from the count by adding 1. This may wrap.
8376 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8377}
8378
8379static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8380 if (!ExitCount)
8381 return 0;
8382
8383 ConstantInt *ExitConst = ExitCount->getValue();
8384
8385 // Guard against huge trip counts.
8386 if (ExitConst->getValue().getActiveBits() > 32)
8387 return 0;
8388
8389 // In case of integer overflow, this returns 0, which is correct.
8390 return ((unsigned)ExitConst->getZExtValue()) + 1;
8391}
8392
8394 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8395 return getConstantTripCount(ExitCount);
8396}
8397
8398unsigned
8400 const BasicBlock *ExitingBlock) {
8401 assert(ExitingBlock && "Must pass a non-null exiting block!");
8402 assert(L->isLoopExiting(ExitingBlock) &&
8403 "Exiting block must actually branch out of the loop!");
8404 const SCEVConstant *ExitCount =
8405 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8406 return getConstantTripCount(ExitCount);
8407}
8408
8410 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8411
8412 const auto *MaxExitCount =
8413 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8415 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8416}
8417
8419 SmallVector<BasicBlock *, 8> ExitingBlocks;
8420 L->getExitingBlocks(ExitingBlocks);
8421
8422 // An exit with an uncomputable exit count makes the result 1.
8423 if (ExitingBlocks.empty() ||
8424 any_of(ExitingBlocks, [this, L](BasicBlock *ExitingBB) {
8425 return isa<SCEVCouldNotCompute>(getExitCount(L, ExitingBB));
8426 }))
8427 return 1;
8428
8429 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8430 unsigned Res = 0;
8431 for (BasicBlock *ExitingBB : ExitingBlocks)
8432 Res = std::gcd(
8433 Res, getSmallConstantTripMultiple(getExitCount(L, ExitingBB), Guards));
8434 return Res;
8435}
8436
8437unsigned ScalarEvolution::getSmallConstantTripMultiple(const SCEV *ExitCount,
8438 LoopGuards &Guards) {
8439 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Must be computable!");
8440
8441 // Get the trip count
8442 const SCEV *TCExpr =
8443 getTripCountFromExitCount(applyLoopGuards(ExitCount, Guards));
8444
8445 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8446 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8447 // the greatest power of 2 divisor less than 2^32.
8448 return Multiple.getActiveBits() > 32
8449 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8450 : (unsigned)Multiple.getZExtValue();
8451}
8452
8454 const SCEV *ExitCount) {
8455 if (isa<SCEVCouldNotCompute>(ExitCount))
8456 return 1;
8457
8458 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
8459 return getSmallConstantTripMultiple(ExitCount, Guards);
8460}
8461
8462/// Returns the largest constant divisor of the trip count of this loop as a
8463/// normal unsigned value, if possible. This means that the actual trip count is
8464/// always a multiple of the returned value (don't forget the trip count could
8465/// very well be zero as well!).
8466///
8467/// Returns 1 if the trip count is unknown or not guaranteed to be the
8468/// multiple of a constant (which is also the case if the trip count is simply
8469/// constant, use getSmallConstantTripCount for that case), Will also return 1
8470/// if the trip count is very large (>= 2^32).
8471///
8472/// As explained in the comments for getSmallConstantTripCount, this assumes
8473/// that control exits the loop via ExitingBlock.
8474unsigned
8476 const BasicBlock *ExitingBlock) {
8477 assert(ExitingBlock && "Must pass a non-null exiting block!");
8478 assert(L->isLoopExiting(ExitingBlock) &&
8479 "Exiting block must actually branch out of the loop!");
8480 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8481 return getSmallConstantTripMultiple(L, ExitCount);
8482}
8483
8485 const BasicBlock *ExitingBlock,
8486 ExitCountKind Kind) {
8487 switch (Kind) {
8488 case Exact:
8489 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8490 case SymbolicMaximum:
8491 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8492 case ConstantMaximum:
8493 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8494 };
8495 llvm_unreachable("Invalid ExitCountKind!");
8496}
8497
8499 const Loop *L, const BasicBlock *ExitingBlock,
8501 switch (Kind) {
8502 case Exact:
8503 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8504 Predicates);
8505 case SymbolicMaximum:
8506 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8507 Predicates);
8508 case ConstantMaximum:
8509 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8510 Predicates);
8511 };
8512 llvm_unreachable("Invalid ExitCountKind!");
8513}
8514
8517 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8518}
8519
8521 ExitCountKind Kind) {
8522 switch (Kind) {
8523 case Exact:
8524 return getBackedgeTakenInfo(L).getExact(L, this);
8525 case ConstantMaximum:
8526 return getBackedgeTakenInfo(L).getConstantMax(this);
8527 case SymbolicMaximum:
8528 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8529 };
8530 llvm_unreachable("Invalid ExitCountKind!");
8531}
8532
8535 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8536}
8537
8540 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8541}
8542
8544 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8545}
8546
8547/// Push PHI nodes in the header of the given loop onto the given Worklist.
8548static void PushLoopPHIs(const Loop *L,
8551 BasicBlock *Header = L->getHeader();
8552
8553 // Push all Loop-header PHIs onto the Worklist stack.
8554 for (PHINode &PN : Header->phis())
8555 if (Visited.insert(&PN).second)
8556 Worklist.push_back(&PN);
8557}
8558
8559ScalarEvolution::BackedgeTakenInfo &
8560ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8561 auto &BTI = getBackedgeTakenInfo(L);
8562 if (BTI.hasFullInfo())
8563 return BTI;
8564
8565 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8566
8567 if (!Pair.second)
8568 return Pair.first->second;
8569
8570 BackedgeTakenInfo Result =
8571 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8572
8573 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8574}
8575
8576ScalarEvolution::BackedgeTakenInfo &
8577ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8578 // Initially insert an invalid entry for this loop. If the insertion
8579 // succeeds, proceed to actually compute a backedge-taken count and
8580 // update the value. The temporary CouldNotCompute value tells SCEV
8581 // code elsewhere that it shouldn't attempt to request a new
8582 // backedge-taken count, which could result in infinite recursion.
8583 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8584 BackedgeTakenCounts.try_emplace(L);
8585 if (!Pair.second)
8586 return Pair.first->second;
8587
8588 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8589 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8590 // must be cleared in this scope.
8591 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8592
8593 // Now that we know more about the trip count for this loop, forget any
8594 // existing SCEV values for PHI nodes in this loop since they are only
8595 // conservative estimates made without the benefit of trip count
8596 // information. This invalidation is not necessary for correctness, and is
8597 // only done to produce more precise results.
8598 if (Result.hasAnyInfo()) {
8599 // Invalidate any expression using an addrec in this loop.
8600 SmallVector<SCEVUse, 8> ToForget;
8601 auto LoopUsersIt = LoopUsers.find(L);
8602 if (LoopUsersIt != LoopUsers.end())
8603 append_range(ToForget, LoopUsersIt->second);
8604 forgetMemoizedResults(ToForget);
8605
8606 // Invalidate constant-evolved loop header phis.
8607 for (PHINode &PN : L->getHeader()->phis())
8608 ConstantEvolutionLoopExitValue.erase(&PN);
8609 }
8610
8611 // Re-lookup the insert position, since the call to
8612 // computeBackedgeTakenCount above could result in a
8613 // recusive call to getBackedgeTakenInfo (on a different
8614 // loop), which would invalidate the iterator computed
8615 // earlier.
8616 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8617}
8618
8620 // This method is intended to forget all info about loops. It should
8621 // invalidate caches as if the following happened:
8622 // - The trip counts of all loops have changed arbitrarily
8623 // - Every llvm::Value has been updated in place to produce a different
8624 // result.
8625 BackedgeTakenCounts.clear();
8626 PredicatedBackedgeTakenCounts.clear();
8627 BECountUsers.clear();
8628 LoopPropertiesCache.clear();
8629 ConstantEvolutionLoopExitValue.clear();
8630 ValueExprMap.clear();
8631 ValuesAtScopes.clear();
8632 ValuesAtScopesUsers.clear();
8633 LoopDispositions.clear();
8634 BlockDispositions.clear();
8635 UnsignedRanges.clear();
8636 SignedRanges.clear();
8637 ExprValueMap.clear();
8638 HasRecMap.clear();
8639 ConstantMultipleCache.clear();
8640 PredicatedSCEVRewrites.clear();
8641 FoldCache.clear();
8642 FoldCacheUser.clear();
8643}
8644void ScalarEvolution::visitAndClearUsers(
8647 SmallVectorImpl<SCEVUse> &ToForget) {
8648 // Nothing can be invalidated if no value has a SCEV yet.
8649 if (ValueExprMap.empty()) {
8650 Worklist.clear();
8651 return;
8652 }
8653 while (!Worklist.empty()) {
8654 Instruction *I = Worklist.pop_back_val();
8655 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8656 continue;
8657
8659 ValueExprMap.find_as(static_cast<Value *>(I));
8660 if (It != ValueExprMap.end()) {
8661 ToForget.push_back(It->second);
8662 eraseValueFromMap(It->first);
8663 if (PHINode *PN = dyn_cast<PHINode>(I))
8664 ConstantEvolutionLoopExitValue.erase(PN);
8665 }
8666
8667 PushDefUseChildren(I, Worklist, Visited);
8668 }
8669}
8670
8672 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8675 SmallVector<SCEVUse, 16> ToForget;
8676
8677 // Iterate over all the loops and sub-loops to drop SCEV information.
8678 while (!LoopWorklist.empty()) {
8679 auto *CurrL = LoopWorklist.pop_back_val();
8680
8681 // Drop any stored trip count value.
8682 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8683 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8684
8685 // Drop information about predicated SCEV rewrites for this loop.
8686 PredicatedSCEVRewrites.remove_if(
8687 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8688
8689 auto LoopUsersItr = LoopUsers.find(CurrL);
8690 if (LoopUsersItr != LoopUsers.end())
8691 llvm::append_range(ToForget, LoopUsersItr->second);
8692
8693 // Drop information about expressions based on loop-header PHIs.
8694 PushLoopPHIs(CurrL, Worklist, Visited);
8695 visitAndClearUsers(Worklist, Visited, ToForget);
8696
8697 LoopPropertiesCache.erase(CurrL);
8698 // Forget all contained loops too, to avoid dangling entries in the
8699 // ValuesAtScopes map.
8700 LoopWorklist.append(CurrL->begin(), CurrL->end());
8701 }
8702 forgetMemoizedResults(ToForget);
8703}
8704
8706 forgetLoop(L->getOutermostLoop());
8707}
8708
8711 if (!I) return;
8712
8713 // Drop information about expressions based on loop-header PHIs.
8716 SmallVector<SCEVUse, 8> ToForget;
8717 Worklist.push_back(I);
8718 Visited.insert(I);
8719 visitAndClearUsers(Worklist, Visited, ToForget);
8720
8721 forgetMemoizedResults(ToForget);
8722}
8723
8727 SmallVector<SCEVUse, 8> ToForget;
8728 for (Value *V : Values)
8729 if (auto *I = dyn_cast<Instruction>(V))
8730 if (Visited.insert(I).second)
8731 Worklist.push_back(I);
8732 visitAndClearUsers(Worklist, Visited, ToForget);
8733
8734 forgetMemoizedResults(ToForget);
8735}
8736
8738 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8739 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8740 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8741 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8742 auto InvalidateValue = [&](Value *Val) {
8743 if (!isSCEVable(Val->getType()))
8744 return;
8745 if (const SCEV *S = getExistingSCEV(Val)) {
8746 struct InvalidationRootCollector {
8747 Loop *L;
8749
8750 InvalidationRootCollector(Loop *L) : L(L) {}
8751
8752 bool follow(const SCEV *S) {
8753 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8754 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8755 if (L->contains(I))
8756 Roots.push_back(S);
8757 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8758 if (L->contains(AddRec->getLoop()))
8759 Roots.push_back(S);
8760 }
8761 return true;
8762 }
8763 bool isDone() const { return false; }
8764 };
8765
8766 InvalidationRootCollector C(L);
8767 visitAll(S, C);
8768 forgetMemoizedResults(C.Roots);
8769 }
8770 };
8771
8772 InvalidateValue(V);
8773
8774 // If V has a non-SCEV-able type (e.g. {i64, i1} from a with.overflow
8775 // intrinsic), its users (e.g. extractvalue) may have stale SCEV
8776 // expressions referencing loop-internal values.
8777 if (!isSCEVable(V->getType()) &&
8778 any_of(V->incoming_values(), IsaPred<WithOverflowInst>))
8779 for (User *U : V->users())
8780 InvalidateValue(U);
8781 // Also perform the normal invalidation.
8782 forgetValue(V);
8783}
8784
8785void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8786
8788 // Unless a specific value is passed to invalidation, completely clear both
8789 // caches.
8790 if (!V) {
8791 BlockDispositions.clear();
8792 LoopDispositions.clear();
8793 return;
8794 }
8795
8796 if (!isSCEVable(V->getType()))
8797 return;
8798
8799 const SCEV *S = getExistingSCEV(V);
8800 if (!S)
8801 return;
8802
8803 // Invalidate the block and loop dispositions cached for S. Dispositions of
8804 // S's users may change if S's disposition changes (i.e. a user may change to
8805 // loop-invariant, if S changes to loop invariant), so also invalidate
8806 // dispositions of S's users recursively.
8807 SmallVector<SCEVUse, 8> Worklist = {S};
8809 while (!Worklist.empty()) {
8810 const SCEV *Curr = Worklist.pop_back_val();
8811 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8812 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8813 if (!LoopDispoRemoved && !BlockDispoRemoved)
8814 continue;
8815 auto Users = SCEVUsers.find(Curr);
8816 if (Users != SCEVUsers.end())
8817 for (const auto *User : Users->second)
8818 if (Seen.insert(User).second)
8819 Worklist.push_back(User);
8820 }
8821}
8822
8823/// Get the exact loop backedge taken count considering all loop exits. A
8824/// computable result can only be returned for loops with all exiting blocks
8825/// dominating the latch. howFarToZero assumes that the limit of each loop test
8826/// is never skipped. This is a valid assumption as long as the loop exits via
8827/// that test. For precise results, it is the caller's responsibility to specify
8828/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8829const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8830 const Loop *L, ScalarEvolution *SE,
8832 // If any exits were not computable, the loop is not computable.
8833 if (!isComplete() || ExitNotTaken.empty())
8834 return SE->getCouldNotCompute();
8835
8836 const BasicBlock *Latch = L->getLoopLatch();
8837 // All exiting blocks we have collected must dominate the only backedge.
8838 if (!Latch)
8839 return SE->getCouldNotCompute();
8840
8841 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8842 // count is simply a minimum out of all these calculated exit counts.
8844 for (const auto &ENT : ExitNotTaken) {
8845 const SCEV *BECount = ENT.ExactNotTaken;
8846 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8847 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8848 "We should only have known counts for exiting blocks that dominate "
8849 "latch!");
8850
8851 Ops.push_back(BECount);
8852
8853 if (Preds)
8854 append_range(*Preds, ENT.Predicates);
8855
8856 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8857 "Predicate should be always true!");
8858 }
8859
8860 // If an earlier exit exits on the first iteration (exit count zero), then
8861 // a later poison exit count should not propagate into the result. This are
8862 // exactly the semantics provided by umin_seq.
8863 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8864}
8865
8866const ScalarEvolution::ExitNotTakenInfo *
8867ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8868 const BasicBlock *ExitingBlock,
8869 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8870 for (const auto &ENT : ExitNotTaken)
8871 if (ENT.ExitingBlock == ExitingBlock) {
8872 if (ENT.hasAlwaysTruePredicate())
8873 return &ENT;
8874 else if (Predicates) {
8875 append_range(*Predicates, ENT.Predicates);
8876 return &ENT;
8877 }
8878 }
8879
8880 return nullptr;
8881}
8882
8883/// getConstantMax - Get the constant max backedge taken count for the loop.
8884const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
8885 ScalarEvolution *SE,
8886 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8887 if (!getConstantMax())
8888 return SE->getCouldNotCompute();
8889
8890 for (const auto &ENT : ExitNotTaken)
8891 if (!ENT.hasAlwaysTruePredicate()) {
8892 if (!Predicates)
8893 return SE->getCouldNotCompute();
8894 append_range(*Predicates, ENT.Predicates);
8895 }
8896
8897 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
8898 isa<SCEVConstant>(getConstantMax())) &&
8899 "No point in having a non-constant max backedge taken count!");
8900 return getConstantMax();
8901}
8902
8903const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
8904 const Loop *L, ScalarEvolution *SE,
8905 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8906 if (!SymbolicMax) {
8907 // Form an expression for the maximum exit count possible for this loop. We
8908 // merge the max and exact information to approximate a version of
8909 // getConstantMaxBackedgeTakenCount which isn't restricted to just
8910 // constants.
8911 SmallVector<SCEVUse, 4> ExitCounts;
8912
8913 for (const auto &ENT : ExitNotTaken) {
8914 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
8915 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
8916 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
8917 "We should only have known counts for exiting blocks that "
8918 "dominate latch!");
8919 ExitCounts.push_back(ExitCount);
8920 if (Predicates)
8921 append_range(*Predicates, ENT.Predicates);
8922
8923 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
8924 "Predicate should be always true!");
8925 }
8926 }
8927 if (ExitCounts.empty())
8928 SymbolicMax = SE->getCouldNotCompute();
8929 else
8930 SymbolicMax =
8931 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
8932 }
8933 return SymbolicMax;
8934}
8935
8936bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
8937 ScalarEvolution *SE) const {
8938 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
8939 return !ENT.hasAlwaysTruePredicate();
8940 };
8941 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
8942}
8943
8946
8948 const SCEV *E, const SCEV *ConstantMaxNotTaken,
8949 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
8953 // If we prove the max count is zero, so is the symbolic bound. This happens
8954 // in practice due to differences in a) how context sensitive we've chosen
8955 // to be and b) how we reason about bounds implied by UB.
8956 if (ConstantMaxNotTaken->isZero()) {
8957 this->ExactNotTaken = E = ConstantMaxNotTaken;
8958 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
8959 }
8960
8963 "Exact is not allowed to be less precise than Constant Max");
8966 "Exact is not allowed to be less precise than Symbolic Max");
8969 "Symbolic Max is not allowed to be less precise than Constant Max");
8972 "No point in having a non-constant max backedge taken count!");
8974 for (const auto PredList : PredLists)
8975 for (const auto *P : PredList) {
8976 if (SeenPreds.contains(P))
8977 continue;
8978 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
8979 SeenPreds.insert(P);
8980 Predicates.push_back(P);
8981 }
8982 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
8983 "Backedge count should be int");
8985 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
8986 "Max backedge count should be int");
8987}
8988
8996
8997/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
8998/// computable exit into a persistent ExitNotTakenInfo array.
8999ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9001 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9002 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9003 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9004
9005 ExitNotTaken.reserve(ExitCounts.size());
9006 std::transform(ExitCounts.begin(), ExitCounts.end(),
9007 std::back_inserter(ExitNotTaken),
9008 [&](const EdgeExitInfo &EEI) {
9009 BasicBlock *ExitBB = EEI.first;
9010 const ExitLimit &EL = EEI.second;
9011 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9012 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9013 EL.Predicates);
9014 });
9015 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9016 isa<SCEVConstant>(ConstantMax)) &&
9017 "No point in having a non-constant max backedge taken count!");
9018}
9019
9020/// Compute the number of times the backedge of the specified loop will execute.
9021ScalarEvolution::BackedgeTakenInfo
9022ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9023 bool AllowPredicates) {
9024 SmallVector<BasicBlock *, 8> ExitingBlocks;
9025 L->getExitingBlocks(ExitingBlocks);
9026
9027 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9028
9030 bool CouldComputeBECount = true;
9031 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9032 const SCEV *MustExitMaxBECount = nullptr;
9033 const SCEV *MayExitMaxBECount = nullptr;
9034 bool MustExitMaxOrZero = false;
9035 bool IsOnlyExit = ExitingBlocks.size() == 1;
9036
9037 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9038 // and compute maxBECount.
9039 // Do a union of all the predicates here.
9040 for (BasicBlock *ExitBB : ExitingBlocks) {
9041 // We canonicalize untaken exits to br (constant), ignore them so that
9042 // proving an exit untaken doesn't negatively impact our ability to reason
9043 // about the loop as whole.
9044 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9045 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9046 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9047 if (ExitIfTrue == CI->isZero())
9048 continue;
9049 }
9050
9051 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9052
9053 assert((AllowPredicates || EL.Predicates.empty()) &&
9054 "Predicated exit limit when predicates are not allowed!");
9055
9056 // 1. For each exit that can be computed, add an entry to ExitCounts.
9057 // CouldComputeBECount is true only if all exits can be computed.
9058 if (EL.ExactNotTaken != getCouldNotCompute())
9059 ++NumExitCountsComputed;
9060 else
9061 // We couldn't compute an exact value for this exit, so
9062 // we won't be able to compute an exact value for the loop.
9063 CouldComputeBECount = false;
9064 // Remember exit count if either exact or symbolic is known. Because
9065 // Exact always implies symbolic, only check symbolic.
9066 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9067 ExitCounts.emplace_back(ExitBB, EL);
9068 else {
9069 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9070 "Exact is known but symbolic isn't?");
9071 ++NumExitCountsNotComputed;
9072 }
9073
9074 // 2. Derive the loop's MaxBECount from each exit's max number of
9075 // non-exiting iterations. Partition the loop exits into two kinds:
9076 // LoopMustExits and LoopMayExits.
9077 //
9078 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9079 // is a LoopMayExit. If any computable LoopMustExit is found, then
9080 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9081 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9082 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9083 // any
9084 // computable EL.ConstantMaxNotTaken.
9085 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9086 DT.dominates(ExitBB, Latch)) {
9087 if (!MustExitMaxBECount) {
9088 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9089 MustExitMaxOrZero = EL.MaxOrZero;
9090 } else {
9091 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9092 EL.ConstantMaxNotTaken);
9093 }
9094 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9095 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9096 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9097 else {
9098 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9099 EL.ConstantMaxNotTaken);
9100 }
9101 }
9102 }
9103 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9104 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9105 // The loop backedge will be taken the maximum or zero times if there's
9106 // a single exit that must be taken the maximum or zero times.
9107 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9108
9109 // Remember which SCEVs are used in exit limits for invalidation purposes.
9110 // We only care about non-constant SCEVs here, so we can ignore
9111 // EL.ConstantMaxNotTaken
9112 // and MaxBECount, which must be SCEVConstant.
9113 for (const auto &Pair : ExitCounts) {
9114 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9115 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9116 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9117 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9118 {L, AllowPredicates});
9119 }
9120 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9121 MaxBECount, MaxOrZero);
9122}
9123
9124ScalarEvolution::ExitLimit
9125ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9126 bool IsOnlyExit, bool AllowPredicates) {
9127 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9128 // If our exiting block does not dominate the latch, then its connection with
9129 // loop's exit limit may be far from trivial.
9130 const BasicBlock *Latch = L->getLoopLatch();
9131 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9132 return getCouldNotCompute();
9133
9134 Instruction *Term = ExitingBlock->getTerminator();
9135 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9136 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9137 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9138 "It should have one successor in loop and one exit block!");
9139 // Proceed to the next level to examine the exit condition expression.
9140 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9141 /*ControlsOnlyExit=*/IsOnlyExit,
9142 AllowPredicates);
9143 }
9144
9145 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9146 // For switch, make sure that there is a single exit from the loop.
9147 BasicBlock *Exit = nullptr;
9148 for (auto *SBB : successors(ExitingBlock))
9149 if (!L->contains(SBB)) {
9150 if (Exit) // Multiple exit successors.
9151 return getCouldNotCompute();
9152 Exit = SBB;
9153 }
9154 assert(Exit && "Exiting block must have at least one exit");
9155 return computeExitLimitFromSingleExitSwitch(
9156 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9157 }
9158
9159 return getCouldNotCompute();
9160}
9161
9163 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9164 bool AllowPredicates) {
9165 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9166 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9167 ControlsOnlyExit, AllowPredicates);
9168}
9169
9170std::optional<ScalarEvolution::ExitLimit>
9171ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9172 bool ExitIfTrue, bool ControlsOnlyExit,
9173 bool AllowPredicates) {
9174 (void)this->L;
9175 (void)this->ExitIfTrue;
9176 (void)this->AllowPredicates;
9177
9178 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9179 this->AllowPredicates == AllowPredicates &&
9180 "Variance in assumed invariant key components!");
9181 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9182 if (Itr == TripCountMap.end())
9183 return std::nullopt;
9184 return Itr->second;
9185}
9186
9187void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9188 bool ExitIfTrue,
9189 bool ControlsOnlyExit,
9190 bool AllowPredicates,
9191 const ExitLimit &EL) {
9192 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9193 this->AllowPredicates == AllowPredicates &&
9194 "Variance in assumed invariant key components!");
9195
9196 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9197 assert(InsertResult.second && "Expected successful insertion!");
9198 (void)InsertResult;
9199 (void)ExitIfTrue;
9200}
9201
9202ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9203 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9204 bool ControlsOnlyExit, bool AllowPredicates) {
9205
9206 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9207 AllowPredicates))
9208 return *MaybeEL;
9209
9210 ExitLimit EL = computeExitLimitFromCondImpl(
9211 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9212 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9213 return EL;
9214}
9215
9216ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9217 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9218 bool ControlsOnlyExit, bool AllowPredicates) {
9219 // Handle BinOp conditions (And, Or).
9220 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9221 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9222 return *LimitFromBinOp;
9223
9224 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9225 // Proceed to the next level to examine the icmp.
9226 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9227 ExitLimit EL =
9228 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9229 if (EL.hasFullInfo() || !AllowPredicates)
9230 return EL;
9231
9232 // Try again, but use SCEV predicates this time.
9233 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9234 ControlsOnlyExit,
9235 /*AllowPredicates=*/true);
9236 }
9237
9238 // Check for a constant condition. These are normally stripped out by
9239 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9240 // preserve the CFG and is temporarily leaving constant conditions
9241 // in place.
9242 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9243 if (ExitIfTrue == !CI->getZExtValue())
9244 // The backedge is always taken.
9245 return getCouldNotCompute();
9246 // The backedge is never taken.
9247 return getZero(CI->getType());
9248 }
9249
9250 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9251 // with a constant step, we can form an equivalent icmp predicate and figure
9252 // out how many iterations will be taken before we exit.
9253 const WithOverflowInst *WO;
9254 const APInt *C;
9255 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9256 match(WO->getRHS(), m_APInt(C))) {
9257 ConstantRange NWR =
9259 WO->getNoWrapKind());
9260 CmpInst::Predicate Pred;
9261 APInt NewRHSC, Offset;
9262 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9263 if (!ExitIfTrue)
9264 Pred = ICmpInst::getInversePredicate(Pred);
9265 auto *LHS = getSCEV(WO->getLHS());
9266 if (Offset != 0)
9268 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9269 ControlsOnlyExit, AllowPredicates);
9270 if (EL.hasAnyInfo())
9271 return EL;
9272 }
9273
9274 // If it's not an integer or pointer comparison then compute it the hard way.
9275 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9276}
9277
9278std::optional<ScalarEvolution::ExitLimit>
9279ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9280 const Loop *L,
9281 Value *ExitCond,
9282 bool ExitIfTrue,
9283 bool AllowPredicates) {
9284 // Check if the controlling expression for this loop is an And or Or.
9285 Value *Op0, *Op1;
9286 bool IsAnd;
9287 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9288 IsAnd = true;
9289 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9290 IsAnd = false;
9291 else
9292 return std::nullopt;
9293
9294 // A sub-condition of a non-trivial binop never solely controls the exit,
9295 // whether we exit always depends on both conditions.
9296 ExitLimit EL0 = computeExitLimitFromCondCached(
9297 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9298 ExitLimit EL1 = computeExitLimitFromCondCached(
9299 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9300
9301 // EitherMayExit is true in these two cases:
9302 // br (and Op0 Op1), loop, exit
9303 // br (or Op0 Op1), exit, loop
9304 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9305
9306 const SCEV *BECount = getCouldNotCompute();
9307 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9308 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9309 if (EitherMayExit) {
9310 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9311 // Both conditions must be same for the loop to continue executing.
9312 // Choose the less conservative count.
9313 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9314 EL1.ExactNotTaken != getCouldNotCompute()) {
9315 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9316 UseSequentialUMin);
9317 }
9318 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9319 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9320 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9321 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9322 else
9323 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9324 EL1.ConstantMaxNotTaken);
9325 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9326 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9327 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9328 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9329 else
9330 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9331 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9332 } else {
9333 // Both conditions must be same at the same time for the loop to exit.
9334 // For now, be conservative.
9335 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9336 BECount = EL0.ExactNotTaken;
9337 }
9338
9339 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9340 // to be more aggressive when computing BECount than when computing
9341 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9342 // and
9343 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9344 // EL1.ConstantMaxNotTaken to not.
9345 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9346 !isa<SCEVCouldNotCompute>(BECount))
9347 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9348 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9349 SymbolicMaxBECount =
9350 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9351 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9352 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9353}
9354
9355ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9356 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9357 bool AllowPredicates) {
9358 // If the condition was exit on true, convert the condition to exit on false
9359 CmpPredicate Pred;
9360 if (!ExitIfTrue)
9361 Pred = ExitCond->getCmpPredicate();
9362 else
9363 Pred = ExitCond->getInverseCmpPredicate();
9364 const ICmpInst::Predicate OriginalPred = Pred;
9365
9366 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9367 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9368
9369 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9370 AllowPredicates);
9371 if (EL.hasAnyInfo())
9372 return EL;
9373
9374 auto *ExhaustiveCount =
9375 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9376
9377 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9378 return ExhaustiveCount;
9379
9380 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9381 ExitCond->getOperand(1), L, OriginalPred);
9382}
9383ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9384 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9385 bool ControlsOnlyExit, bool AllowPredicates) {
9386
9387 // Try to evaluate any dependencies out of the loop.
9388 LHS = getSCEVAtScope(LHS, L);
9389 RHS = getSCEVAtScope(RHS, L);
9390
9391 // At this point, we would like to compute how many iterations of the
9392 // loop the predicate will return true for these inputs.
9393 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9394 // If there is a loop-invariant, force it into the RHS.
9395 std::swap(LHS, RHS);
9397 }
9398
9399 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9401 // Simplify the operands before analyzing them.
9402 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9403
9404 // If we have a comparison of a chrec against a constant, try to use value
9405 // ranges to answer this query.
9406 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9407 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9408 if (AddRec->getLoop() == L) {
9409 // Form the constant range.
9410 ConstantRange CompRange =
9411 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9412
9413 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9414 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9415 }
9416
9417 // If this loop must exit based on this condition (or execute undefined
9418 // behaviour), see if we can improve wrap flags. This is essentially
9419 // a must execute style proof.
9420 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9421 // If we can prove the test sequence produced must repeat the same values
9422 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9423 // because if it did, we'd have an infinite (undefined) loop.
9424 // TODO: We can peel off any functions which are invertible *in L*. Loop
9425 // invariant terms are effectively constants for our purposes here.
9426 SCEVUse InnerLHS = LHS;
9427 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9428 InnerLHS = ZExt->getOperand();
9429 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9430 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9431 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9432 /*OrNegative=*/true)) {
9433 auto Flags = AR->getNoWrapFlags();
9434 Flags = setFlags(Flags, SCEV::FlagNW);
9437 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9438 }
9439
9440 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9441 // From no-self-wrap, this follows trivially from the fact that every
9442 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9443 // last value before (un)signed wrap. Since we know that last value
9444 // didn't exit, nor will any smaller one.
9445 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9446 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9447 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9448 AR && AR->getLoop() == L && AR->isAffine() &&
9449 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9450 isKnownPositive(AR->getStepRecurrence(*this))) {
9451 auto Flags = AR->getNoWrapFlags();
9452 Flags = setFlags(Flags, WrapType);
9455 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9456 }
9457 }
9458 }
9459
9460 switch (Pred) {
9461 case ICmpInst::ICMP_NE: { // while (X != Y)
9462 // Convert to: while (X-Y != 0)
9463 if (LHS->getType()->isPointerTy()) {
9466 return LHS;
9467 }
9468 if (RHS->getType()->isPointerTy()) {
9471 return RHS;
9472 }
9473 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9474 AllowPredicates);
9475 if (EL.hasAnyInfo())
9476 return EL;
9477 break;
9478 }
9479 case ICmpInst::ICMP_EQ: { // while (X == Y)
9480 // Convert to: while (X-Y == 0)
9481 if (LHS->getType()->isPointerTy()) {
9484 return LHS;
9485 }
9486 if (RHS->getType()->isPointerTy()) {
9489 return RHS;
9490 }
9491 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9492 if (EL.hasAnyInfo()) return EL;
9493 break;
9494 }
9495 case ICmpInst::ICMP_SLE:
9496 case ICmpInst::ICMP_ULE:
9497 // Since the loop is finite, an invariant RHS cannot include the boundary
9498 // value, otherwise it would loop forever.
9499 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9500 !isLoopInvariant(RHS, L)) {
9501 // Otherwise, perform the addition in a wider type, to avoid overflow.
9502 // If the LHS is an addrec with the appropriate nowrap flag, the
9503 // extension will be sunk into it and the exit count can be analyzed.
9504 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9505 if (!OldType)
9506 break;
9507 // Prefer doubling the bitwidth over adding a single bit to make it more
9508 // likely that we use a legal type.
9509 auto *NewType =
9510 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9511 if (ICmpInst::isSigned(Pred)) {
9512 LHS = getSignExtendExpr(LHS, NewType);
9513 RHS = getSignExtendExpr(RHS, NewType);
9514 } else {
9515 LHS = getZeroExtendExpr(LHS, NewType);
9516 RHS = getZeroExtendExpr(RHS, NewType);
9517 }
9518 }
9520 [[fallthrough]];
9521 case ICmpInst::ICMP_SLT:
9522 case ICmpInst::ICMP_ULT: { // while (X < Y)
9523 bool IsSigned = ICmpInst::isSigned(Pred);
9524 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/false,
9525 ControlsOnlyExit, AllowPredicates);
9526 if (EL.hasAnyInfo())
9527 return EL;
9528 break;
9529 }
9530 case ICmpInst::ICMP_SGE:
9531 case ICmpInst::ICMP_UGE:
9532 // Since the loop is finite, an invariant RHS cannot include the boundary
9533 // value, otherwise it would loop forever.
9534 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9535 !isLoopInvariant(RHS, L))
9536 break;
9538 [[fallthrough]];
9539 case ICmpInst::ICMP_SGT:
9540 case ICmpInst::ICMP_UGT: { // while (X > Y)
9541 // "X > Y" is analyzed as the equivalent "~X < ~Y".
9542 bool IsSigned = ICmpInst::isSigned(Pred);
9543 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, /*Invert=*/true,
9544 ControlsOnlyExit, AllowPredicates);
9545 if (EL.hasAnyInfo())
9546 return EL;
9547 break;
9548 }
9549 default:
9550 break;
9551 }
9552
9553 return getCouldNotCompute();
9554}
9555
9556ScalarEvolution::ExitLimit
9557ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9558 SwitchInst *Switch,
9559 BasicBlock *ExitingBlock,
9560 bool ControlsOnlyExit) {
9561 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9562
9563 // Give up if the exit is the default dest of a switch.
9564 if (Switch->getDefaultDest() == ExitingBlock)
9565 return getCouldNotCompute();
9566
9567 assert(L->contains(Switch->getDefaultDest()) &&
9568 "Default case must not exit the loop!");
9569 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9570 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9571
9572 // while (X != Y) --> while (X-Y != 0)
9573 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9574 if (EL.hasAnyInfo())
9575 return EL;
9576
9577 return getCouldNotCompute();
9578}
9579
9580static ConstantInt *
9582 ScalarEvolution &SE) {
9583 const SCEV *InVal = SE.getConstant(C);
9584 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9586 "Evaluation of SCEV at constant didn't fold correctly?");
9587 return cast<SCEVConstant>(Val)->getValue();
9588}
9589
9590ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9591 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9592 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9593 if (!RHS)
9594 return getCouldNotCompute();
9595
9596 const BasicBlock *Latch = L->getLoopLatch();
9597 if (!Latch)
9598 return getCouldNotCompute();
9599
9600 const BasicBlock *Predecessor = L->getLoopPredecessor();
9601 if (!Predecessor)
9602 return getCouldNotCompute();
9603
9604 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9605 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9606 // OutShiftAmt.
9607 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9608 Instruction::BinaryOps &OutOpCode,
9609 unsigned &OutShiftAmt) {
9610 using namespace PatternMatch;
9611
9612 ConstantInt *ShiftAmt;
9613 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9614 OutOpCode = Instruction::LShr;
9615 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9616 OutOpCode = Instruction::AShr;
9617 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9618 OutOpCode = Instruction::Shl;
9619 else
9620 return false;
9621
9622 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9623 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9624 return false;
9625 OutShiftAmt = Amt;
9626 return true;
9627 };
9628
9629 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9630 //
9631 // loop:
9632 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9633 // %iv.shifted = lshr i32 %iv, <positive constant>
9634 //
9635 // Return true on a successful match. Return the corresponding PHI node (%iv
9636 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9637 // shift amount in ShiftAmtOut.
9638 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9639 Instruction::BinaryOps &OpCodeOut,
9640 unsigned &ShiftAmtOut) {
9641 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9642
9643 {
9645 Value *V;
9646 unsigned Amt;
9647
9648 // If we encounter a shift instruction, "peel off" the shift operation,
9649 // and remember that we did so. Later when we inspect %iv's backedge
9650 // value, we will make sure that the backedge value uses the same
9651 // operation.
9652 //
9653 // Note: the peeled shift operation does not have to be the same
9654 // instruction as the one feeding into the PHI's backedge value. We only
9655 // really care about it being the same *kind* of shift instruction --
9656 // that's all that is required for our later inferences to hold.
9657 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9658 PostShiftOpCode = OpC;
9659 LHS = V;
9660 }
9661 }
9662
9663 PNOut = dyn_cast<PHINode>(LHS);
9664 if (!PNOut || PNOut->getParent() != L->getHeader())
9665 return false;
9666
9667 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9668 Value *OpLHS;
9669
9670 return
9671 // The backedge value for the PHI node must be a shift by a positive
9672 // amount
9673 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9674
9675 // of the PHI node itself
9676 OpLHS == PNOut &&
9677
9678 // and the kind of shift should be match the kind of shift we peeled
9679 // off, if any.
9680 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9681 };
9682
9683 PHINode *PN;
9685 unsigned ShiftAmt;
9686 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9687 return getCouldNotCompute();
9688
9689 const DataLayout &DL = getDataLayout();
9690
9691 // The key rationale for this optimization is that for some kinds of shift
9692 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9693 // within a finite number of iterations. If the condition guarding the
9694 // backedge (in the sense that the backedge is taken if the condition is true)
9695 // is false for the value the shift recurrence stabilizes to, then we know
9696 // that the backedge is taken only a finite number of times.
9697
9698 ConstantInt *StableValue = nullptr;
9699 switch (OpCode) {
9700 default:
9701 llvm_unreachable("Impossible case!");
9702
9703 case Instruction::AShr: {
9704 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9705 // bitwidth(K) iterations.
9706 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9707 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9708 Predecessor->getTerminator(), &DT);
9709 auto *Ty = cast<IntegerType>(RHS->getType());
9710 if (Known.isNonNegative())
9711 StableValue = ConstantInt::get(Ty, 0);
9712 else if (Known.isNegative())
9713 StableValue = ConstantInt::get(Ty, -1, true);
9714 else
9715 return getCouldNotCompute();
9716
9717 break;
9718 }
9719 case Instruction::LShr:
9720 case Instruction::Shl:
9721 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9722 // stabilize to 0 in at most bitwidth(K) iterations.
9723 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9724 break;
9725 }
9726
9727 auto *Result =
9728 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9729 assert(Result->getType()->isIntegerTy(1) &&
9730 "Otherwise cannot be an operand to a branch instruction");
9731
9732 if (Result->isNullValue()) {
9733 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9734 unsigned MaxBTC = BitWidth;
9735
9736 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9737 // compute a tighter max backedge-taken count from the range of the start
9738 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9739 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9740 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9741 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9742 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9743 const SCEV *StartSCEV = getSCEV(StartValue);
9744 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9745 if (MaxStart.isStrictlyPositive()) {
9746 unsigned ActiveBits = MaxStart.getActiveBits();
9747 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9748 MaxBTC = std::min(MaxBTC, RangeBTC);
9749 }
9750 }
9751
9752 const SCEV *UpperBound =
9754 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9755 }
9756
9757 return getCouldNotCompute();
9758}
9759
9760/// Return true if we can constant fold an instruction of the specified type,
9761/// assuming that all operands were constants.
9762static bool canConstantFold(const Instruction *I,
9763 const TargetLibraryInfo *TLI) {
9767 return true;
9768
9769 if (const CallInst *CI = dyn_cast<CallInst>(I))
9770 if (const Function *F = CI->getCalledFunction())
9771 return canConstantFoldCallTo(CI, F, TLI);
9772 return false;
9773}
9774
9775/// Determine whether this instruction can constant evolve within this loop
9776/// assuming its operands can all constant evolve.
9777static bool canConstantEvolve(Instruction *I, const Loop *L,
9778 const TargetLibraryInfo *TLI) {
9779 // An instruction outside of the loop can't be derived from a loop PHI.
9780 if (!L->contains(I)) return false;
9781
9782 if (isa<PHINode>(I)) {
9783 // We don't currently keep track of the control flow needed to evaluate
9784 // PHIs, so we cannot handle PHIs inside of loops.
9785 return L->getHeader() == I->getParent();
9786 }
9787
9788 // If we won't be able to constant fold this expression even if the operands
9789 // are constants, bail early.
9790 return canConstantFold(I, TLI);
9791}
9792
9793/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9794/// recursing through each instruction operand until reaching a loop header phi.
9795static PHINode *
9798 const TargetLibraryInfo *TLI, unsigned Depth) {
9800 return nullptr;
9801
9802 // Otherwise, we can evaluate this instruction if all of its operands are
9803 // constant or derived from a PHI node themselves.
9804 PHINode *PHI = nullptr;
9805 for (Value *Op : UseInst->operands()) {
9806 if (isa<Constant>(Op)) continue;
9807
9809 if (!OpInst || !canConstantEvolve(OpInst, L, TLI))
9810 return nullptr;
9811
9812 PHINode *P = dyn_cast<PHINode>(OpInst);
9813 if (!P)
9814 // If this operand is already visited, reuse the prior result.
9815 // We may have P != PHI if this is the deepest point at which the
9816 // inconsistent paths meet.
9817 P = PHIMap.lookup(OpInst);
9818 if (!P) {
9819 // Recurse and memoize the results, whether a phi is found or not.
9820 // This recursive call invalidates pointers into PHIMap.
9821 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, TLI, Depth + 1);
9822 PHIMap[OpInst] = P;
9823 }
9824 if (!P)
9825 return nullptr; // Not evolving from PHI
9826 if (PHI && PHI != P)
9827 return nullptr; // Evolving from multiple different PHIs.
9828 PHI = P;
9829 }
9830 // This is a expression evolving from a constant PHI!
9831 return PHI;
9832}
9833
9834/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9835/// in the loop that V is derived from. We allow arbitrary operations along the
9836/// way, but the operands of an operation must either be constants or a value
9837/// derived from a constant PHI. If this expression does not fit with these
9838/// constraints, return null.
9840 const TargetLibraryInfo *TLI) {
9842 if (!I || !canConstantEvolve(I, L, TLI))
9843 return nullptr;
9844
9845 if (PHINode *PN = dyn_cast<PHINode>(I))
9846 return PN;
9847
9848 // Record non-constant instructions contained by the loop.
9850 return getConstantEvolvingPHIOperands(I, L, PHIMap, TLI, 0);
9851}
9852
9853/// EvaluateExpression - Given an expression that passes the
9854/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9855/// in the loop has the value PHIVal. If we can't fold this expression for some
9856/// reason, return null.
9859 const DataLayout &DL,
9860 const TargetLibraryInfo *TLI) {
9861 // Convenient constant check, but redundant for recursive calls.
9862 if (Constant *C = dyn_cast<Constant>(V)) return C;
9864 if (!I) return nullptr;
9865
9866 if (Constant *C = Vals.lookup(I)) return C;
9867
9868 // An instruction inside the loop depends on a value outside the loop that we
9869 // weren't given a mapping for, or a value such as a call inside the loop.
9870 if (!canConstantEvolve(I, L, TLI))
9871 return nullptr;
9872
9873 // An unmapped PHI can be due to a branch or another loop inside this loop,
9874 // or due to this not being the initial iteration through a loop where we
9875 // couldn't compute the evolution of this particular PHI last time.
9876 if (isa<PHINode>(I)) return nullptr;
9877
9878 std::vector<Constant*> Operands(I->getNumOperands());
9879
9880 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9881 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9882 if (!Operand) {
9883 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9884 if (!Operands[i]) return nullptr;
9885 continue;
9886 }
9887 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9888 Vals[Operand] = C;
9889 if (!C) return nullptr;
9890 Operands[i] = C;
9891 }
9892
9893 return ConstantFoldInstOperands(I, Operands, DL, TLI,
9894 /*AllowNonDeterministic=*/false);
9895}
9896
9897
9898// If every incoming value to PN except the one for BB is a specific Constant,
9899// return that, else return nullptr.
9901 Constant *IncomingVal = nullptr;
9902
9903 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9904 if (PN->getIncomingBlock(i) == BB)
9905 continue;
9906
9907 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
9908 if (!CurrentVal)
9909 return nullptr;
9910
9911 if (IncomingVal != CurrentVal) {
9912 if (IncomingVal)
9913 return nullptr;
9914 IncomingVal = CurrentVal;
9915 }
9916 }
9917
9918 return IncomingVal;
9919}
9920
9921/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
9922/// in the header of its containing loop, we know the loop executes a
9923/// constant number of times, and the PHI node is just a recurrence
9924/// involving constants, fold it.
9925Constant *
9926ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
9927 const APInt &BEs,
9928 const Loop *L) {
9929 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
9930 if (!Inserted)
9931 return I->second;
9932
9934 return nullptr; // Not going to evaluate it.
9935
9936 Constant *&RetVal = I->second;
9937
9938 DenseMap<Instruction *, Constant *> CurrentIterVals;
9939 BasicBlock *Header = L->getHeader();
9940 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
9941
9942 BasicBlock *Latch = L->getLoopLatch();
9943 if (!Latch)
9944 return nullptr;
9945
9946 for (PHINode &PHI : Header->phis()) {
9947 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
9948 CurrentIterVals[&PHI] = StartCST;
9949 }
9950 if (!CurrentIterVals.count(PN))
9951 return RetVal = nullptr;
9952
9953 Value *BEValue = PN->getIncomingValueForBlock(Latch);
9954
9955 // Execute the loop symbolically to determine the exit value.
9956 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
9957 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
9958
9959 unsigned NumIterations = BEs.getZExtValue(); // must be in range
9960 unsigned IterationNum = 0;
9961 const DataLayout &DL = getDataLayout();
9962 for (; ; ++IterationNum) {
9963 if (IterationNum == NumIterations)
9964 return RetVal = CurrentIterVals[PN]; // Got exit value!
9965
9966 // Compute the value of the PHIs for the next iteration.
9967 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
9968 DenseMap<Instruction *, Constant *> NextIterVals;
9969 Constant *NextPHI =
9970 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9971 if (!NextPHI)
9972 return nullptr; // Couldn't evaluate!
9973 NextIterVals[PN] = NextPHI;
9974
9975 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
9976
9977 // Also evaluate the other PHI nodes. However, we don't get to stop if we
9978 // cease to be able to evaluate one of them or if they stop evolving,
9979 // because that doesn't necessarily prevent us from computing PN.
9981 for (const auto &I : CurrentIterVals) {
9982 PHINode *PHI = dyn_cast<PHINode>(I.first);
9983 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
9984 PHIsToCompute.emplace_back(PHI, I.second);
9985 }
9986 // We use two distinct loops because EvaluateExpression may invalidate any
9987 // iterators into CurrentIterVals.
9988 for (const auto &I : PHIsToCompute) {
9989 PHINode *PHI = I.first;
9990 Constant *&NextPHI = NextIterVals[PHI];
9991 if (!NextPHI) { // Not already computed.
9992 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
9993 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
9994 }
9995 if (NextPHI != I.second)
9996 StoppedEvolving = false;
9997 }
9998
9999 // If all entries in CurrentIterVals == NextIterVals then we can stop
10000 // iterating, the loop can't continue to change.
10001 if (StoppedEvolving)
10002 return RetVal = CurrentIterVals[PN];
10003
10004 CurrentIterVals.swap(NextIterVals);
10005 }
10006}
10007
10008const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10009 Value *Cond,
10010 bool ExitWhen) {
10011 PHINode *PN = getConstantEvolvingPHI(Cond, L, &TLI);
10012 if (!PN) return getCouldNotCompute();
10013
10014 // If the loop is canonicalized, the PHI will have exactly two entries.
10015 // That's the only form we support here.
10016 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10017
10018 DenseMap<Instruction *, Constant *> CurrentIterVals;
10019 BasicBlock *Header = L->getHeader();
10020 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10021
10022 BasicBlock *Latch = L->getLoopLatch();
10023 assert(Latch && "Should follow from NumIncomingValues == 2!");
10024
10025 for (PHINode &PHI : Header->phis()) {
10026 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10027 CurrentIterVals[&PHI] = StartCST;
10028 }
10029 if (!CurrentIterVals.count(PN))
10030 return getCouldNotCompute();
10031
10032 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10033 // the loop symbolically to determine when the condition gets a value of
10034 // "ExitWhen".
10035 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10036 const DataLayout &DL = getDataLayout();
10037 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10038 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10039 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10040
10041 // Couldn't symbolically evaluate.
10042 if (!CondVal) return getCouldNotCompute();
10043
10044 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10045 ++NumBruteForceTripCountsComputed;
10046 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10047 }
10048
10049 // Update all the PHI nodes for the next iteration.
10050 DenseMap<Instruction *, Constant *> NextIterVals;
10051
10052 // Create a list of which PHIs we need to compute. We want to do this before
10053 // calling EvaluateExpression on them because that may invalidate iterators
10054 // into CurrentIterVals.
10055 SmallVector<PHINode *, 8> PHIsToCompute;
10056 for (const auto &I : CurrentIterVals) {
10057 PHINode *PHI = dyn_cast<PHINode>(I.first);
10058 if (!PHI || PHI->getParent() != Header) continue;
10059 PHIsToCompute.push_back(PHI);
10060 }
10061 for (PHINode *PHI : PHIsToCompute) {
10062 Constant *&NextPHI = NextIterVals[PHI];
10063 if (NextPHI) continue; // Already computed!
10064
10065 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10066 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10067 }
10068 CurrentIterVals.swap(NextIterVals);
10069 }
10070
10071 // Too many iterations were needed to evaluate.
10072 return getCouldNotCompute();
10073}
10074
10076 if (isa<SCEVConstant>(V))
10077 return V;
10078
10079 auto &Values = ValuesAtScopes[V];
10080 // Check to see if we've folded this expression at this loop before.
10081 for (auto &LS : Values)
10082 if (LS.first == L)
10083 return LS.second ? LS.second : SCEVUse(V);
10084
10085 Values.emplace_back(L, nullptr);
10086
10087 // Otherwise compute it.
10088 SCEVUse C = computeSCEVAtScope(V, L);
10089 for (auto &LS : reverse(ValuesAtScopes[V]))
10090 if (LS.first == L) {
10091 LS.second = C;
10092 // Record the dependency under the bare expression: invalidation walks
10093 // expressions, and any use flags on C do not change which expression
10094 // this is the value at scope of.
10095 if (!isa<SCEVConstant>(C))
10096 ValuesAtScopesUsers[C.getPointer()].push_back({L, V});
10097 break;
10098 }
10099 return C;
10100}
10101
10103 const BasicBlock *ExitingBlock) {
10104 SCEVUse ExitValue = getSCEVAtScope(V, L->getParentLoop());
10105 if (!isLoopInvariant(ExitValue, L)) {
10106 // If we failed to evaluate it in the outer scope, try to evaluate an
10107 // addrec for the specific exit.
10108 // TODO: Generalize this to other expressions.
10109 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
10110 if (!isa<SCEVCouldNotCompute>(ExitCount))
10111 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V))
10112 if (AddRec->getLoop() == L)
10113 ExitValue = AddRec->evaluateAtIteration(ExitCount, *this);
10114 }
10115 return ExitValue;
10116}
10117
10118/// This builds up a Constant using the ConstantExpr interface. That way, we
10119/// will return Constants for objects which aren't represented by a
10120/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10121/// Returns NULL if the SCEV isn't representable as a Constant.
10123 switch (V->getSCEVType()) {
10124 case scCouldNotCompute:
10125 case scAddRecExpr:
10126 case scVScale:
10127 return nullptr;
10128 case scConstant:
10129 return cast<SCEVConstant>(V)->getValue();
10130 case scUnknown:
10132 case scPtrToAddr: {
10134 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10135 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10136
10137 return nullptr;
10138 }
10139 case scTruncate: {
10141 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10142 return ConstantExpr::getTrunc(CastOp, ST->getType());
10143 return nullptr;
10144 }
10145 case scAddExpr: {
10146 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10147 Constant *C = nullptr;
10148 for (const SCEV *Op : SA->operands()) {
10150 if (!OpC)
10151 return nullptr;
10152 if (!C) {
10153 C = OpC;
10154 continue;
10155 }
10156 assert(!C->getType()->isPointerTy() &&
10157 "Can only have one pointer, and it must be last");
10158 if (OpC->getType()->isPointerTy()) {
10159 // The offsets have been converted to bytes. We can add bytes using
10160 // an i8 GEP.
10161 C = ConstantExpr::getPtrAdd(OpC, C);
10162 } else {
10163 C = ConstantExpr::getAdd(C, OpC);
10164 }
10165 }
10166 return C;
10167 }
10168 case scMulExpr:
10169 case scSignExtend:
10170 case scZeroExtend:
10171 case scUDivExpr:
10172 case scSMaxExpr:
10173 case scUMaxExpr:
10174 case scSMinExpr:
10175 case scUMinExpr:
10177 return nullptr;
10178 }
10179 llvm_unreachable("Unknown SCEV kind!");
10180}
10181
10182const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10183 SmallVectorImpl<SCEVUse> &NewOps) {
10184 switch (S->getSCEVType()) {
10185 case scTruncate:
10186 case scZeroExtend:
10187 case scSignExtend:
10188 case scPtrToAddr:
10189 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10190 case scAddRecExpr: {
10191 auto *AddRec = cast<SCEVAddRecExpr>(S);
10192 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10193 }
10194 case scAddExpr:
10195 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10196 case scMulExpr:
10197 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10198 case scUDivExpr:
10199 return getUDivExpr(NewOps[0], NewOps[1]);
10200 case scUMaxExpr:
10201 case scSMaxExpr:
10202 case scUMinExpr:
10203 case scSMinExpr:
10204 return getMinMaxExpr(S->getSCEVType(), NewOps);
10206 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10207 case scConstant:
10208 case scVScale:
10209 case scUnknown:
10210 return S;
10211 case scCouldNotCompute:
10212 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10213 }
10214 llvm_unreachable("Unknown SCEV kind!");
10215}
10216
10217SCEVUse ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10218 switch (V->getSCEVType()) {
10219 case scConstant:
10220 case scVScale:
10221 return V;
10222 case scAddRecExpr: {
10223 // If this is a loop recurrence for a loop that does not contain L, then we
10224 // are dealing with the final value computed by the loop.
10225 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10226 // First, attempt to evaluate each operand.
10227 // Avoid performing the look-up in the common case where the specified
10228 // expression has no loop-variant portions.
10229 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10230 SCEVUse OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10231 if (OpAtScope == AddRec->getOperand(i))
10232 continue;
10233
10234 // Okay, at least one of these operands is loop variant but might be
10235 // foldable. Build a new instance of the folded commutative expression.
10237 NewOps.reserve(AddRec->getNumOperands());
10238 append_range(NewOps, AddRec->operands().take_front(i));
10239 NewOps.push_back(OpAtScope);
10240 for (++i; i != e; ++i)
10241 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10242
10243 const SCEV *FoldedRec = getAddRecExpr(
10244 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10245 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10246 // The addrec may be folded to a nonrecurrence, for example, if the
10247 // induction variable is multiplied by zero after constant folding. Go
10248 // ahead and return the folded value.
10249 if (!AddRec)
10250 return FoldedRec;
10251 break;
10252 }
10253
10254 // If the scope is outside the addrec's loop, evaluate it by using the
10255 // loop exit value of the addrec.
10256 if (!AddRec->getLoop()->contains(L)) {
10257 SCEVUse ExitValue = AddRec->getExitValue(*this);
10258 if (isa<SCEVCouldNotCompute>(ExitValue))
10259 return AddRec;
10260 return ExitValue;
10261 }
10262
10263 return AddRec;
10264 }
10265 case scTruncate:
10266 case scZeroExtend:
10267 case scSignExtend:
10268 case scPtrToAddr:
10269 case scAddExpr:
10270 case scMulExpr:
10271 case scUDivExpr:
10272 case scUMaxExpr:
10273 case scSMaxExpr:
10274 case scUMinExpr:
10275 case scSMinExpr:
10276 case scSequentialUMinExpr: {
10277 ArrayRef<SCEVUse> Ops = V->operands();
10278 // Avoid performing the look-up in the common case where the specified
10279 // expression has no loop-variant portions.
10280 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10281 SCEVUse OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10282 if (OpAtScope != Ops[i].getPointer()) {
10283 // Okay, at least one of these operands is loop variant but might be
10284 // foldable. Build a new instance of the folded commutative expression.
10286 NewOps.reserve(Ops.size());
10287 append_range(NewOps, Ops.take_front(i));
10288 NewOps.push_back(OpAtScope);
10289
10290 for (++i; i != e; ++i) {
10291 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10292 NewOps.push_back(OpAtScope);
10293 }
10294
10295 return getWithOperands(V, NewOps);
10296 }
10297 }
10298 // If we got here, all operands are loop invariant.
10299 return V;
10300 }
10301 case scUnknown: {
10302 // If this instruction is evolved from a constant-evolving PHI, compute the
10303 // exit value from the loop without using SCEVs.
10304 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10306 if (!I)
10307 return V; // This is some other type of SCEVUnknown, just return it.
10308
10309 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10310 const Loop *CurrLoop = this->LI[I->getParent()];
10311 // Looking for loop exit value.
10312 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10313 PN->getParent() == CurrLoop->getHeader()) {
10314 // Okay, there is no closed form solution for the PHI node. Check
10315 // to see if the loop that contains it has a known backedge-taken
10316 // count. If so, we may be able to force computation of the exit
10317 // value.
10318 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10319 // This trivial case can show up in some degenerate cases where
10320 // the incoming IR has not yet been fully simplified.
10321 if (BackedgeTakenCount->isZero()) {
10322 Value *InitValue = nullptr;
10323 bool MultipleInitValues = false;
10324 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10325 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10326 if (!InitValue)
10327 InitValue = PN->getIncomingValue(i);
10328 else if (InitValue != PN->getIncomingValue(i)) {
10329 MultipleInitValues = true;
10330 break;
10331 }
10332 }
10333 }
10334 if (!MultipleInitValues && InitValue)
10335 return getSCEV(InitValue);
10336 }
10337 // Do we have a loop invariant value flowing around the backedge
10338 // for a loop which must execute the backedge?
10339 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10340 isKnownNonZero(BackedgeTakenCount) &&
10341 PN->getNumIncomingValues() == 2) {
10342
10343 unsigned InLoopPred =
10344 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10345 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10346 if (CurrLoop->isLoopInvariant(BackedgeVal))
10347 return getSCEV(BackedgeVal);
10348 }
10349 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10350 // Okay, we know how many times the containing loop executes. If
10351 // this is a constant evolving PHI node, get the final value at
10352 // the specified iteration number.
10353 Constant *RV =
10354 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10355 if (RV)
10356 return getSCEV(RV);
10357 }
10358 }
10359 }
10360
10361 // Okay, this is an expression that we cannot symbolically evaluate
10362 // into a SCEV. Check to see if it's possible to symbolically evaluate
10363 // the arguments into constants, and if so, try to constant propagate the
10364 // result. This is particularly useful for computing loop exit values.
10365 if (!canConstantFold(I, &TLI))
10366 return V; // This is some other type of SCEVUnknown, just return it.
10367
10368 SmallVector<Constant *, 4> Operands;
10369 Operands.reserve(I->getNumOperands());
10370 bool MadeImprovement = false;
10371 for (Value *Op : I->operands()) {
10372 if (Constant *C = dyn_cast<Constant>(Op)) {
10373 Operands.push_back(C);
10374 continue;
10375 }
10376
10377 // If any of the operands is non-constant and if they are
10378 // non-integer and non-pointer, don't even try to analyze them
10379 // with scev techniques.
10380 if (!isSCEVable(Op->getType()))
10381 return V;
10382
10383 const SCEV *OrigV = getSCEV(Op);
10384 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10385 MadeImprovement |= OrigV != OpV;
10386
10388 if (!C)
10389 return V;
10390 assert(C->getType() == Op->getType() && "Type mismatch");
10391 Operands.push_back(C);
10392 }
10393
10394 // Check to see if getSCEVAtScope actually made an improvement.
10395 if (!MadeImprovement)
10396 return V; // This is some other type of SCEVUnknown, just return it.
10397
10398 Constant *C = nullptr;
10399 const DataLayout &DL = getDataLayout();
10400 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10401 /*AllowNonDeterministic=*/false);
10402 if (!C)
10403 return V;
10404 return getSCEV(C);
10405 }
10406 case scCouldNotCompute:
10407 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10408 }
10409 llvm_unreachable("Unknown SCEV type!");
10410}
10411
10413 return getSCEVAtScope(getSCEV(V), L);
10414}
10415
10416const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10418 return stripInjectiveFunctions(ZExt->getOperand());
10420 return stripInjectiveFunctions(SExt->getOperand());
10421 return S;
10422}
10423
10424/// Finds the minimum unsigned root of the following equation:
10425///
10426/// A * X = B (mod N)
10427///
10428/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10429/// A and B isn't important.
10430///
10431/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10432static const SCEV *
10435 ScalarEvolution &SE, const Loop *L) {
10436 uint32_t BW = A.getBitWidth();
10437 assert(BW == SE.getTypeSizeInBits(B->getType()));
10438 assert(A != 0 && "A must be non-zero.");
10439
10440 // 1. D = gcd(A, N)
10441 //
10442 // The gcd of A and N may have only one prime factor: 2. The number of
10443 // trailing zeros in A is its multiplicity
10444 uint32_t Mult2 = A.countr_zero();
10445 // D = 2^Mult2
10446
10447 // 2. Check if B is divisible by D.
10448 //
10449 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10450 // is not less than multiplicity of this prime factor for D.
10451 unsigned MinTZ = SE.getMinTrailingZeros(B);
10452 // Try again with the terminator of the loop predecessor for context-specific
10453 // result, if MinTZ s too small.
10454 if (MinTZ < Mult2 && L->getLoopPredecessor())
10455 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10456 if (MinTZ < Mult2) {
10457 // Check if we can prove there's no remainder using URem.
10458 const SCEV *URem =
10459 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10460 const SCEV *Zero = SE.getZero(B->getType());
10461 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10462 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10463 if (!Predicates)
10464 return SE.getCouldNotCompute();
10465
10466 // Avoid adding a predicate that is known to be false.
10467 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10468 return SE.getCouldNotCompute();
10469 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10470 }
10471 }
10472
10473 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10474 // modulo (N / D).
10475 //
10476 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10477 // (N / D) in general. The inverse itself always fits into BW bits, though,
10478 // so we immediately truncate it.
10479 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10480 APInt I = AD.multiplicativeInverse().zext(BW);
10481
10482 // 4. Compute the minimum unsigned root of the equation:
10483 // I * (B / D) mod (N / D)
10484 // To simplify the computation, we factor out the divide by D:
10485 // (I * B mod N) / D
10486 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10487 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10488}
10489
10490/// For a given quadratic addrec, generate coefficients of the corresponding
10491/// quadratic equation, multiplied by a common value to ensure that they are
10492/// integers.
10493/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10494/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10495/// were multiplied by, and BitWidth is the bit width of the original addrec
10496/// coefficients.
10497/// This function returns std::nullopt if the addrec coefficients are not
10498/// compile- time constants.
10499static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10501 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10502 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10503 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10504 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10505 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10506 << *AddRec << '\n');
10507
10508 // We currently can only solve this if the coefficients are constants.
10509 if (!LC || !MC || !NC) {
10510 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10511 return std::nullopt;
10512 }
10513
10514 APInt L = LC->getAPInt();
10515 APInt M = MC->getAPInt();
10516 APInt N = NC->getAPInt();
10517 assert(!N.isZero() && "This is not a quadratic addrec");
10518
10519 unsigned BitWidth = LC->getAPInt().getBitWidth();
10520 unsigned NewWidth = BitWidth + 1;
10521 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10522 << BitWidth << '\n');
10523 // The sign-extension (as opposed to a zero-extension) here matches the
10524 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10525 N = N.sext(NewWidth);
10526 M = M.sext(NewWidth);
10527 L = L.sext(NewWidth);
10528
10529 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10530 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10531 // L+M, L+2M+N, L+3M+3N, ...
10532 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10533 //
10534 // The equation Acc = 0 is then
10535 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10536 // In a quadratic form it becomes:
10537 // N n^2 + (2M-N) n + 2L = 0.
10538
10539 APInt A = N;
10540 APInt B = 2 * M - A;
10541 APInt C = 2 * L;
10542 APInt T = APInt(NewWidth, 2);
10543 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10544 << "x + " << C << ", coeff bw: " << NewWidth
10545 << ", multiplied by " << T << '\n');
10546 return std::make_tuple(A, B, C, T, BitWidth);
10547}
10548
10549/// Helper function to compare optional APInts:
10550/// (a) if X and Y both exist, return min(X, Y),
10551/// (b) if neither X nor Y exist, return std::nullopt,
10552/// (c) if exactly one of X and Y exists, return that value.
10553static std::optional<APInt> MinOptional(std::optional<APInt> X,
10554 std::optional<APInt> Y) {
10555 if (X && Y) {
10556 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10557 APInt XW = X->sext(W);
10558 APInt YW = Y->sext(W);
10559 return XW.slt(YW) ? *X : *Y;
10560 }
10561 if (!X && !Y)
10562 return std::nullopt;
10563 return X ? *X : *Y;
10564}
10565
10566/// Helper function to truncate an optional APInt to a given BitWidth.
10567/// When solving addrec-related equations, it is preferable to return a value
10568/// that has the same bit width as the original addrec's coefficients. If the
10569/// solution fits in the original bit width, truncate it (except for i1).
10570/// Returning a value of a different bit width may inhibit some optimizations.
10571///
10572/// In general, a solution to a quadratic equation generated from an addrec
10573/// may require BW+1 bits, where BW is the bit width of the addrec's
10574/// coefficients. The reason is that the coefficients of the quadratic
10575/// equation are BW+1 bits wide (to avoid truncation when converting from
10576/// the addrec to the equation).
10577static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10578 unsigned BitWidth) {
10579 if (!X)
10580 return std::nullopt;
10581 unsigned W = X->getBitWidth();
10583 return X->trunc(BitWidth);
10584 return X;
10585}
10586
10587/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10588/// iterations. The values L, M, N are assumed to be signed, and they
10589/// should all have the same bit widths.
10590/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10591/// where BW is the bit width of the addrec's coefficients.
10592/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10593/// returned as such, otherwise the bit width of the returned value may
10594/// be greater than BW.
10595///
10596/// This function returns std::nullopt if
10597/// (a) the addrec coefficients are not constant, or
10598/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10599/// like x^2 = 5, no integer solutions exist, in other cases an integer
10600/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10601static std::optional<APInt>
10603 APInt A, B, C, M;
10604 unsigned BitWidth;
10605 auto T = GetQuadraticEquation(AddRec);
10606 if (!T)
10607 return std::nullopt;
10608
10609 std::tie(A, B, C, M, BitWidth) = *T;
10610 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10611 std::optional<APInt> X =
10613 if (!X)
10614 return std::nullopt;
10615
10616 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10617 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10618 if (!V->isZero())
10619 return std::nullopt;
10620
10621 return TruncIfPossible(X, BitWidth);
10622}
10623
10624/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10625/// iterations. The values M, N are assumed to be signed, and they
10626/// should all have the same bit widths.
10627/// Find the least n such that c(n) does not belong to the given range,
10628/// while c(n-1) does.
10629///
10630/// This function returns std::nullopt if
10631/// (a) the addrec coefficients are not constant, or
10632/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10633/// bounds of the range.
10634static std::optional<APInt>
10636 const ConstantRange &Range, ScalarEvolution &SE) {
10637 assert(AddRec->getOperand(0)->isZero() &&
10638 "Starting value of addrec should be 0");
10639 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10640 << Range << ", addrec " << *AddRec << '\n');
10641 // This case is handled in getNumIterationsInRange. Here we can assume that
10642 // we start in the range.
10643 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10644 "Addrec's initial value should be in range");
10645
10646 APInt A, B, C, M;
10647 unsigned BitWidth;
10648 auto T = GetQuadraticEquation(AddRec);
10649 if (!T)
10650 return std::nullopt;
10651
10652 // Be careful about the return value: there can be two reasons for not
10653 // returning an actual number. First, if no solutions to the equations
10654 // were found, and second, if the solutions don't leave the given range.
10655 // The first case means that the actual solution is "unknown", the second
10656 // means that it's known, but not valid. If the solution is unknown, we
10657 // cannot make any conclusions.
10658 // Return a pair: the optional solution and a flag indicating if the
10659 // solution was found.
10660 auto SolveForBoundary =
10661 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10662 // Solve for signed overflow and unsigned overflow, pick the lower
10663 // solution.
10664 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10665 << Bound << " (before multiplying by " << M << ")\n");
10666 Bound *= M; // The quadratic equation multiplier.
10667
10668 std::optional<APInt> SO;
10669 if (BitWidth > 1) {
10670 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10671 "signed overflow\n");
10673 }
10674 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10675 "unsigned overflow\n");
10676 std::optional<APInt> UO =
10678
10679 auto LeavesRange = [&] (const APInt &X) {
10680 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10682 if (Range.contains(V0->getValue()))
10683 return false;
10684 // X should be at least 1, so X-1 is non-negative.
10685 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10687 if (Range.contains(V1->getValue()))
10688 return true;
10689 return false;
10690 };
10691
10692 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10693 // can be a solution, but the function failed to find it. We cannot treat it
10694 // as "no solution".
10695 if (!SO || !UO)
10696 return {std::nullopt, false};
10697
10698 // Check the smaller value first to see if it leaves the range.
10699 // At this point, both SO and UO must have values.
10700 std::optional<APInt> Min = MinOptional(SO, UO);
10701 if (LeavesRange(*Min))
10702 return { Min, true };
10703 std::optional<APInt> Max = Min == SO ? UO : SO;
10704 if (LeavesRange(*Max))
10705 return { Max, true };
10706
10707 // Solutions were found, but were eliminated, hence the "true".
10708 return {std::nullopt, true};
10709 };
10710
10711 std::tie(A, B, C, M, BitWidth) = *T;
10712 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10713 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10714 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10715 auto SL = SolveForBoundary(Lower);
10716 auto SU = SolveForBoundary(Upper);
10717 // If any of the solutions was unknown, no meaninigful conclusions can
10718 // be made.
10719 if (!SL.second || !SU.second)
10720 return std::nullopt;
10721
10722 // Claim: The correct solution is not some value between Min and Max.
10723 //
10724 // Justification: Assuming that Min and Max are different values, one of
10725 // them is when the first signed overflow happens, the other is when the
10726 // first unsigned overflow happens. Crossing the range boundary is only
10727 // possible via an overflow (treating 0 as a special case of it, modeling
10728 // an overflow as crossing k*2^W for some k).
10729 //
10730 // The interesting case here is when Min was eliminated as an invalid
10731 // solution, but Max was not. The argument is that if there was another
10732 // overflow between Min and Max, it would also have been eliminated if
10733 // it was considered.
10734 //
10735 // For a given boundary, it is possible to have two overflows of the same
10736 // type (signed/unsigned) without having the other type in between: this
10737 // can happen when the vertex of the parabola is between the iterations
10738 // corresponding to the overflows. This is only possible when the two
10739 // overflows cross k*2^W for the same k. In such case, if the second one
10740 // left the range (and was the first one to do so), the first overflow
10741 // would have to enter the range, which would mean that either we had left
10742 // the range before or that we started outside of it. Both of these cases
10743 // are contradictions.
10744 //
10745 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10746 // solution is not some value between the Max for this boundary and the
10747 // Min of the other boundary.
10748 //
10749 // Justification: Assume that we had such Max_A and Min_B corresponding
10750 // to range boundaries A and B and such that Max_A < Min_B. If there was
10751 // a solution between Max_A and Min_B, it would have to be caused by an
10752 // overflow corresponding to either A or B. It cannot correspond to B,
10753 // since Min_B is the first occurrence of such an overflow. If it
10754 // corresponded to A, it would have to be either a signed or an unsigned
10755 // overflow that is larger than both eliminated overflows for A. But
10756 // between the eliminated overflows and this overflow, the values would
10757 // cover the entire value space, thus crossing the other boundary, which
10758 // is a contradiction.
10759
10760 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10761}
10762
10763ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10764 const Loop *L,
10765 bool ControlsOnlyExit,
10766 bool AllowPredicates) {
10767
10768 // This is only used for loops with a "x != y" exit test. The exit condition
10769 // is now expressed as a single expression, V = x-y. So the exit test is
10770 // effectively V != 0. We know and take advantage of the fact that this
10771 // expression only being used in a comparison by zero context.
10772
10774 // If the value is a constant
10775 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10776 // If the value is already zero, the branch will execute zero times.
10777 if (C->getValue()->isZero()) return C;
10778 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10779 }
10780
10781 const SCEVAddRecExpr *AddRec =
10782 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10783
10784 if (!AddRec && AllowPredicates)
10785 // Try to make this an AddRec using runtime tests, in the first X
10786 // iterations of this loop, where X is the SCEV expression found by the
10787 // algorithm below.
10788 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10789
10790 if (!AddRec || AddRec->getLoop() != L)
10791 return getCouldNotCompute();
10792
10793 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10794 // the quadratic equation to solve it.
10795 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10796 // We can only use this value if the chrec ends up with an exact zero
10797 // value at this index. When solving for "X*X != 5", for example, we
10798 // should not accept a root of 2.
10799 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10800 const auto *R = cast<SCEVConstant>(getConstant(*S));
10801 return ExitLimit(R, R, R, false, Predicates);
10802 }
10803 return getCouldNotCompute();
10804 }
10805
10806 // Otherwise we can only handle this if it is affine.
10807 if (!AddRec->isAffine())
10808 return getCouldNotCompute();
10809
10810 // If this is an affine expression, the execution count of this branch is
10811 // the minimum unsigned root of the following equation:
10812 //
10813 // Start + Step*N = 0 (mod 2^BW)
10814 //
10815 // equivalent to:
10816 //
10817 // Step*N = -Start (mod 2^BW)
10818 //
10819 // where BW is the common bit width of Start and Step.
10820
10821 // Get the initial value for the loop.
10822 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10823 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10824
10825 if (!isLoopInvariant(Step, L))
10826 return getCouldNotCompute();
10827
10828 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
10829 // Specialize step for this loop so we get context sensitive facts below.
10830 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10831
10832 // For positive steps (counting up until unsigned overflow):
10833 // N = -Start/Step (as unsigned)
10834 // For negative steps (counting down to zero):
10835 // N = Start/-Step
10836 // First compute the unsigned distance from zero in the direction of Step.
10837 bool CountDown = isKnownNegative(StepWLG);
10838 if (!CountDown && !isKnownNonNegative(StepWLG))
10839 return getCouldNotCompute();
10840
10841 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10842 // Handle unitary steps, which cannot wraparound.
10843 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10844 // N = Distance (as unsigned)
10845
10846 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10847 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10848 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10849
10850 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10851 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10852 // case, and see if we can improve the bound.
10853 //
10854 // Explicitly handling this here is necessary because getUnsignedRange
10855 // isn't context-sensitive; it doesn't know that we only care about the
10856 // range inside the loop.
10857 const SCEV *Zero = getZero(Distance->getType());
10858 const SCEV *One = getOne(Distance->getType());
10859 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10860 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10861 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10862 // as "unsigned_max(Distance + 1) - 1". Also apply the loop guards to
10863 // Distance + 1; the range of Distance itself may be a wrapped set even
10864 // when the guards bound Distance + 1 tightly.
10865 APInt Max = APIntOps::umin(
10866 getUnsignedRangeMax(applyLoopGuards(DistancePlusOne, Guards)),
10867 getUnsignedRangeMax(DistancePlusOne));
10868 MaxBECount = APIntOps::umin(MaxBECount, Max - 1);
10869 }
10870 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10871 Predicates);
10872 }
10873
10874 // If the condition controls loop exit (the loop exits only if the expression
10875 // is true) and the addition is no-wrap we can use unsigned divide to
10876 // compute the backedge count. In this case, the step may not divide the
10877 // distance, but we don't care because if the condition is "missed" the loop
10878 // will have undefined behavior due to wrapping.
10879 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10880 loopHasNoAbnormalExits(AddRec->getLoop())) {
10881
10882 // If the stride is zero and the start is non-zero, the loop must be
10883 // infinite. In C++, most loops are finite by assumption, in which case the
10884 // step being zero implies UB must execute if the loop is entered.
10885 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10886 !isKnownNonZero(StepWLG))
10887 return getCouldNotCompute();
10888
10889 const SCEV *Exact =
10890 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10891 const SCEV *ConstantMax = getCouldNotCompute();
10892 if (Exact != getCouldNotCompute()) {
10893 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10894 ConstantMax =
10896 }
10897 const SCEV *SymbolicMax =
10898 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10899 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10900 }
10901
10902 // Solve the general equation.
10903 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
10904 if (!StepC || StepC->getValue()->isZero())
10905 return getCouldNotCompute();
10906 const SCEV *E = SolveLinEquationWithOverflow(
10907 StepC->getAPInt(), getNegativeSCEV(Start),
10908 AllowPredicates ? &Predicates : nullptr, *this, L);
10909
10910 const SCEV *M = E;
10911 if (E != getCouldNotCompute()) {
10912 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
10913 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
10914 }
10915 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
10916 return ExitLimit(E, M, S, false, Predicates);
10917}
10918
10919ScalarEvolution::ExitLimit
10920ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
10921 // Loops that look like: while (X == 0) are very strange indeed. We don't
10922 // handle them yet except for the trivial case. This could be expanded in the
10923 // future as needed.
10924
10925 // If the value is a constant, check to see if it is known to be non-zero
10926 // already. If so, the backedge will execute zero times.
10927 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10928 if (!C->getValue()->isZero())
10929 return getZero(C->getType());
10930 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10931 }
10932
10933 // We could implement others, but I really doubt anyone writes loops like
10934 // this, and if they did, they would already be constant folded.
10935 return getCouldNotCompute();
10936}
10937
10938std::pair<const BasicBlock *, const BasicBlock *>
10939ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
10940 const {
10941 // If the block has a unique predecessor, then there is no path from the
10942 // predecessor to the block that does not go through the direct edge
10943 // from the predecessor to the block.
10944 if (const BasicBlock *Pred = BB->getSinglePredecessor())
10945 return {Pred, BB};
10946
10947 // A loop's header is defined to be a block that dominates the loop.
10948 // If the header has a unique predecessor outside the loop, it must be
10949 // a block that has exactly one successor that can reach the loop.
10950 if (const Loop *L = LI.getLoopFor(BB))
10951 return {L->getLoopPredecessor(), L->getHeader()};
10952
10953 return {nullptr, BB};
10954}
10955
10956/// SCEV structural equivalence is usually sufficient for testing whether two
10957/// expressions are equal, however for the purposes of looking for a condition
10958/// guarding a loop, it can be useful to be a little more general, since a
10959/// front-end may have replicated the controlling expression.
10960static bool HasSameValue(const SCEV *A, const SCEV *B) {
10961 // Quick check to see if they are the same SCEV.
10962 if (A == B) return true;
10963
10964 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
10965 // Not all instructions that are "identical" compute the same value. For
10966 // instance, two distinct alloca instructions allocating the same type are
10967 // identical and do not read memory; but compute distinct values.
10968 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
10969 };
10970
10971 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
10972 // two different instructions with the same value. Check for this case.
10973 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
10974 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
10975 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
10976 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
10977 if (ComputesEqualValues(AI, BI))
10978 return true;
10979
10980 // Otherwise assume they may have a different value.
10981 return false;
10982}
10983
10984static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
10985 const SCEV *Op0, *Op1;
10986 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
10987 return false;
10988 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10989 LHS = Op1;
10990 return true;
10991 }
10992 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
10993 LHS = Op0;
10994 return true;
10995 }
10996 return false;
10997}
10998
11000 SCEVUse &RHS, unsigned Depth) {
11001 bool Changed = false;
11002 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11003 // '0 != 0'.
11004 auto TrivialCase = [&](bool TriviallyTrue) {
11006 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11007 return true;
11008 };
11009 // If we hit the max recursion limit bail out.
11010 if (Depth >= 3)
11011 return false;
11012
11013 const SCEV *NewLHS, *NewRHS;
11014 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11015 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11016 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11017 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11018
11019 // (X * vscale) pred (Y * vscale) ==> X pred Y
11020 // when both multiples are NSW.
11021 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11022 // when both multiples are NUW.
11023 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11024 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11025 !ICmpInst::isSigned(Pred))) {
11026 LHS = NewLHS;
11027 RHS = NewRHS;
11028 Changed = true;
11029 }
11030 }
11031
11032 // Canonicalize a constant to the right side.
11033 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11034 // Check for both operands constant.
11035 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11036 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11037 return TrivialCase(false);
11038 return TrivialCase(true);
11039 }
11040 // Otherwise swap the operands to put the constant on the right.
11041 std::swap(LHS, RHS);
11043 Changed = true;
11044 }
11045
11046 // (K + A) pred (K + B) --> A pred B
11047 // For equality, no flags are needed.
11048 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11049 {
11050 const SCEVConstant *C = nullptr;
11051 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11052 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11053 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11054 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11055 if (ICmpInst::isEquality(Pred) ||
11056 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11057 RAdd->hasNoSignedWrap()) ||
11058 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11059 RAdd->hasNoUnsignedWrap())) {
11060 LHS = NewLHS;
11061 RHS = NewRHS;
11062 Changed = true;
11063 }
11064 }
11065 }
11066
11067 // (C * A) pred (C * B) --> A pred B
11068 // For equality predicates, both muls must be NUW or both must be NSW
11069 // (either suffices to make multiplication by C injective; C == 0 is
11070 // impossible because SCEV folds 0 * X to 0).
11071 // For signed ordering, C must be positive and both muls must be NSW.
11072 // For unsigned ordering, both muls must be NUW.
11073 {
11074 const SCEVConstant *C = nullptr;
11075 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11076 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11077 const auto *LMul = cast<SCEVMulExpr>(LHS);
11078 const auto *RMul = cast<SCEVMulExpr>(RHS);
11079 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11080 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11081 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11082 (ICmpInst::isSigned(Pred) && BothNSW &&
11083 C->getAPInt().isStrictlyPositive()) ||
11084 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11085 LHS = NewLHS;
11086 RHS = NewRHS;
11087 Changed = true;
11088 }
11089 }
11090 }
11091
11092 // If we're comparing an addrec with a value which is loop-invariant in the
11093 // addrec's loop, put the addrec on the left. Also make a dominance check,
11094 // as both operands could be addrecs loop-invariant in each other's loop.
11095 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11096 const Loop *L = AR->getLoop();
11097 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11098 std::swap(LHS, RHS);
11100 Changed = true;
11101 }
11102 }
11103
11104 // If there's a constant operand, canonicalize comparisons with boundary
11105 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11106 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11107 const APInt &RA = RC->getAPInt();
11108
11109 bool SimplifiedByConstantRange = false;
11110
11111 if (!ICmpInst::isEquality(Pred)) {
11113 if (ExactCR.isFullSet())
11114 return TrivialCase(true);
11115 if (ExactCR.isEmptySet())
11116 return TrivialCase(false);
11117
11118 APInt NewRHS;
11119 CmpInst::Predicate NewPred;
11120 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11121 ICmpInst::isEquality(NewPred)) {
11122 // We were able to convert an inequality to an equality.
11123 Pred = NewPred;
11124 RHS = getConstant(NewRHS);
11125 Changed = SimplifiedByConstantRange = true;
11126 }
11127 }
11128
11129 if (!SimplifiedByConstantRange) {
11130 switch (Pred) {
11131 default:
11132 break;
11133 case ICmpInst::ICMP_EQ:
11134 case ICmpInst::ICMP_NE:
11135 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11136 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11137 Changed = true;
11138 break;
11139
11140 // The "Should have been caught earlier!" messages refer to the fact
11141 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11142 // should have fired on the corresponding cases, and canonicalized the
11143 // check to trivial case.
11144
11145 case ICmpInst::ICMP_UGE:
11146 assert(!RA.isMinValue() && "Should have been caught earlier!");
11147 Pred = ICmpInst::ICMP_UGT;
11148 RHS = getConstant(RA - 1);
11149 Changed = true;
11150 break;
11151 case ICmpInst::ICMP_ULE:
11152 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11153 Pred = ICmpInst::ICMP_ULT;
11154 RHS = getConstant(RA + 1);
11155 Changed = true;
11156 break;
11157 case ICmpInst::ICMP_SGE:
11158 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11159 Pred = ICmpInst::ICMP_SGT;
11160 RHS = getConstant(RA - 1);
11161 Changed = true;
11162 break;
11163 case ICmpInst::ICMP_SLE:
11164 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11165 Pred = ICmpInst::ICMP_SLT;
11166 RHS = getConstant(RA + 1);
11167 Changed = true;
11168 break;
11169 }
11170 }
11171 }
11172
11173 // a /u b == 0 => a < b
11174 // a /u b != 0 => a >= b
11175 if (ICmpInst::isEquality(Pred) && RHS->isZero() &&
11176 match(LHS, m_scev_UDiv(m_SCEV(LHS), m_SCEV(RHS)))) {
11178 Changed = true;
11179 }
11180
11181 // Check for obvious equality.
11182 if (HasSameValue(LHS, RHS)) {
11183 if (ICmpInst::isTrueWhenEqual(Pred))
11184 return TrivialCase(true);
11186 return TrivialCase(false);
11187 }
11188
11189 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11190 // adding or subtracting 1 from one of the operands.
11191 switch (Pred) {
11192 case ICmpInst::ICMP_SLE:
11193 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11194 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11196 Pred = ICmpInst::ICMP_SLT;
11197 Changed = true;
11198 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11199 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11201 Pred = ICmpInst::ICMP_SLT;
11202 Changed = true;
11203 }
11204 break;
11205 case ICmpInst::ICMP_SGE:
11206 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11207 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11209 Pred = ICmpInst::ICMP_SGT;
11210 Changed = true;
11211 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11212 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11214 Pred = ICmpInst::ICMP_SGT;
11215 Changed = true;
11216 }
11217 break;
11218 case ICmpInst::ICMP_ULE:
11219 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11220 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11222 Pred = ICmpInst::ICMP_ULT;
11223 Changed = true;
11224 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11225 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11226 Pred = ICmpInst::ICMP_ULT;
11227 Changed = true;
11228 }
11229 break;
11230 case ICmpInst::ICMP_UGE:
11231 // If RHS is an op we can fold the -1, try that first.
11232 // Otherwise prefer LHS to preserve the nuw flag.
11233 if ((isa<SCEVConstant>(RHS) ||
11235 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11236 !getUnsignedRangeMin(RHS).isMinValue()) {
11237 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11238 Pred = ICmpInst::ICMP_UGT;
11239 Changed = true;
11240 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11241 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11243 Pred = ICmpInst::ICMP_UGT;
11244 Changed = true;
11245 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11246 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11247 Pred = ICmpInst::ICMP_UGT;
11248 Changed = true;
11249 }
11250 break;
11251 default:
11252 break;
11253 }
11254
11255 // TODO: More simplifications are possible here.
11256
11257 // Recursively simplify until we either hit a recursion limit or nothing
11258 // changes.
11259 if (Changed)
11260 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11261
11262 return Changed;
11263}
11264
11266 return getSignedRangeMax(S).isNegative();
11267}
11268
11272
11274 return !getSignedRangeMin(S).isNegative();
11275}
11276
11280
11282 // Query push down for cases where the unsigned range is
11283 // less than sufficient.
11284 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11285 return isKnownNonZero(SExt->getOperand(0));
11286 return getUnsignedRangeMin(S) != 0;
11287}
11288
11290 bool OrNegative) {
11291 auto NonRecursive = [OrNegative](const SCEV *S) {
11292 if (auto *C = dyn_cast<SCEVConstant>(S))
11293 return C->getAPInt().isPowerOf2() ||
11294 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11295
11296 // vscale is a power-of-two.
11297 return isa<SCEVVScale>(S);
11298 };
11299
11300 if (NonRecursive(S))
11301 return true;
11302
11303 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11304 if (!Mul)
11305 return false;
11306 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11307}
11308
11310 const SCEV *S, uint64_t M,
11312 if (M == 0)
11313 return false;
11314 if (M == 1)
11315 return true;
11316
11317 // For a constant, check that "S % M == 0".
11318 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11319 APInt C = Cst->getAPInt();
11320 return C.urem(M) == 0;
11321 }
11322
11323 // Basic tests have failed.
11324 // Check "S % M == 0" at compile time and record runtime Assumptions.
11325 auto *STy = dyn_cast<IntegerType>(S->getType());
11326 const SCEV *SmodM =
11327 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11328 const SCEV *Zero = getZero(STy);
11329
11330 // Check whether "S % M == 0" is known at compile time.
11331 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11332 return true;
11333
11334 // Check whether "S % M != 0" is known at compile time.
11335 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11336 return false;
11337
11338 if (!Predicates)
11339 return false;
11340
11341 // Look through Add and AddRec expressions with nuw to improve the
11342 // precision of added predicates. S is a multiple of M if S starts with a
11343 // multiple of M and at every iteration step S only adds multiples of M.
11346 all_of(S->operands(),
11347 [&](SCEVUse Op) { return isKnownMultipleOf(Op, M, Predicates); }))
11348 return true;
11349
11350 // Similarly, look through Mul with nuw, where any operand being a
11351 // known-multiple is sufficient.
11352 if (auto *Mul = dyn_cast<SCEVMulExpr>(S))
11353 if (Mul->hasNoUnsignedWrap() && any_of(S->operands(), [&](SCEVUse Op) {
11354 return isKnownMultipleOf(Op, M, Predicates);
11355 }))
11356 return true;
11357
11358 // Similarly, look through MinMax, with no wrapping arithmetic to consider.
11359 if (isa<SCEVMinMaxExpr>(S) && all_of(S->operands(), [&](SCEVUse Op) {
11360 return isKnownMultipleOf(Op, M, Predicates);
11361 }))
11362 return true;
11363
11365
11366 // Detect redundant predicates.
11367 for (auto *A : *Predicates)
11368 if (A->implies(P, *this))
11369 return true;
11370
11371 // Only record non-redundant predicates.
11372 Predicates->push_back(P);
11373 return true;
11374}
11375
11377 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11379}
11380
11381std::pair<const SCEV *, const SCEV *>
11383 // Compute SCEV on entry of loop L.
11384 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11385 if (Start == getCouldNotCompute())
11386 return { Start, Start };
11387 // Compute post increment SCEV for loop L.
11388 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11389 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11390 return { Start, PostInc };
11391}
11392
11394 SCEVUse RHS) {
11395 // First collect all loops.
11397 getUsedLoops(LHS, LoopsUsed);
11398 getUsedLoops(RHS, LoopsUsed);
11399
11400 if (LoopsUsed.empty())
11401 return false;
11402
11403 // Domination relationship must be a linear order on collected loops.
11404#ifndef NDEBUG
11405 for (const auto *L1 : LoopsUsed)
11406 for (const auto *L2 : LoopsUsed)
11407 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11408 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11409 "Domination relationship is not a linear order");
11410#endif
11411
11412 const Loop *MDL =
11413 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11414 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11415 });
11416
11417 // Get init and post increment value for LHS.
11418 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11419 // if LHS contains unknown non-invariant SCEV then bail out.
11420 if (SplitLHS.first == getCouldNotCompute())
11421 return false;
11422 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11423 // Get init and post increment value for RHS.
11424 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11425 // if RHS contains unknown non-invariant SCEV then bail out.
11426 if (SplitRHS.first == getCouldNotCompute())
11427 return false;
11428 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11429 // It is possible that init SCEV contains an invariant load but it does
11430 // not dominate MDL and is not available at MDL loop entry, so we should
11431 // check it here.
11432 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11433 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11434 return false;
11435
11436 // It seems backedge guard check is faster than entry one so in some cases
11437 // it can speed up whole estimation by short circuit
11438 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11439 SplitRHS.second) &&
11440 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11441}
11442
11444 SCEVUse RHS) {
11445 // Canonicalize the inputs first.
11446 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11447
11448 return isKnownViaInduction(Pred, LHS, RHS) ||
11449 isKnownPredicateViaSplitting(Pred, LHS, RHS) ||
11450 isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11451}
11452
11454 const SCEV *LHS,
11455 const SCEV *RHS) {
11456 if (isKnownPredicate(Pred, LHS, RHS))
11457 return true;
11459 return false;
11460 return std::nullopt;
11461}
11462
11464 const SCEV *RHS,
11465 const Instruction *CtxI) {
11466 // TODO: Analyze guards and assumes from Context's block.
11467 return isKnownPredicate(Pred, LHS, RHS) ||
11468 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11469}
11470
11471std::optional<bool>
11473 const SCEV *RHS, const Instruction *CtxI) {
11474 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11475 if (KnownWithoutContext)
11476 return KnownWithoutContext;
11477
11478 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11479 return true;
11481 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11482 return false;
11483 return std::nullopt;
11484}
11485
11487 const SCEVAddRecExpr *LHS,
11488 const SCEV *RHS) {
11489 const Loop *L = LHS->getLoop();
11490 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11491 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11492}
11493
11494std::optional<ScalarEvolution::MonotonicPredicateType>
11496 ICmpInst::Predicate Pred) {
11497 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11498
11499#ifndef NDEBUG
11500 // Verify an invariant: inverting the predicate should turn a monotonically
11501 // increasing change to a monotonically decreasing one, and vice versa.
11502 if (Result) {
11503 auto ResultSwapped =
11504 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11505
11506 assert(*ResultSwapped != *Result &&
11507 "monotonicity should flip as we flip the predicate");
11508 }
11509#endif
11510
11511 return Result;
11512}
11513
11514std::optional<ScalarEvolution::MonotonicPredicateType>
11515ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11516 ICmpInst::Predicate Pred) {
11517 // A zero step value for LHS means the induction variable is essentially a
11518 // loop invariant value. We don't really depend on the predicate actually
11519 // flipping from false to true (for increasing predicates, and the other way
11520 // around for decreasing predicates), all we care about is that *if* the
11521 // predicate changes then it only changes from false to true.
11522 //
11523 // A zero step value in itself is not very useful, but there may be places
11524 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11525 // as general as possible.
11526
11527 // Only handle LE/LT/GE/GT predicates.
11528 if (!ICmpInst::isRelational(Pred))
11529 return std::nullopt;
11530
11531 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11532 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11533 "Should be greater or less!");
11534
11535 // Check that AR does not wrap.
11536 if (ICmpInst::isUnsigned(Pred)) {
11537 if (!LHS->hasNoUnsignedWrap())
11538 return std::nullopt;
11540 }
11541 assert(ICmpInst::isSigned(Pred) &&
11542 "Relational predicate is either signed or unsigned!");
11543 if (!LHS->hasNoSignedWrap())
11544 return std::nullopt;
11545
11546 const SCEV *Step = LHS->getStepRecurrence(*this);
11547
11548 if (isKnownNonNegative(Step))
11550
11551 if (isKnownNonPositive(Step))
11553
11554 return std::nullopt;
11555}
11556
11557std::optional<ScalarEvolution::LoopInvariantPredicate>
11559 const SCEV *RHS, const Loop *L,
11560 const Instruction *CtxI) {
11561 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11562 if (!isLoopInvariant(RHS, L)) {
11563 if (!isLoopInvariant(LHS, L))
11564 return std::nullopt;
11565
11566 std::swap(LHS, RHS);
11568 }
11569
11570 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11571 if (!ArLHS || ArLHS->getLoop() != L)
11572 return std::nullopt;
11573
11574 // Even if both are valid, we need to consistently choose the unsigned or the
11575 // signed predicate for the monotonicity and backedge checks below, not
11576 // mixtures of both. For now, prefer the unsigned predicate.
11577 Pred = Pred.dropSameSign();
11578 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11579 if (!MonotonicType)
11580 return std::nullopt;
11581 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11582 // true as the loop iterates, and the backedge is control dependent on
11583 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11584 //
11585 // * if the predicate was false in the first iteration then the predicate
11586 // is never evaluated again, since the loop exits without taking the
11587 // backedge.
11588 // * if the predicate was true in the first iteration then it will
11589 // continue to be true for all future iterations since it is
11590 // monotonically increasing.
11591 //
11592 // For both the above possibilities, we can replace the loop varying
11593 // predicate with its value on the first iteration of the loop (which is
11594 // loop invariant).
11595 //
11596 // A similar reasoning applies for a monotonically decreasing predicate, by
11597 // replacing true with false and false with true in the above two bullets.
11599 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11600
11601 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11603 RHS);
11604
11605 if (!CtxI)
11606 return std::nullopt;
11607 // Try to prove via context.
11608 // TODO: Support other cases.
11609 switch (Pred) {
11610 default:
11611 break;
11612 case ICmpInst::ICMP_ULE:
11613 case ICmpInst::ICMP_ULT: {
11614 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11615 // Given preconditions
11616 // (1) ArLHS does not cross the border of positive and negative parts of
11617 // range because of:
11618 // - Positive step; (TODO: lift this limitation)
11619 // - nuw - does not cross zero boundary;
11620 // - nsw - does not cross SINT_MAX boundary;
11621 // (2) ArLHS <s RHS
11622 // (3) RHS >=s 0
11623 // we can replace the loop variant ArLHS <u RHS condition with loop
11624 // invariant Start(ArLHS) <u RHS.
11625 //
11626 // Because of (1) there are two options:
11627 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11628 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11629 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11630 // Because of (2) ArLHS <u RHS is trivially true.
11631 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11632 // We can strengthen this to Start(ArLHS) <u RHS.
11633 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11634 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11635 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11636 isKnownNonNegative(RHS) &&
11637 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11639 RHS);
11640 }
11641 }
11642
11643 return std::nullopt;
11644}
11645
11646std::optional<ScalarEvolution::LoopInvariantPredicate>
11648 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11649 const Instruction *CtxI, const SCEV *MaxIter) {
11651 Pred, LHS, RHS, L, CtxI, MaxIter))
11652 return LIP;
11653 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11654 // Number of iterations expressed as UMIN isn't always great for expressing
11655 // the value on the last iteration. If the straightforward approach didn't
11656 // work, try the following trick: if the a predicate is invariant for X, it
11657 // is also invariant for umin(X, ...). So try to find something that works
11658 // among subexpressions of MaxIter expressed as umin.
11659 for (SCEVUse Op : UMin->operands())
11661 Pred, LHS, RHS, L, CtxI, Op))
11662 return LIP;
11663 return std::nullopt;
11664}
11665
11666std::optional<ScalarEvolution::LoopInvariantPredicate>
11668 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11669 const Instruction *CtxI, const SCEV *MaxIter) {
11670 // Try to prove the following set of facts:
11671 // - The predicate is monotonic in the iteration space.
11672 // - If the check does not fail on the 1st iteration:
11673 // - No overflow will happen during first MaxIter iterations;
11674 // - It will not fail on the MaxIter'th iteration.
11675 // If the check does fail on the 1st iteration, we leave the loop and no
11676 // other checks matter.
11677
11678 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11679 if (!isLoopInvariant(RHS, L)) {
11680 if (!isLoopInvariant(LHS, L))
11681 return std::nullopt;
11682
11683 std::swap(LHS, RHS);
11685 }
11686
11687 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11688 if (!AR || AR->getLoop() != L)
11689 return std::nullopt;
11690
11691 // Even if both are valid, we need to consistently chose the unsigned or the
11692 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11693 // predicate.
11694 Pred = Pred.dropSameSign();
11695
11696 // The predicate must be relational (i.e. <, <=, >=, >).
11697 if (!ICmpInst::isRelational(Pred))
11698 return std::nullopt;
11699
11700 // TODO: Support steps other than +/- 1.
11701 const SCEV *Step = AR->getStepRecurrence(*this);
11702 auto *One = getOne(Step->getType());
11703 auto *MinusOne = getNegativeSCEV(One);
11704 if (Step != One && Step != MinusOne)
11705 return std::nullopt;
11706
11707 // Type mismatch here means that MaxIter is potentially larger than max
11708 // unsigned value in start type, which mean we cannot prove no wrap for the
11709 // indvar.
11710 if (AR->getType() != MaxIter->getType())
11711 return std::nullopt;
11712
11713 // Value of IV on suggested last iteration.
11714 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11715 // Does it still meet the requirement?
11716 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11717 return std::nullopt;
11718 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11719 // not exceed max unsigned value of this type), this effectively proves
11720 // that there is no wrap during the iteration. To prove that there is no
11721 // signed/unsigned wrap, we need to check that
11722 // Start <= Last for step = 1 or Start >= Last for step = -1.
11723 ICmpInst::Predicate NoOverflowPred =
11725 if (Step == MinusOne)
11726 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11727 const SCEV *Start = AR->getStart();
11728 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11729 return std::nullopt;
11730
11731 // Everything is fine.
11732 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11733}
11734
11735bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11736 SCEVUse LHS,
11737 SCEVUse RHS) {
11738 if (HasSameValue(LHS, RHS))
11739 return ICmpInst::isTrueWhenEqual(Pred);
11740
11741 auto CheckRange = [&](bool IsSigned) {
11742 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11743 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11744 return RangeLHS.icmp(Pred, RangeRHS);
11745 };
11746
11747 // The check at the top of the function catches the case where the values are
11748 // known to be equal.
11749 if (Pred == CmpInst::ICMP_EQ)
11750 return false;
11751
11752 if (Pred == CmpInst::ICMP_NE) {
11753 if (CheckRange(true) || CheckRange(false))
11754 return true;
11755 auto *Diff = getMinusSCEV(LHS, RHS);
11756 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11757 }
11758
11759 return CheckRange(CmpInst::isSigned(Pred));
11760}
11761
11762bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11764 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11765 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11766 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11767 // OutC1 and OutC2.
11768 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11769 APInt &OutC2, SCEVFlags ExpectedFlags) {
11770 SCEVUse XNonConstOp, XConstOp;
11771 SCEVUse YNonConstOp, YConstOp;
11772 SCEVFlags XFlagsPresent;
11773 SCEVFlags YFlagsPresent;
11774
11775 // Use nullptr for 0, to avoid creating a zero SCEV.
11776 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11777 XConstOp = nullptr;
11778 XNonConstOp = X;
11779 XFlagsPresent = ExpectedFlags;
11780 }
11781 if (XConstOp && !isa<SCEVConstant>(XConstOp))
11782 return false;
11783
11784 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11785 YConstOp = nullptr;
11786 YNonConstOp = Y;
11787 YFlagsPresent = ExpectedFlags;
11788 }
11789
11790 if (YNonConstOp != XNonConstOp)
11791 return false;
11792
11793 if (YConstOp && !isa<SCEVConstant>(YConstOp))
11794 return false;
11795
11796 // When matching ADDs with NUW flags (and unsigned predicates), only the
11797 // second ADD (with the larger constant) requires NUW.
11798 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11799 return false;
11801 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11802 return false;
11803 }
11804
11805 OutC1 = XConstOp ? cast<SCEVConstant>(XConstOp)->getAPInt()
11806 : APInt::getZero(getTypeSizeInBits(X->getType()));
11807 OutC2 = YConstOp ? cast<SCEVConstant>(YConstOp)->getAPInt()
11808 : APInt::getZero(getTypeSizeInBits(Y->getType()));
11809
11810 return true;
11811 };
11812
11813 APInt C1;
11814 APInt C2;
11815
11816 switch (Pred) {
11817 default:
11818 break;
11819
11820 case ICmpInst::ICMP_SGE:
11821 std::swap(LHS, RHS);
11822 [[fallthrough]];
11823 case ICmpInst::ICMP_SLE:
11824 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11825 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11826 return true;
11827
11828 break;
11829
11830 case ICmpInst::ICMP_SGT:
11831 std::swap(LHS, RHS);
11832 [[fallthrough]];
11833 case ICmpInst::ICMP_SLT:
11834 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11835 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11836 return true;
11837
11838 break;
11839
11840 case ICmpInst::ICMP_UGE:
11841 std::swap(LHS, RHS);
11842 [[fallthrough]];
11843 case ICmpInst::ICMP_ULE:
11844 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11845 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11846 return true;
11847
11848 break;
11849
11850 case ICmpInst::ICMP_UGT:
11851 std::swap(LHS, RHS);
11852 [[fallthrough]];
11853 case ICmpInst::ICMP_ULT:
11854 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11855 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11856 return true;
11857 break;
11858 }
11859
11860 return false;
11861}
11862
11863bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11865 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11866 return false;
11867
11868 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11869 // the stack can result in exponential time complexity.
11870 SaveAndRestore Restore(ProvingSplitPredicate, true);
11871
11872 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11873 //
11874 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11875 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11876 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11877 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11878 // use isKnownPredicate later if needed.
11879 return isKnownNonNegative(RHS) &&
11882}
11883
11884bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11885 const SCEV *LHS, const SCEV *RHS) {
11886 // No need to even try if we know the module has no guards.
11887 if (!HasGuards)
11888 return false;
11889
11890 return any_of(*BB, [&](const Instruction &I) {
11891 using namespace llvm::PatternMatch;
11892
11893 Value *Condition;
11895 m_Value(Condition))) &&
11896 isImpliedCond(Pred, LHS, RHS, Condition, false);
11897 });
11898}
11899
11900/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11901/// protected by a conditional between LHS and RHS. This is used to
11902/// to eliminate casts.
11904 CmpPredicate Pred,
11905 const SCEV *LHS,
11906 const SCEV *RHS) {
11907 // Interpret a null as meaning no loop, where there is obviously no guard
11908 // (interprocedural conditions notwithstanding). Do not bother about
11909 // unreachable loops.
11910 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11911 return true;
11912
11913 if (VerifyIR)
11914 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11915 "This cannot be done on broken IR!");
11916
11917
11918 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11919 return true;
11920
11921 BasicBlock *Latch = L->getLoopLatch();
11922 if (!Latch)
11923 return false;
11924
11925 CondBrInst *LoopContinuePredicate =
11927 if (LoopContinuePredicate &&
11928 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
11929 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
11930 return true;
11931
11932 // We don't want more than one activation of the following loops on the stack
11933 // -- that can lead to O(n!) time complexity.
11934 if (WalkingBEDominatingConds)
11935 return false;
11936
11937 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
11938
11939 // See if we can exploit a trip count to prove the predicate.
11940 const auto &BETakenInfo = getBackedgeTakenInfo(L);
11941 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
11942 if (LatchBECount != getCouldNotCompute()) {
11943 // We know that Latch branches back to the loop header exactly
11944 // LatchBECount times. This means the backdege condition at Latch is
11945 // equivalent to "{0,+,1} u< LatchBECount".
11946 Type *Ty = LatchBECount->getType();
11947 auto NoWrapFlags = SCEVFlags(SCEV::FlagNUW | SCEV::FlagNW);
11948 const SCEV *LoopCounter =
11949 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
11950 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
11951 LatchBECount))
11952 return true;
11953 }
11954
11955 // Check conditions due to any @llvm.assume intrinsics.
11956 for (auto &AssumeVH : AC.assumptions()) {
11957 if (!AssumeVH)
11958 continue;
11959 auto *CI = cast<CallInst>(AssumeVH);
11960 if (!DT.dominates(CI, Latch->getTerminator()))
11961 continue;
11962
11963 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
11964 return true;
11965 }
11966
11967 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
11968 return true;
11969
11970 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
11971 DTN != HeaderDTN; DTN = DTN->getIDom()) {
11972 assert(DTN && "should reach the loop header before reaching the root!");
11973
11974 BasicBlock *BB = DTN->getBlock();
11975 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
11976 return true;
11977
11978 BasicBlock *PBB = BB->getSinglePredecessor();
11979 if (!PBB)
11980 continue;
11981
11983 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
11984 continue;
11985
11986 // If we have an edge `E` within the loop body that dominates the only
11987 // latch, the condition guarding `E` also guards the backedge. This
11988 // reasoning works only for loops with a single latch.
11989 // We're constructively (and conservatively) enumerating edges within the
11990 // loop body that dominate the latch. The dominator tree better agree
11991 // with us on this:
11992 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
11993 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
11994 BB != ContBr->getSuccessor(0)))
11995 return true;
11996 }
11997
11998 return false;
11999}
12000
12002 CmpPredicate Pred,
12003 const SCEV *LHS,
12004 const SCEV *RHS) {
12005 // Do not bother proving facts for unreachable code.
12006 if (!DT.isReachableFromEntry(BB))
12007 return true;
12008 if (VerifyIR)
12009 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12010 "This cannot be done on broken IR!");
12011
12012 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12013 // the facts (a >= b && a != b) separately. A typical situation is when the
12014 // non-strict comparison is known from ranges and non-equality is known from
12015 // dominating predicates. If we are proving strict comparison, we always try
12016 // to prove non-equality and non-strict comparison separately.
12017 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12018 const bool ProvingStrictComparison =
12019 Pred != NonStrictPredicate.dropSameSign();
12020 bool ProvedNonStrictComparison = false;
12021 bool ProvedNonEquality = false;
12022
12023 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12024 if (!ProvedNonStrictComparison)
12025 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12026 if (!ProvedNonEquality)
12027 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12028 if (ProvedNonStrictComparison && ProvedNonEquality)
12029 return true;
12030 return false;
12031 };
12032
12033 if (ProvingStrictComparison) {
12034 auto ProofFn = [&](CmpPredicate P) {
12035 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12036 };
12037 if (SplitAndProve(ProofFn))
12038 return true;
12039 }
12040
12041 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12042 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12043 const Instruction *CtxI = &BB->front();
12044 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12045 return true;
12046 if (ProvingStrictComparison) {
12047 auto ProofFn = [&](CmpPredicate P) {
12048 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12049 };
12050 if (SplitAndProve(ProofFn))
12051 return true;
12052 }
12053 return false;
12054 };
12055
12056 // Starting at the block's predecessor, climb up the predecessor chain, as long
12057 // as there are predecessors that can be found that have unique successors
12058 // leading to the original block.
12059 const Loop *ContainingLoop = LI.getLoopFor(BB);
12060 const BasicBlock *PredBB;
12061 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12062 PredBB = ContainingLoop->getLoopPredecessor();
12063 else
12064 PredBB = BB->getSinglePredecessor();
12065 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12066 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12067 const CondBrInst *BlockEntryPredicate =
12068 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12069 if (!BlockEntryPredicate)
12070 continue;
12071
12072 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12073 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12074 return true;
12075 }
12076
12077 // Check conditions due to any @llvm.assume intrinsics.
12078 for (auto &AssumeVH : AC.assumptions()) {
12079 if (!AssumeVH)
12080 continue;
12081 auto *CI = cast<CallInst>(AssumeVH);
12082 if (!DT.dominates(CI, BB))
12083 continue;
12084
12085 if (ProveViaCond(CI->getArgOperand(0), false))
12086 return true;
12087 }
12088
12089 // Check conditions due to any @llvm.experimental.guard intrinsics.
12090 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12091 F.getParent(), Intrinsic::experimental_guard);
12092 if (GuardDecl)
12093 for (const auto *GU : GuardDecl->users())
12094 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12095 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12096 if (ProveViaCond(Guard->getArgOperand(0), false))
12097 return true;
12098 return false;
12099}
12100
12102 const SCEV *LHS,
12103 const SCEV *RHS) {
12104 // Interpret a null as meaning no loop, where there is obviously no guard
12105 // (interprocedural conditions notwithstanding).
12106 if (!L)
12107 return false;
12108
12109 // Both LHS and RHS must be available at loop entry.
12111 "LHS is not available at Loop Entry");
12113 "RHS is not available at Loop Entry");
12114
12115 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12116 return true;
12117
12118 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12119}
12120
12121bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12122 const SCEV *RHS,
12123 const Value *FoundCondValue, bool Inverse,
12124 const Instruction *CtxI) {
12125 // False conditions implies anything. Do not bother analyzing it further.
12126 if (FoundCondValue ==
12127 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12128 return true;
12129
12130 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12131 return false;
12132
12133 llvm::scope_exit ClearOnExit(
12134 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12135
12136 // Recursively handle And and Or conditions.
12137 const Value *Op0, *Op1;
12138 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12139 if (!Inverse)
12140 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12141 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12142 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12143 if (Inverse)
12144 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12145 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12146 }
12147
12148 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12149 if (!ICI) return false;
12150
12151 // Now that we found a conditional branch that dominates the loop or controls
12152 // the loop latch. Check to see if it is the comparison we are looking for.
12153 CmpPredicate FoundPred;
12154 if (Inverse)
12155 FoundPred = ICI->getInverseCmpPredicate();
12156 else
12157 FoundPred = ICI->getCmpPredicate();
12158
12159 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12160 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12161
12162 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12163}
12164
12165bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12166 const SCEV *RHS, CmpPredicate FoundPred,
12167 const SCEV *FoundLHS, const SCEV *FoundRHS,
12168 const Instruction *CtxI) {
12169 // Balance the types.
12170 if (getTypeSizeInBits(LHS->getType()) <
12171 getTypeSizeInBits(FoundLHS->getType())) {
12172 // For unsigned and equality predicates, try to prove that both found
12173 // operands fit into narrow unsigned range. If so, try to prove facts in
12174 // narrow types.
12175 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12176 !FoundRHS->getType()->isPointerTy()) {
12177 auto *NarrowType = LHS->getType();
12178 auto *WideType = FoundLHS->getType();
12179 auto BitWidth = getTypeSizeInBits(NarrowType);
12180 const SCEV *MaxValue = getZeroExtendExpr(
12182 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12183 MaxValue) &&
12184 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12185 MaxValue)) {
12186 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12187 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12188 // We cannot preserve samesign after truncation.
12189 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12190 TruncFoundLHS, TruncFoundRHS, CtxI))
12191 return true;
12192 }
12193 }
12194
12195 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12196 return false;
12197 if (CmpInst::isSigned(Pred)) {
12198 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12199 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12200 } else {
12201 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12202 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12203 }
12204 } else if (getTypeSizeInBits(LHS->getType()) >
12205 getTypeSizeInBits(FoundLHS->getType())) {
12206 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12207 return false;
12208 if (CmpInst::isSigned(FoundPred)) {
12209 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12210 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12211 } else {
12212 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12213 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12214 }
12215 }
12216 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12217 FoundRHS, CtxI);
12218}
12219
12220bool ScalarEvolution::isImpliedCondBalancedTypes(
12221 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12222 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12224 getTypeSizeInBits(FoundLHS->getType()) &&
12225 "Types should be balanced!");
12226 // Canonicalize the query to match the way instcombine will have
12227 // canonicalized the comparison.
12228 if (SimplifyICmpOperands(Pred, LHS, RHS))
12229 if (LHS == RHS)
12230 return CmpInst::isTrueWhenEqual(Pred);
12231 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12232 if (FoundLHS == FoundRHS)
12233 return CmpInst::isFalseWhenEqual(FoundPred);
12234
12235 // Check to see if we can make the LHS or RHS match.
12236 if (LHS == FoundRHS || RHS == FoundLHS) {
12237 if (isa<SCEVConstant>(RHS)) {
12238 std::swap(FoundLHS, FoundRHS);
12239 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12240 } else {
12241 std::swap(LHS, RHS);
12243 }
12244 }
12245
12246 // Check whether the found predicate is the same as the desired predicate.
12247 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12248 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12249
12250 // Check whether swapping the found predicate makes it the same as the
12251 // desired predicate.
12252 if (auto P = CmpPredicate::getMatching(
12253 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12254 // We can write the implication
12255 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12256 // using one of the following ways:
12257 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12258 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12259 // Both require swapping the operands of one condition. Don't do this if it
12260 // would break canonical constant/addrec ordering.
12262 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12263 LHS, FoundLHS, FoundRHS, CtxI);
12264 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12265 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12266
12267 return false;
12268 }
12269
12270 // Try the query as is and with its operands swapped. E.g. "x >s -1" is
12271 // tried as "-1 <s x" too, to match the found condition "x <u y".
12272 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12274 return CmpInst::isRelational(P2) &&
12276 };
12277 if (IsSignFlippedPredicate(Pred, FoundPred) &&
12278 isImpliedCondViaSignFlippedPred(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12279 return true;
12280 CmpPredicate SwappedPred = ICmpInst::getSwappedCmpPredicate(Pred);
12281 if (IsSignFlippedPredicate(SwappedPred, FoundPred) &&
12282 isImpliedCondViaSignFlippedPred(SwappedPred, RHS, LHS, FoundLHS, FoundRHS,
12283 CtxI))
12284 return true;
12285
12286 // Check if we can make progress by sharpening ranges.
12287 if (FoundPred == ICmpInst::ICMP_NE &&
12288 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12289
12290 const SCEVConstant *C = nullptr;
12291 const SCEV *V = nullptr;
12292
12293 if (isa<SCEVConstant>(FoundLHS)) {
12294 C = cast<SCEVConstant>(FoundLHS);
12295 V = FoundRHS;
12296 } else {
12297 C = cast<SCEVConstant>(FoundRHS);
12298 V = FoundLHS;
12299 }
12300
12301 // The guarding predicate tells us that C != V. If the known range
12302 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12303 // range we consider has to correspond to same signedness as the
12304 // predicate we're interested in folding.
12305
12306 APInt Min = ICmpInst::isSigned(Pred) ?
12308
12309 if (Min == C->getAPInt()) {
12310 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12311 // This is true even if (Min + 1) wraps around -- in case of
12312 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12313
12314 APInt SharperMin = Min + 1;
12315
12316 switch (Pred) {
12317 case ICmpInst::ICMP_SGE:
12318 case ICmpInst::ICMP_UGE:
12319 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12320 // RHS, we're done.
12321 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12322 CtxI))
12323 return true;
12324 [[fallthrough]];
12325
12326 case ICmpInst::ICMP_SGT:
12327 case ICmpInst::ICMP_UGT:
12328 // We know from the range information that (V `Pred` Min ||
12329 // V == Min). We know from the guarding condition that !(V
12330 // == Min). This gives us
12331 //
12332 // V `Pred` Min || V == Min && !(V == Min)
12333 // => V `Pred` Min
12334 //
12335 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12336
12337 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12338 return true;
12339 break;
12340
12341 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12342 case ICmpInst::ICMP_SLE:
12343 case ICmpInst::ICMP_ULE:
12344 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12345 LHS, V, getConstant(SharperMin), CtxI))
12346 return true;
12347 [[fallthrough]];
12348
12349 case ICmpInst::ICMP_SLT:
12350 case ICmpInst::ICMP_ULT:
12351 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12352 LHS, V, getConstant(Min), CtxI))
12353 return true;
12354 break;
12355
12356 default:
12357 // No change
12358 break;
12359 }
12360 }
12361 }
12362
12363 // Check whether the actual condition is beyond sufficient.
12364 if (FoundPred == ICmpInst::ICMP_EQ)
12365 if (ICmpInst::isTrueWhenEqual(Pred))
12366 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12367 return true;
12368 if (Pred == ICmpInst::ICMP_NE)
12369 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12370 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12371 return true;
12372
12373 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12374 return true;
12375
12376 // Otherwise assume the worst.
12377 return false;
12378}
12379
12380bool ScalarEvolution::isImpliedCondViaSignFlippedPred(
12381 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12382 const SCEV *FoundRHS, const Instruction *CtxI) {
12383 CmpPredicate FoundPred = ICmpInst::getFlippedSignednessPredicate(Pred);
12384 // Unsigned comparison is the same as signed comparison when both the
12385 // operands are non-negative or negative.
12386 if (haveSameSign(FoundLHS, FoundRHS) &&
12387 isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12388 return true;
12389 // Canonicalize both conditions to "le/lt".
12390 if (ICmpInst::isGT(Pred) || ICmpInst::isGE(Pred)) {
12392 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12393 std::swap(LHS, RHS);
12394 std::swap(FoundLHS, FoundRHS);
12395 }
12396 assert((ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred)) && "Must be!");
12397 assert((ICmpInst::isLT(FoundPred) || ICmpInst::isLE(FoundPred)) &&
12398 "Must be!");
12399 if (ICmpInst::isSigned(Pred)) {
12400 // Use implication:
12401 // x <u y && y <=u 2^(n-1) --> x >=s 0,
12402 // x <=u y && y <u 2^(n-1) --> x >=s 0,
12403 // where n is the bit width of x and y.
12404 // In both cases x <u 2^(n-1), so x >=s 0.
12405 // y <=u 2^(n-1) means y >=s 0 or y == INT_MIN.
12406 // If the implication's left part holds, try proving the query from x >=s
12407 // 0.
12408 Type *Ty = FoundLHS->getType();
12409 unsigned BitWidth = getTypeSizeInBits(Ty);
12410 const SCEV *SignedMin = getConstant(APInt::getSignedMinValue(BitWidth));
12411 CmpPredicate BoundPred =
12413 if (isKnownViaNonRecursiveReasoning(BoundPred, FoundRHS, SignedMin)) {
12414 // x >=s 0, written as 0 <=s x, or as -1 <s x to match a strict query.
12415 const SCEV *Bound = ICmpInst::isLE(Pred) ? getZero(Ty) : getMinusOne(Ty);
12416 if (isImpliedCondOperands(Pred, LHS, RHS, Bound, FoundLHS, CtxI))
12417 return true;
12418 }
12419 }
12421 // Use implication:
12422 // x <u y && y >=s 0 --> x <s y.
12423 // If we can prove the left part, the right part is also proven.
12424 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12425 return true;
12426 }
12428 // Use implication:
12429 // x <s y && y <s 0 --> x <u y.
12430 // If we can prove the left part, the right part is also proven.
12431 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
12432 return true;
12433 }
12434 return false;
12435}
12436
12437bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12438 SCEVFlags &Flags) {
12439 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12440 return false;
12441
12442 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12443 return true;
12444}
12445
12446std::optional<APInt>
12448 // We avoid subtracting expressions here because this function is usually
12449 // fairly deep in the call stack (i.e. is called many times).
12450
12451 unsigned BW = getTypeSizeInBits(More->getType());
12452 APInt Diff(BW, 0);
12453 APInt DiffMul(BW, 1);
12454 // Try various simplifications to reduce the difference to a constant. Limit
12455 // the number of allowed simplifications to keep compile-time low.
12456 for (unsigned I = 0; I < 8; ++I) {
12457 if (More == Less)
12458 return Diff;
12459
12460 // Reduce addrecs with identical steps to their start value.
12462 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12463 const auto *MAR = cast<SCEVAddRecExpr>(More);
12464
12465 if (LAR->getLoop() != MAR->getLoop())
12466 return std::nullopt;
12467
12468 // We look at affine expressions only; not for correctness but to keep
12469 // getStepRecurrence cheap.
12470 if (!LAR->isAffine() || !MAR->isAffine())
12471 return std::nullopt;
12472
12473 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12474 return std::nullopt;
12475
12476 Less = LAR->getStart();
12477 More = MAR->getStart();
12478 continue;
12479 }
12480
12481 // Try to match a common constant multiply.
12482 auto MatchConstMul =
12483 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12484 const APInt *C;
12485 const SCEV *Op;
12486 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12487 return {{Op, *C}};
12488 return std::nullopt;
12489 };
12490 if (auto MatchedMore = MatchConstMul(More)) {
12491 if (auto MatchedLess = MatchConstMul(Less)) {
12492 if (MatchedMore->second == MatchedLess->second) {
12493 More = MatchedMore->first;
12494 Less = MatchedLess->first;
12495 DiffMul *= MatchedMore->second;
12496 continue;
12497 }
12498 }
12499 }
12500
12501 // Try to cancel out common factors in two add expressions.
12503 auto Add = [&](const SCEV *S, int Mul) {
12504 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12505 if (Mul == 1) {
12506 Diff += C->getAPInt() * DiffMul;
12507 } else {
12508 assert(Mul == -1);
12509 Diff -= C->getAPInt() * DiffMul;
12510 }
12511 } else
12512 Multiplicity[S] += Mul;
12513 };
12514 auto Decompose = [&](const SCEV *S, int Mul) {
12515 if (isa<SCEVAddExpr>(S)) {
12516 for (const SCEV *Op : S->operands())
12517 Add(Op, Mul);
12518 } else
12519 Add(S, Mul);
12520 };
12521 Decompose(More, 1);
12522 Decompose(Less, -1);
12523
12524 // Check whether all the non-constants cancel out, or reduce to new
12525 // More/Less values.
12526 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12527 for (const auto &[S, Mul] : Multiplicity) {
12528 if (Mul == 0)
12529 continue;
12530 if (Mul == 1) {
12531 if (NewMore)
12532 return std::nullopt;
12533 NewMore = S;
12534 } else if (Mul == -1) {
12535 if (NewLess)
12536 return std::nullopt;
12537 NewLess = S;
12538 } else
12539 return std::nullopt;
12540 }
12541
12542 // Values stayed the same, no point in trying further.
12543 if (NewMore == More || NewLess == Less)
12544 return std::nullopt;
12545
12546 More = NewMore;
12547 Less = NewLess;
12548
12549 // Reduced to constant.
12550 if (!More && !Less)
12551 return Diff;
12552
12553 // Left with variable on only one side, bail out.
12554 if (!More || !Less)
12555 return std::nullopt;
12556 }
12557
12558 // Did not reduce to constant.
12559 return std::nullopt;
12560}
12561
12562bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12563 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12564 const SCEV *FoundRHS, const Instruction *CtxI) {
12565 // Try to recognize the following pattern:
12566 //
12567 // FoundRHS = ...
12568 // ...
12569 // loop:
12570 // FoundLHS = {Start,+,W}
12571 // context_bb: // Basic block from the same loop
12572 // known(Pred, FoundLHS, FoundRHS)
12573 //
12574 // If some predicate is known in the context of a loop, it is also known on
12575 // each iteration of this loop, including the first iteration. Therefore, in
12576 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12577 // prove the original pred using this fact.
12578 if (!CtxI)
12579 return false;
12580 const BasicBlock *ContextBB = CtxI->getParent();
12581 // Make sure AR varies in the context block.
12582 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
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(FoundRHS, AR->getLoop()))
12590 return false;
12591 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12592 }
12593
12594 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12595 const Loop *L = AR->getLoop();
12596 const auto *Latch = L->getLoopLatch();
12597 // Make sure that context belongs to the loop and executes on 1st iteration
12598 // (if it ever executes at all).
12599 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12600 return false;
12601 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12602 return false;
12603 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12604 }
12605
12606 return false;
12607}
12608
12609bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12610 const SCEV *LHS,
12611 const SCEV *RHS,
12612 const SCEV *FoundLHS,
12613 const SCEV *FoundRHS) {
12614 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12615 return false;
12616
12617 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12618 if (!AddRecLHS)
12619 return false;
12620
12621 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12622 if (!AddRecFoundLHS)
12623 return false;
12624
12625 // We'd like to let SCEV reason about control dependencies, so we constrain
12626 // both the inequalities to be about add recurrences on the same loop. This
12627 // way we can use isLoopEntryGuardedByCond later.
12628
12629 const Loop *L = AddRecFoundLHS->getLoop();
12630 if (L != AddRecLHS->getLoop())
12631 return false;
12632
12633 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12634 //
12635 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12636 // ... (2)
12637 //
12638 // Informal proof for (2), assuming (1) [*]:
12639 //
12640 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12641 //
12642 // Then
12643 //
12644 // FoundLHS s< FoundRHS s< INT_MIN - C
12645 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12646 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12647 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12648 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12649 // <=> FoundLHS + C s< FoundRHS + C
12650 //
12651 // [*]: (1) can be proved by ruling out overflow.
12652 //
12653 // [**]: This can be proved by analyzing all the four possibilities:
12654 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12655 // (A s>= 0, B s>= 0).
12656 //
12657 // Note:
12658 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12659 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12660 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12661 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12662 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12663 // C)".
12664
12665 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12666 if (!LDiff)
12667 return false;
12668 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12669 if (!RDiff || *LDiff != *RDiff)
12670 return false;
12671
12672 if (LDiff->isMinValue())
12673 return true;
12674
12675 APInt FoundRHSLimit;
12676
12677 if (Pred == CmpInst::ICMP_ULT) {
12678 FoundRHSLimit = -(*RDiff);
12679 } else {
12680 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12681 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12682 }
12683
12684 // Try to prove (1) or (2), as needed.
12685 return isAvailableAtLoopEntry(FoundRHS, L) &&
12686 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12687 getConstant(FoundRHSLimit));
12688}
12689
12690bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12691 const SCEV *RHS, const SCEV *FoundLHS,
12692 const SCEV *FoundRHS, unsigned Depth) {
12693 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12694
12695 llvm::scope_exit ClearOnExit([&]() {
12696 if (LPhi) {
12697 bool Erased = PendingMerges.erase(LPhi);
12698 assert(Erased && "Failed to erase LPhi!");
12699 (void)Erased;
12700 }
12701 if (RPhi) {
12702 bool Erased = PendingMerges.erase(RPhi);
12703 assert(Erased && "Failed to erase RPhi!");
12704 (void)Erased;
12705 }
12706 });
12707
12708 // Find respective Phis and check that they are not being pending.
12709 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12710 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12711 if (!PendingMerges.insert(Phi).second)
12712 return false;
12713 LPhi = Phi;
12714 }
12715 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12716 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12717 // If we detect a loop of Phi nodes being processed by this method, for
12718 // example:
12719 //
12720 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12721 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12722 //
12723 // we don't want to deal with a case that complex, so return conservative
12724 // answer false.
12725 if (!PendingMerges.insert(Phi).second)
12726 return false;
12727 RPhi = Phi;
12728 }
12729
12730 // If none of LHS, RHS is a Phi, nothing to do here.
12731 if (!LPhi && !RPhi)
12732 return false;
12733
12734 // If there is a SCEVUnknown Phi we are interested in, make it left.
12735 if (!LPhi) {
12736 std::swap(LHS, RHS);
12737 std::swap(FoundLHS, FoundRHS);
12738 std::swap(LPhi, RPhi);
12740 }
12741
12742 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12743 const BasicBlock *LBB = LPhi->getParent();
12744 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12745
12746 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12747 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12748 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12749 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12750 };
12751
12752 if (RPhi && RPhi->getParent() == LBB) {
12753 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12754 // If we compare two Phis from the same block, and for each entry block
12755 // the predicate is true for incoming values from this block, then the
12756 // predicate is also true for the Phis.
12757 for (const BasicBlock *IncBB : predecessors(LBB)) {
12758 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12759 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12760 if (!ProvedEasily(L, R))
12761 return false;
12762 }
12763 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12764 // Case two: RHS is also a Phi from the same basic block, and it is an
12765 // AddRec. It means that there is a loop which has both AddRec and Unknown
12766 // PHIs, for it we can compare incoming values of AddRec from above the loop
12767 // and latch with their respective incoming values of LPhi.
12768 // TODO: Generalize to handle loops with many inputs in a header.
12769 if (LPhi->getNumIncomingValues() != 2) return false;
12770
12771 auto *RLoop = RAR->getLoop();
12772 auto *Predecessor = RLoop->getLoopPredecessor();
12773 assert(Predecessor && "Loop with AddRec with no predecessor?");
12774 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12775 if (!ProvedEasily(L1, RAR->getStart()))
12776 return false;
12777 auto *Latch = RLoop->getLoopLatch();
12778 assert(Latch && "Loop with AddRec with no latch?");
12779 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12780 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12781 return false;
12782 } else {
12783 // In all other cases go over inputs of LHS and compare each of them to RHS,
12784 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12785 // At this point RHS is either a non-Phi, or it is a Phi from some block
12786 // different from LBB.
12787 for (const BasicBlock *IncBB : predecessors(LBB)) {
12788 // Check that RHS is available in this block.
12789 if (!dominates(RHS, IncBB))
12790 return false;
12791 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12792 // Make sure L does not refer to a value from a potentially previous
12793 // iteration of a loop.
12794 if (!properlyDominates(L, LBB))
12795 return false;
12796 // Addrecs are considered to properly dominate their loop, so are missed
12797 // by the previous check. Discard any values that have computable
12798 // evolution in this loop.
12799 if (auto *Loop = LI.getLoopFor(LBB))
12801 return false;
12802 if (!ProvedEasily(L, RHS))
12803 return false;
12804 }
12805 }
12806 return true;
12807}
12808
12809bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12810 const SCEV *LHS,
12811 const SCEV *RHS,
12812 const SCEV *FoundLHS,
12813 const SCEV *FoundRHS) {
12814 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12815 // sure that we are dealing with same LHS.
12816 if (RHS == FoundRHS) {
12817 std::swap(LHS, RHS);
12818 std::swap(FoundLHS, FoundRHS);
12820 }
12821 if (LHS != FoundLHS)
12822 return false;
12823
12824 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12825 if (!SUFoundRHS)
12826 return false;
12827
12828 Value *Shiftee, *ShiftValue;
12829
12830 using namespace PatternMatch;
12831 if (match(SUFoundRHS->getValue(),
12832 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12833 auto *ShifteeS = getSCEV(Shiftee);
12834 // Prove one of the following:
12835 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12836 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12837 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12838 // ---> LHS <s RHS
12839 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12840 // ---> LHS <=s RHS
12841 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12842 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12843 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12844 if (isKnownNonNegative(ShifteeS))
12845 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12846 }
12847
12848 return false;
12849}
12850
12851bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12852 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12853 const SCEV *FoundRHS) {
12854 // Only valid for equality predicates: (A == B) implies (C == D) when
12855 // the SCEV difference A - B equals C - D (they check the same
12856 // underlying relationship at every iteration).
12857 if (!ICmpInst::isEquality(Pred))
12858 return false;
12859
12860 // Restrict to cases involving loop recurrences - that's where this
12861 // pattern arises (correlated IV comparisons). This avoids calling
12862 // getMinusSCEV on arbitrary non-loop expressions.
12864 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12865 return false;
12866
12867 // AddRecs from different loops can never produce matching differences.
12868 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12869 if (!QueryAddRec)
12870 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12871 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12872 if (!FoundAddRec)
12873 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12874 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12875 return false;
12876
12877 // If the strides differ, the differences can never match.
12878 if (QueryAddRec->getStepRecurrence(*this) !=
12879 FoundAddRec->getStepRecurrence(*this))
12880 return false;
12881
12882 // Compute differences. For pointer-typed operands sharing the same base,
12883 // getMinusSCEV strips the common base and returns an integer SCEV.
12884 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12885 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12886 if (isa<SCEVCouldNotCompute>(FoundDiff))
12887 return false;
12888
12889 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12890 if (isa<SCEVCouldNotCompute>(Diff))
12891 return false;
12892
12893 return Diff == FoundDiff;
12894}
12895
12896bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12897 const SCEV *RHS,
12898 const SCEV *FoundLHS,
12899 const SCEV *FoundRHS,
12900 const Instruction *CtxI) {
12901 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12902 FoundRHS) ||
12903 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12904 FoundRHS) ||
12905 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12906 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12907 CtxI) ||
12908 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12909 FoundRHS) ||
12910 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12911}
12912
12913/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12914template <typename MinMaxExprType>
12915static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12916 const SCEV *Candidate) {
12917 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12918 if (!MinMaxExpr)
12919 return false;
12920
12921 return is_contained(MinMaxExpr->operands(), Candidate);
12922}
12923
12925 CmpPredicate Pred, const SCEV *LHS,
12926 const SCEV *RHS) {
12927 // If both sides are affine addrecs for the same loop, with equal
12928 // steps, and we know the recurrences don't wrap, then we only
12929 // need to check the predicate on the starting values.
12930
12931 if (!ICmpInst::isRelational(Pred))
12932 return false;
12933
12934 const SCEV *LStart, *RStart, *Step;
12935 const Loop *L;
12936 if (!match(LHS,
12937 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12939 m_SpecificLoop(L))))
12940 return false;
12944 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
12945 return false;
12946
12947 return SE.isKnownPredicate(Pred, LStart, RStart);
12948}
12949
12950/// Is LHS `Pred` RHS true because one of them is an AddRec that is known not to
12951/// go below its own start value?
12953 CmpPredicate Pred,
12954 const SCEV *LHS,
12955 const SCEV *RHS) {
12956 // Normalize to (AddRec Pred Start).
12959 std::swap(LHS, RHS);
12960 }
12961
12962 // The recurrence is equal to Start in the first iteration, so only the
12963 // non-strict predicate holds.
12964 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE)
12965 return false;
12966
12967 const auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
12968 if (!AR || AR->getStart() != RHS)
12969 return false;
12970
12971 return SE.getMonotonicPredicateType(AR, Pred) ==
12973}
12974
12975/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
12976/// expression?
12978 const SCEV *LHS, const SCEV *RHS) {
12979 switch (Pred) {
12980 default:
12981 return false;
12982
12983 case ICmpInst::ICMP_SGE:
12984 std::swap(LHS, RHS);
12985 [[fallthrough]];
12986 case ICmpInst::ICMP_SLE:
12987 return
12988 // min(A, ...) <= A
12990 // A <= max(A, ...)
12992
12993 case ICmpInst::ICMP_UGE:
12994 std::swap(LHS, RHS);
12995 [[fallthrough]];
12996 case ICmpInst::ICMP_ULE:
12997 return
12998 // min(A, ...) <= A
12999 // FIXME: what about umin_seq?
13001 // A <= max(A, ...)
13003
13004 case ICmpInst::ICMP_UGT:
13005 std::swap(LHS, RHS);
13006 [[fallthrough]];
13007 case ICmpInst::ICMP_ULT:
13008 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
13009 // umin(Ops) u< RHS.
13010 //
13011 // Use computeConstantDifference instead of the more powerful
13012 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
13013 // is called from isKnownViaNonRecursiveReasoning, so recursing into
13014 // the full predicate prover would be expensive.
13015 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
13016 for (SCEVUse Op : Min->operands()) {
13017 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13018 // When Op and RHS share a common base differing by a
13019 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13020 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13021 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13022 return true;
13023 }
13024 }
13025 return false;
13026 }
13027
13028 llvm_unreachable("covered switch fell through?!");
13029}
13030
13031bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13032 const SCEV *RHS,
13033 const SCEV *FoundLHS,
13034 const SCEV *FoundRHS,
13035 unsigned Depth) {
13038 "LHS and RHS have different sizes?");
13039 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13040 getTypeSizeInBits(FoundRHS->getType()) &&
13041 "FoundLHS and FoundRHS have different sizes?");
13042 // We want to avoid hurting the compile time with analysis of too big trees.
13044 return false;
13045
13046 // We only want to work with GT comparison so far.
13047 if (ICmpInst::isLT(Pred)) {
13049 std::swap(LHS, RHS);
13050 std::swap(FoundLHS, FoundRHS);
13051 }
13052
13054
13055 // For unsigned, try to reduce it to corresponding signed comparison.
13056 if (P == ICmpInst::ICMP_UGT)
13057 // We can replace unsigned predicate with its signed counterpart if all
13058 // involved values are non-negative.
13059 // TODO: We could have better support for unsigned.
13060 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13061 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13062 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13063 // use this fact to prove that LHS and RHS are non-negative.
13064 const SCEV *MinusOne = getMinusOne(LHS->getType());
13065 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13066 FoundRHS) &&
13067 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13068 FoundRHS))
13070 }
13071
13072 if (P != ICmpInst::ICMP_SGT)
13073 return false;
13074
13075 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13076 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13077 return Ext->getOperand();
13078 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13079 // the constant in some cases.
13080 return S;
13081 };
13082
13083 // Acquire values from extensions.
13084 auto *OrigLHS = LHS;
13085 auto *OrigFoundLHS = FoundLHS;
13086 LHS = GetOpFromSExt(LHS);
13087 FoundLHS = GetOpFromSExt(FoundLHS);
13088
13089 // Is the SGT predicate can be proved trivially or using the found context.
13090 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13091 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13092 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13093 FoundRHS, Depth + 1);
13094 };
13095
13096 SCEVUse LL;
13097 SCEVUse LR;
13098 if (match(LHS, m_scev_NSWAdd(m_SCEV(LL), m_SCEV(LR)))) {
13099 // We want to avoid creation of any new non-constant SCEV. Since we are
13100 // going to compare the operands to RHS, we should be certain that we don't
13101 // need any size extensions for this. So let's decline all cases when the
13102 // sizes of types of LHS and RHS do not match.
13103 // TODO: Maybe try to get RHS from sext to catch more cases?
13105 return false;
13106
13107 auto *MinusOne = getMinusOne(RHS->getType());
13108
13109 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13110 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13111 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13112 };
13113 // Try to prove the following rule:
13114 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13115 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13116 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13117 return true;
13118 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13119 Value *LL, *LR;
13120 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13121
13122 using namespace llvm::PatternMatch;
13123
13124 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13125 // Rules for division.
13126 // We are going to perform some comparisons with Denominator and its
13127 // derivative expressions. In general case, creating a SCEV for it may
13128 // lead to a complex analysis of the entire graph, and in particular it
13129 // can request trip count recalculation for the same loop. This would
13130 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13131 // this, we only want to create SCEVs that are constants in this section.
13132 // So we bail if Denominator is not a constant.
13133 if (!isa<ConstantInt>(LR))
13134 return false;
13135
13136 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13137
13138 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13139 // then a SCEV for the numerator already exists and matches with FoundLHS.
13140 auto *Numerator = getExistingSCEV(LL);
13141 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13142 return false;
13143
13144 // Make sure that the numerator matches with FoundLHS and the denominator
13145 // is positive.
13146 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13147 return false;
13148
13149 auto *DTy = Denominator->getType();
13150 auto *FRHSTy = FoundRHS->getType();
13151 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13152 // One of types is a pointer and another one is not. We cannot extend
13153 // them properly to a wider type, so let us just reject this case.
13154 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13155 // to avoid this check.
13156 return false;
13157
13158 // Given that:
13159 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13160 auto *WTy = getWiderType(DTy, FRHSTy);
13161 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13162 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13163
13164 // Try to prove the following rule:
13165 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13166 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13167 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13168 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13169 if (isKnownNonPositive(RHS) &&
13170 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13171 return true;
13172
13173 // Try to prove the following rule:
13174 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13175 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13176 // If we divide it by Denominator > 2, then:
13177 // 1. If FoundLHS is negative, then the result is 0.
13178 // 2. If FoundLHS is non-negative, then the result is non-negative.
13179 // Anyways, the result is non-negative.
13180 auto *MinusOne = getMinusOne(WTy);
13181 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13182 if (isKnownNegative(RHS) &&
13183 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13184 return true;
13185 }
13186 }
13187
13188 // If our expression contained SCEVUnknown Phis, and we split it down and now
13189 // need to prove something for them, try to prove the predicate for every
13190 // possible incoming values of those Phis.
13191 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13192 return true;
13193
13194 return false;
13195}
13196
13198 const SCEV *RHS) {
13199 // zext x u<= sext x, sext x s<= zext x
13200 const SCEV *Op;
13201 switch (Pred) {
13202 case ICmpInst::ICMP_SGE:
13203 std::swap(LHS, RHS);
13204 [[fallthrough]];
13205 case ICmpInst::ICMP_SLE: {
13206 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13207 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13209 }
13210 case ICmpInst::ICMP_UGE:
13211 std::swap(LHS, RHS);
13212 [[fallthrough]];
13213 case ICmpInst::ICMP_ULE: {
13214 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13215 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13217 }
13218 default:
13219 return false;
13220 };
13221 llvm_unreachable("unhandled case");
13222}
13223
13224bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13225 SCEVUse LHS,
13226 SCEVUse RHS) {
13227 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13228 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13229 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13230 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13232 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13233}
13234
13235bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13236 const SCEV *LHS,
13237 const SCEV *RHS,
13238 const SCEV *FoundLHS,
13239 const SCEV *FoundRHS) {
13240 if (ICmpInst::isEquality(Pred)) {
13241 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13242 return true;
13243 } else {
13245 if (isKnownViaNonRecursiveReasoning(NonStrictPred, LHS, FoundLHS) &&
13246 isKnownViaNonRecursiveReasoning(
13247 ICmpInst::getSwappedPredicate(NonStrictPred), RHS, FoundRHS))
13248 return true;
13249 }
13250
13251 // Maybe it can be proved via operations?
13252 return isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS);
13253}
13254
13255bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13256 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13257 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13258 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13259 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13260 // reduce the compile time impact of this optimization.
13261 return false;
13262
13263 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13264 if (!Addend)
13265 return false;
13266
13267 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13268
13269 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13270 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13271 ConstantRange FoundLHSRange =
13272 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13273
13274 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13275 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13276
13277 // We can also compute the range of values for `LHS` that satisfy the
13278 // consequent, "`LHS` `Pred` `RHS`":
13279 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13280 // The antecedent implies the consequent if every value of `LHS` that
13281 // satisfies the antecedent also satisfies the consequent.
13282 return LHSRange.icmp(Pred, ConstRHS);
13283}
13284
13285bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13286 bool IsSigned, bool Invert) {
13287 assert(isKnownPositive(Stride) && "Positive stride expected!");
13288
13289 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13290 const SCEV *One = getOne(Stride->getType());
13291
13292 if (IsSigned) {
13293 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/true, Invert);
13294 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13295 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13296
13297 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13298 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13299 }
13300
13301 APInt MaxRHS = getRangeMax(RHS, /*IsSigned=*/false, Invert);
13302 APInt MaxValue = APInt::getMaxValue(BitWidth);
13303 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13304
13305 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13306 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13307}
13308
13310 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13311 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13312 // expression fixes the case of N=0.
13313 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13314 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13315 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13316}
13317
13318const SCEV *
13319ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
13320 const SCEV *End, unsigned BitWidth,
13321 bool IsSigned, bool Invert) {
13322 // The logic in this function assumes we can represent a positive stride.
13323 // If we can't, the backedge-taken count must be zero.
13324 if (IsSigned && BitWidth == 1)
13325 return getZero(Stride->getType());
13326
13327 // This code below only been closely audited for negative strides in the
13328 // unsigned comparison case, it may be correct for signed comparison, but
13329 // that needs to be established.
13330 if (IsSigned && isKnownNegative(Stride))
13331 return getCouldNotCompute();
13332
13333 // Calculate the maximum backedge count based on the range of values
13334 // permitted by Start, End, and Stride. If Invert is true, both Start and End
13335 // need inverting. Stride was already negated by the caller.
13336 APInt MinStart = getRangeMin(Start, IsSigned, Invert);
13337
13338 APInt MinStride =
13339 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13340
13341 // We assume either the stride is positive, or the backedge-taken count
13342 // is zero. So force StrideForMaxBECount to be at least one.
13343 APInt One(BitWidth, 1);
13344 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13345 : APIntOps::umax(One, MinStride);
13346
13347 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13348 : APInt::getMaxValue(BitWidth);
13349 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13350
13351 // Although End can be a MAX expression we estimate MaxEnd considering only
13352 // the case End = RHS of the loop termination condition. This is safe because
13353 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13354 // taken count.
13355 APInt MaxEnd = getRangeMax(End, IsSigned, Invert);
13356 MaxEnd =
13357 IsSigned ? APIntOps::smin(MaxEnd, Limit) : APIntOps::umin(MaxEnd, Limit);
13358
13359 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13360 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13361 : APIntOps::umax(MaxEnd, MinStart);
13362
13363 APInt Delta = MaxEnd - MinStart;
13364
13365 // Try to refine Delta in case End - Start (or Start - End if Invert) gives a
13366 // tighter bound after folding.
13367 const SCEV *DeltaExpr =
13368 Invert ? getMinusSCEV(Start, End) : getMinusSCEV(End, Start);
13369 Delta = APIntOps::umin(Delta, getUnsignedRangeMax(DeltaExpr));
13370
13371 return getUDivCeilSCEV(getConstant(Delta), getConstant(StrideForMaxBECount));
13372}
13373
13375ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13376 const Loop *L, bool IsSigned, bool Invert,
13377 bool ControlsOnlyExit, bool AllowPredicates) {
13379
13380 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
13381
13382 // FIXME: Extend the non-invariant RHS analysis to greater-than comparisons.
13383 if (Invert && !isLoopInvariant(RHS, L))
13384 return getCouldNotCompute();
13385
13387 bool PredicatedIV = false;
13388 // FIXME: Generalize the NUW inference below to decreasing IVs.
13389 if (!IV && !Invert) {
13390 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13391 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13392 if (AR && AR->getLoop() == L && AR->isAffine()) {
13393 auto canProveNUW = [&]() {
13394 // We can use the comparison to infer no-wrap flags only if it fully
13395 // controls the loop exit.
13396 if (!ControlsOnlyExit)
13397 return false;
13398
13399 if (!isLoopInvariant(RHS, L))
13400 return false;
13401
13402 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13403 // We need the sequence defined by AR to strictly increase in the
13404 // unsigned integer domain for the logic below to hold.
13405 return false;
13406
13407 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13408 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13409 // If RHS <=u Limit, then there must exist a value V in the sequence
13410 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13411 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13412 // overflow occurs. This limit also implies that a signed comparison
13413 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13414 // the high bits on both sides must be zero.
13415 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13416 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13417 Limit = Limit.zext(OuterBitWidth);
13418 return getUnsignedRangeMax(applyLoopGuards(RHS, Guards)).ule(Limit);
13419 };
13420 auto Flags = AR->getNoWrapFlags();
13421 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13422 Flags = setFlags(Flags, SCEV::FlagNUW);
13423
13424 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13425 if (AR->hasNoUnsignedWrap()) {
13426 // Emulate what getZeroExtendExpr would have done during construction
13427 // if we'd been able to infer the fact just above at that time.
13428 const SCEV *Step = AR->getStepRecurrence(*this);
13429 Type *Ty = ZExt->getType();
13430 const SCEV *S = getAddRecExpr(
13432 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13434 }
13435 }
13436 }
13437 }
13438
13439 if (!IV && AllowPredicates) {
13440 // Try to make this an AddRec using runtime tests, in the first X
13441 // iterations of this loop, where X is the SCEV expression found by the
13442 // algorithm below.
13443 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13444 PredicatedIV = true;
13445 }
13446
13447 // Avoid weird loops
13448 if (!IV || IV->getLoop() != L || !IV->isAffine())
13449 return getCouldNotCompute();
13450
13451 // A precondition of this method is that the condition being analyzed
13452 // reaches an exiting branch which dominates the latch. Given that, we can
13453 // assume that an increment which violates the nowrap specification and
13454 // produces poison must cause undefined behavior when the resulting poison
13455 // value is branched upon and thus we can conclude that the backedge is
13456 // taken no more often than would be required to produce that poison value.
13457 // Note that a well defined loop can exit on the iteration which violates
13458 // the nowrap specification if there is another exit (either explicit or
13459 // implicit/exceptional) which causes the loop to execute before the
13460 // exiting instruction we're analyzing would trigger UB.
13461 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13462 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13463 // Reverse the ordering for greater-than comparisons.
13465 if (Invert)
13467
13468 // The step of ~IV is the negated step of IV.
13469 const SCEV *Stride = IV->getStepRecurrence(*this);
13470 if (Invert)
13471 Stride = getNegativeSCEV(Stride);
13472 const SCEV *GuardedStride = Stride;
13473
13474 // Whether the IV may reach the maximum (or minimum if inverted) value
13475 // before the exit is taken.
13476 bool IVMayOverflow = true;
13477
13478 bool PositiveStride = isKnownPositive(Stride);
13479 // A dominating guard may prove the stride positive.
13480 if (!PositiveStride) {
13481 const SCEV *LoopGuardedStride = applyLoopGuards(Stride, Guards);
13482 if (isKnownPositive(LoopGuardedStride)) {
13483 GuardedStride = LoopGuardedStride;
13484 PositiveStride = true;
13485 // Encode the context-sensitive stride > 0 fact into the expression
13486 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13487 }
13488 }
13489
13490 // Avoid negative or zero stride values.
13491 if (!PositiveStride) {
13492 // FIXME: Generalize the unknown-stride analysis to decreasing IVs.
13493 if (Invert)
13494 return getCouldNotCompute();
13495
13496 // We can compute the correct backedge taken count for loops with unknown
13497 // strides if we can prove that the loop is not an infinite loop with side
13498 // effects. Here's the loop structure we are trying to handle -
13499 //
13500 // i = start
13501 // do {
13502 // A[i] = i;
13503 // i += s;
13504 // } while (i < end);
13505 //
13506 // The backedge taken count for such loops is evaluated as -
13507 // (max(end, start + stride) - start - 1) /u stride
13508 //
13509 // The additional preconditions that we need to check to prove correctness
13510 // of the above formula is as follows -
13511 //
13512 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13513 // NoWrap flag).
13514 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13515 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13516 // no side effects within the loop) or a predicate is added to ensure
13517 // stride is positive.
13518 // c) loop has a single static exit (with no abnormal exits)
13519 //
13520 // Precondition a) implies that if the stride is negative, this is a single
13521 // trip loop. The backedge taken count formula reduces to zero in this case.
13522 //
13523 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13524 // then a zero stride means the backedge can't be taken without executing
13525 // undefined behavior.
13526 //
13527 // The positive stride case is the same as isKnownPositive(Stride) returning
13528 // true (original behavior of the function).
13529 //
13530 if (PredicatedIV || !NoWrap || !loopHasNoAbnormalExits(L))
13531 return getCouldNotCompute();
13532
13533 if (!loopIsFiniteByAssumption(L)) {
13534 // If the loop may be infinite, add a predicate ensuring Stride is
13535 // positive, to guarantee forward progress.
13536 if (!AllowPredicates || !isLoopInvariant(Stride, L))
13537 return getCouldNotCompute();
13538
13539 const SCEV *Zero = getZero(Stride->getType());
13540 const SCEVPredicate *P =
13542 Predicates.push_back(P);
13543 // When the predicate holds (Stride > 0), umax(Stride, 1) == Stride,
13544 // so the result is unchanged. To prevent div by zero.
13545 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13546 } else if (!isKnownNonZero(Stride)) {
13547 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13548 // if it might eventually be greater than start and if so, on which
13549 // iteration. We can't even produce a useful upper bound.
13550 if (!isLoopInvariant(RHS, L))
13551 return getCouldNotCompute();
13552
13553 // We allow a potentially zero stride, but we need to divide by stride
13554 // below. Since the loop can't be infinite and this check must control
13555 // the sole exit, we can infer the exit must be taken on the first
13556 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13557 // we know the numerator in the divides below must be zero, so we can
13558 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13559 // and produce the right result.
13560 // FIXME: Handle the case where Stride is poison?
13561 auto wouldZeroStrideBeUB = [&]() {
13562 // Proof by contradiction. Suppose the stride were zero. If we can
13563 // prove that the backedge *is* taken on the first iteration, then since
13564 // we know this condition controls the sole exit, we must have an
13565 // infinite loop. We can't have a (well defined) infinite loop per
13566 // check just above.
13567 // Note: The (Start - Stride) term is used to get the start' term from
13568 // (start' + stride,+,stride). Remember that we only care about the
13569 // result of this expression when stride == 0 at runtime.
13570 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13571 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13572 };
13573 if (!wouldZeroStrideBeUB()) {
13574 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13575 }
13576 }
13577 } else {
13578 // Avoid proven overflow cases: this will ensure that the backedge taken
13579 // count will not generate any unsigned overflow.
13580 IVMayOverflow = canIVOverflowOnLT(RHS, GuardedStride, IsSigned, Invert) &&
13581 canIVOverflowOnLT(applyLoopGuards(RHS, Guards),
13582 GuardedStride, IsSigned, Invert);
13583 if (IVMayOverflow && !NoWrap)
13584 return getCouldNotCompute();
13585 }
13586
13587 // On all paths just preceeding, we established the following invariant:
13588 // IV can be assumed not to overflow up to and including the exiting
13589 // iteration. We proved this in one of two ways:
13590 // 1) We can show overflow doesn't occur before the exiting iteration
13591 // 1a) canIVOverflowOnLT, and b) step of one
13592 // 2) We can show that if overflow occurs, the loop must execute UB
13593 // before any possible exit.
13594 // Note that we have not yet proved RHS invariant (in general).
13595
13596 const SCEV *Start = IV->getStart();
13597
13598 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13599 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13600 // Use integer-typed versions for actual computation; we can't subtract
13601 // pointers in general.
13602 const SCEV *OrigStart = Start;
13603 const SCEV *OrigRHS = RHS;
13604 if (Start->getType()->isPointerTy()) {
13605 Start = getPtrToAddrExpr(Start);
13606 if (isa<SCEVCouldNotCompute>(Start))
13607 return Start;
13608 }
13609 if (RHS->getType()->isPointerTy()) {
13612 return RHS;
13613 }
13614
13615 const SCEV *End = nullptr, *BECount = getCouldNotCompute(),
13616 *BECountIfBackedgeTaken = getCouldNotCompute();
13617 if (!isLoopInvariant(RHS, L)) {
13618 assert(!Invert && "RHS must be loop-invariant for Invert");
13619 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13620 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13621 any(RHSAddRec->getNoWrapFlags())) {
13622 // The structure of loop we are trying to calculate backedge count of:
13623 //
13624 // left = left_start
13625 // right = right_start
13626 //
13627 // while(left < right){
13628 // ... do something here ...
13629 // left += s1; // stride of left is s1 (s1 > 0)
13630 // right += s2; // stride of right is s2 (s2 < 0)
13631 // }
13632 //
13633
13634 const SCEV *RHSStart = RHSAddRec->getStart();
13635 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13636
13637 // If Stride - RHSStride is positive and does not overflow, we can write
13638 // backedge count as ->
13639 // ceil((End - Start) /u (Stride - RHSStride))
13640 // Where, End = max(RHSStart, Start)
13641
13642 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13643 if (isKnownNegative(RHSStride) &&
13644 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13645 RHSStride)) {
13646
13647 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13648 if (isKnownPositive(Denominator)) {
13649 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13650 : getUMaxExpr(RHSStart, Start);
13651
13652 // We can do this because End >= Start, as End = max(RHSStart, Start)
13653 const SCEV *Delta = getMinusSCEV(End, Start);
13654
13655 BECount = getUDivCeilSCEV(Delta, Denominator);
13656 BECountIfBackedgeTaken =
13657 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13658 }
13659 }
13660 }
13661 } else {
13662 // Let End = max(RHS,Start). We use the expression (End-Start)/Stride to
13663 // describe the backedge count: if the backedge is taken at least once then
13664 // End is RHS, and if not End is Start so we get a backedge count of zero.
13665 // Inverted, End is min(RHS, Start).
13666 //
13667 // AddingStrideMinusOneMayOverflow has the following preconditions:
13668 //
13669 // 1. Start <= End, signed if IsSigned (inverted: End <= Start)
13670 // 2. The index variable doesn't overflow.
13671 //
13672 // Therefore, we know N exists such that
13673 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13674 // doesn't overflow.
13675 //
13676 // Using this information, try to prove whether the addition in
13677 // "(End - Start) + (Stride - 1)" has unsigned overflow.
13678 //
13679 // If the IV cannot overflow, RHS is at least Stride - 1 below the maximum
13680 // value, so the distance End - Start is at most UMAX - (Stride - 1) and
13681 // the (Stride - 1) addition below cannot overflow.
13682 const SCEV *One = getOne(Stride->getType());
13683 bool AddingStrideMinusOneMayOverflow = IVMayOverflow && [&] {
13684 if (isKnownToBeAPowerOfTwo(Stride)) {
13685 // Suppose Stride is a power of two, and Start/End are unsigned
13686 // integers. Let UMAX be the largest representable unsigned
13687 // integer.
13688 //
13689 // By the preconditions of this function, we know
13690 // "(Start + Stride * N) >= End", and this doesn't overflow.
13691 // As a formula:
13692 //
13693 // End <= (Start + Stride * N) <= UMAX
13694 //
13695 // Subtracting Start from all the terms:
13696 //
13697 // End - Start <= Stride * N <= UMAX - Start
13698 //
13699 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13700 //
13701 // End - Start <= Stride * N <= UMAX
13702 //
13703 // Stride * N is a multiple of Stride. Therefore,
13704 //
13705 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13706 //
13707 // Since Stride is a power of two, UMAX + 1 is divisible by
13708 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13709 // write:
13710 //
13711 // End - Start <= Stride * N <= UMAX - Stride - 1
13712 //
13713 // Dropping the middle term:
13714 //
13715 // End - Start <= UMAX - Stride - 1
13716 //
13717 // Adding Stride - 1 to both sides:
13718 //
13719 // (End - Start) + (Stride - 1) <= UMAX
13720 //
13721 // In other words, the addition doesn't have unsigned overflow.
13722 //
13723 // A similar proof works if we treat Start/End as signed values.
13724 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13725 // to use signed max instead of unsigned max. Note that we're
13726 // trying to prove a lack of unsigned overflow in either case.
13727 // Inverted: "Start - End <= Stride * N <= Start - MIN <= UMAX", same.
13728 return false;
13729 }
13730 if (!Invert && (Start == Stride || Start == getMinusSCEV(Stride, One))) {
13731 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13732 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13733 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13734 // 1 <s End.
13735 //
13736 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13737 // End.
13738 //
13739 // Both need Start to be the smaller value, so neither applies inverted.
13740 return false;
13741 }
13742 return true;
13743 }();
13744
13745 // If inverted, the analyzed values are complements: "~V - Offset" is "~(V +
13746 // Offset)" and "~To - ~From" is "From - To".
13747 auto StepBack = [&](const SCEV *V, const SCEV *Offset) -> const SCEV * {
13748 if (Invert)
13749 return getAddExpr(V, Offset);
13750 return getMinusSCEV(V, Offset);
13751 };
13752 auto Distance = [&](const SCEV *From, const SCEV *To) {
13753 return Invert ? getMinusSCEV(From, To) : getMinusSCEV(To, From);
13754 };
13755
13756 const SCEV *OrigPrevStart = StepBack(OrigStart, Stride);
13757 assert(isAvailableAtLoopEntry(OrigPrevStart, L) && "Must be!");
13758 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13759 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13760 // Can we prove Start - Stride < RHS, and either Start - Stride < Start or
13761 // (via !AddingStrideMinusOneMayOverflow) that (RHS - Start) + (Stride - 1)
13762 // does not overflow?
13763 if ((!AddingStrideMinusOneMayOverflow ||
13764 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigStart)) &&
13765 isLoopEntryGuardedByCond(L, Cond, OrigPrevStart, OrigRHS)) {
13766 // In this case, we can use a refined formula for computing backedge
13767 // taken count. The general formula remains:
13768 // "End-Start /uceiling Stride"
13769 // We want to use the alternate formula:
13770 // "((RHS - 1) - (Start - Stride)) /u Stride"
13771 // Let's do a quick case analysis to show these are equivalent under
13772 // our preconditions. When inverted, the proof uses complemented Start,
13773 // RHS and End; Stride remains positive.
13774 // * For RHS <= Start (End is Start), the backedge-taken count must be
13775 // zero. Together with the precondition "Start - Stride < RHS", we have
13776 // "Start - Stride < RHS <= Start". Subtracting Start - Stride from
13777 // all sides we get "0 < RHS - (Start - Stride) <= Stride".
13778 // Subtracting 1 we get "0 <= (RHS - 1) - (Start - Stride) < Stride".
13779 // So dividing that by Stride gives zero.
13780 //
13781 // * For RHS > Start (End is RHS), the backedge count must be
13782 // "RHS-Start /uceil Stride", so it is sufficient to show that the
13783 // numerator "((RHS - 1) - (Start - Stride))" does not overflow.
13784 //
13785 // If "Start - Stride < Start" holds, we have
13786 // "RHS > Start > Start - Stride". As such
13787 // "RHS - (Start - Stride) - 1" does not overflow, which is the
13788 // reassociated numerator.
13789 //
13790 // Otherwise !AddingStrideMinusOneMayOverflow guarantees that
13791 // "(End - Start) + (Stride - 1)" does not overflow unsigned. Here
13792 // "End" is "RHS", as "RHS > Start", so this is the reassociated
13793 // numerator. Neither sub-term wraps unsigned: "RHS - Start"
13794 // due to "RHS > Start", and "Stride - 1", as Stride is non-zero.
13795 const SCEV *Numerator =
13796 getMinusSCEV(Distance(StepBack(Start, Stride), RHS), One);
13797 BECount = getUDivExpr(Numerator, Stride);
13798 }
13799
13800 if (isa<SCEVCouldNotCompute>(BECount)) {
13801 auto canProveRHSIsAtOrBeyondStart = [&]() {
13802 // Inverted, the claim is "Start >= RHS". Reverse the comparisons below
13803 // by swapping their operands rather than their predicates:
13804 // isLoopEntryGuardedByCond is sensitive to operand order and loses the
13805 // proof if the IV bound moves to the other side.
13806 auto SwapIfInverted = [&](const SCEV *A, const SCEV *B) {
13807 return Invert ? std::pair(B, A) : std::pair(A, B);
13808 };
13809
13810 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13811 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, Guards);
13812 const SCEV *GuardedStart = applyLoopGuards(OrigStart, Guards);
13813 if (Invert)
13814 std::swap(GuardedRHS, GuardedStart);
13815
13816 auto [GELHS, GERHS] = SwapIfInverted(OrigRHS, OrigStart);
13817 if (isLoopEntryGuardedByCond(L, CondGE, GELHS, GERHS) ||
13818 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13819 return true;
13820
13821 if ((GuardedRHS != GELHS || GuardedStart != GERHS) &&
13822 isKnownPredicate(CondGE, GELHS, GERHS))
13823 return true;
13824
13825 // (RHS > Start - 1) implies RHS >= Start.
13826 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13827 // "Start - 1" doesn't overflow.
13828 // * For signed comparison, if Start - 1 does overflow, it's equal
13829 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13830 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13831 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13832 //
13833 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13834 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13835 auto [GTLHS, GTRHS] = SwapIfInverted(OrigRHS, StepBack(OrigStart, One));
13836 return isLoopEntryGuardedByCond(L, CondGT, GTLHS, GTRHS);
13837 };
13838
13839 // If we know that RHS >= Start in the context of loop, then we know
13840 // that max(RHS, Start) = RHS at this point.
13841 if (canProveRHSIsAtOrBeyondStart()) {
13842 End = RHS;
13843 } else {
13844 // If RHS < Start, the backedge will be taken zero times. So in
13845 // general, we can write the backedge-taken count as:
13846 //
13847 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13848 //
13849 // We convert it to the following to make it more convenient for SCEV:
13850 //
13851 // ceil(max(RHS, Start) - Start) / Stride
13852 //
13853 // Inverted, this is ceil(Start - min(RHS, Start)) / Stride.
13854 if (Invert)
13855 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13856 else
13857 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13858
13859 // See what would happen if we assume the backedge is taken. This is
13860 // used to compute MaxBECount.
13861 BECountIfBackedgeTaken = getUDivCeilSCEV(Distance(Start, RHS), Stride);
13862 }
13863
13864 const SCEV *Delta = Distance(Start, End);
13865 if (!AddingStrideMinusOneMayOverflow) {
13866 // floor((D + (S - 1)) / S)
13867 // We prefer this formulation if it's legal because it's fewer
13868 // operations.
13869 BECount =
13870 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13871 } else {
13872 BECount = getUDivCeilSCEV(Delta, Stride);
13873 }
13874 }
13875 }
13876
13877 const SCEV *ConstantMaxBECount;
13878 bool MaxOrZero = false;
13879 if (isa<SCEVConstant>(BECount)) {
13880 ConstantMaxBECount = BECount;
13881 } else {
13882 ConstantMaxBECount = computeMaxBECountForLT(
13883 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
13884 Invert);
13885 // If we know exactly how many times the backedge will be taken if it's
13886 // taken at least once, then the backedge count will either be that or
13887 // zero. If that count exceeds the range-based bound, the backedge can
13888 // never be taken.
13889 const APInt *IfTaken, *RangeMax;
13890 if (match(BECountIfBackedgeTaken, m_scev_APInt(IfTaken))) {
13891 if (match(ConstantMaxBECount, m_scev_APInt(RangeMax)) &&
13892 IfTaken->ugt(*RangeMax)) {
13893 ConstantMaxBECount = getZero(BECountIfBackedgeTaken->getType());
13894 } else {
13895 ConstantMaxBECount = BECountIfBackedgeTaken;
13896 MaxOrZero = true;
13897 }
13898 }
13899 }
13900
13901 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13902 !isa<SCEVCouldNotCompute>(BECount))
13903 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13904
13905 const SCEV *SymbolicMaxBECount =
13906 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13907 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13908 Predicates);
13909}
13910
13912 ScalarEvolution &SE) const {
13913 if (Range.isFullSet()) // Infinite loop.
13914 return SE.getCouldNotCompute();
13915
13916 // If the start is a non-zero constant, shift the range to simplify things.
13917 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
13918 if (!SC->getValue()->isZero()) {
13920 Operands[0] = SE.getZero(SC->getType());
13921 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
13923 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
13924 return ShiftedAddRec->getNumIterationsInRange(
13925 Range.subtract(SC->getAPInt()), SE);
13926 // This is strange and shouldn't happen.
13927 return SE.getCouldNotCompute();
13928 }
13929
13930 // The only time we can solve this is when we have all constant indices.
13931 // Otherwise, we cannot determine the overflow conditions.
13933 return SE.getCouldNotCompute();
13934
13935 // Okay at this point we know that all elements of the chrec are constants and
13936 // that the start element is zero.
13937
13938 // First check to see if the range contains zero. If not, the first
13939 // iteration exits.
13940 unsigned BitWidth = SE.getTypeSizeInBits(getType());
13941 if (!Range.contains(APInt(BitWidth, 0)))
13942 return SE.getZero(getType());
13943
13944 if (isAffine()) {
13945 // If this is an affine expression then we have this situation:
13946 // Solve {0,+,A} in Range === Ax in Range
13947
13948 // We know that zero is in the range. If A is positive then we know that
13949 // the upper value of the range must be the first possible exit value.
13950 // If A is negative then the lower of the range is the last possible loop
13951 // value. Also note that we already checked for a full range.
13952 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
13953 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
13954
13955 // The exit value should be (End+A)/A.
13956 APInt ExitVal = (End + A).udiv(A);
13957 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
13958
13959 // Evaluate at the exit value. If we really did fall out of the valid
13960 // range, then we computed our trip count, otherwise wrap around or other
13961 // things must have happened.
13962 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
13963 if (Range.contains(Val->getValue()))
13964 return SE.getCouldNotCompute(); // Something strange happened
13965
13966 // Ensure that the previous value is in the range.
13967 assert(Range.contains(
13969 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
13970 "Linear scev computation is off in a bad way!");
13971 return SE.getConstant(ExitValue);
13972 }
13973
13974 if (isQuadratic()) {
13975 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
13976 return SE.getConstant(*S);
13977 }
13978
13979 return SE.getCouldNotCompute();
13980}
13981
13982const SCEVAddRecExpr *
13984 assert(getNumOperands() > 1 && "AddRec with zero step?");
13985 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
13986 // but in this case we cannot guarantee that the value returned will be an
13987 // AddRec because SCEV does not have a fixed point where it stops
13988 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
13989 // may happen if we reach arithmetic depth limit while simplifying. So we
13990 // construct the returned value explicitly.
13992 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
13993 // (this + Step) is {A+B,+,B+C,+...,+,N}.
13994 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
13995 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
13996 // We know that the last operand is not a constant zero (otherwise it would
13997 // have been popped out earlier). This guarantees us that if the result has
13998 // the same last operand, then it will also not be popped out, meaning that
13999 // the returned value will be an AddRec.
14000 const SCEV *Last = getOperand(getNumOperands() - 1);
14001 assert(!Last->isZero() && "Recurrency with zero step?");
14002 Ops.push_back(Last);
14004}
14005
14006// Return true when S contains at least an undef value.
14008 return SCEVExprContains(
14009 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14010}
14011
14012// Return true when S contains a value that is a nullptr.
14014 return SCEVExprContains(S, [](const SCEV *S) {
14015 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14016 return SU->getValue() == nullptr;
14017 return false;
14018 });
14019}
14020
14021/// Return the size of an element read or written by Inst.
14023 if (!isa<LoadInst, StoreInst>(Inst))
14024 return nullptr;
14026 return getSizeOfExpr(ETy, getLoadStoreType(Inst));
14027}
14028
14029//===----------------------------------------------------------------------===//
14030// SCEVCallbackVH Class Implementation
14031//===----------------------------------------------------------------------===//
14032
14034 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14035 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14036 SE->ConstantEvolutionLoopExitValue.erase(PN);
14037 SE->eraseValueFromMap(getValPtr());
14038 // this now dangles!
14039}
14040
14041void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14042 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14043
14044 // Forget all the expressions associated with users of the old value,
14045 // so that future queries will recompute the expressions using the new
14046 // value.
14047 SE->forgetValue(getValPtr());
14048 // this now dangles!
14049}
14050
14051ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14052 : CallbackVH(V), SE(se) {}
14053
14054//===----------------------------------------------------------------------===//
14055// ScalarEvolution Class Implementation
14056//===----------------------------------------------------------------------===//
14057
14060 LoopInfo &LI)
14061 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14062 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14063 LoopDispositions(64), BlockDispositions(64) {
14064 // To use guards for proving predicates, we need to scan every instruction in
14065 // relevant basic blocks, and not just terminators. Doing this is a waste of
14066 // time if the IR does not actually contain any calls to
14067 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14068 //
14069 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14070 // to _add_ guards to the module when there weren't any before, and wants
14071 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14072 // efficient in lieu of being smart in that rather obscure case.
14073
14074 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14075 F.getParent(), Intrinsic::experimental_guard);
14076 HasGuards = GuardDecl && !GuardDecl->use_empty();
14077}
14078
14080 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14081 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14082 ValueExprMap(std::move(Arg.ValueExprMap)),
14083 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14084 PendingMerges(std::move(Arg.PendingMerges)),
14085 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14086 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14087 PredicatedBackedgeTakenCounts(
14088 std::move(Arg.PredicatedBackedgeTakenCounts)),
14089 BECountUsers(std::move(Arg.BECountUsers)),
14090 ConstantEvolutionLoopExitValue(
14091 std::move(Arg.ConstantEvolutionLoopExitValue)),
14092 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14093 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14094 LoopDispositions(std::move(Arg.LoopDispositions)),
14095 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14096 BlockDispositions(std::move(Arg.BlockDispositions)),
14097 SCEVUsers(std::move(Arg.SCEVUsers)),
14098 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14099 SignedRanges(std::move(Arg.SignedRanges)),
14100 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14101 UniquePreds(std::move(Arg.UniquePreds)),
14102 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14103 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14104 LoopUsers(std::move(Arg.LoopUsers)),
14105 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14106 FirstUnknown(Arg.FirstUnknown),
14107 NextUnknownOrderID(Arg.NextUnknownOrderID) {
14108 Arg.FirstUnknown = nullptr;
14109}
14110
14112 // Iterate through all the SCEVUnknown instances and call their
14113 // destructors, so that they release their references to their values.
14114 for (SCEVUnknown *U = FirstUnknown; U;) {
14115 SCEVUnknown *Tmp = U;
14116 U = U->Next;
14117 Tmp->~SCEVUnknown();
14118 }
14119 FirstUnknown = nullptr;
14120
14121 ExprValueMap.clear();
14122 ValueExprMap.clear();
14123 HasRecMap.clear();
14124 BackedgeTakenCounts.clear();
14125 PredicatedBackedgeTakenCounts.clear();
14126
14127 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14128 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14129 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14130 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14131}
14132
14136
14137/// When printing a top-level SCEV for trip counts, it's helpful to include
14138/// a type for constants which are otherwise hard to disambiguate.
14139static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14140 if (isa<SCEVConstant>(S))
14141 OS << *S->getType() << " ";
14142 OS << *S;
14143}
14144
14146 const Loop *L) {
14147 // Print all inner loops first
14148 for (Loop *I : *L)
14149 PrintLoopInfo(OS, SE, I);
14150
14151 OS << "Loop ";
14152 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14153 OS << ": ";
14154
14155 SmallVector<BasicBlock *, 8> ExitingBlocks;
14156 L->getExitingBlocks(ExitingBlocks);
14157 if (ExitingBlocks.size() != 1)
14158 OS << "<multiple exits> ";
14159
14160 auto *BTC = SE->getBackedgeTakenCount(L);
14161 if (!isa<SCEVCouldNotCompute>(BTC)) {
14162 OS << "backedge-taken count is ";
14163 PrintSCEVWithTypeHint(OS, BTC);
14164 } else
14165 OS << "Unpredictable backedge-taken count.";
14166 OS << "\n";
14167
14168 if (ExitingBlocks.size() > 1)
14169 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14170 OS << " exit count for " << ExitingBlock->getName() << ": ";
14171 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14172 PrintSCEVWithTypeHint(OS, EC);
14173 if (isa<SCEVCouldNotCompute>(EC)) {
14174 // Retry with predicates.
14176 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14177 if (!isa<SCEVCouldNotCompute>(EC)) {
14178 OS << "\n predicated exit count for " << ExitingBlock->getName()
14179 << ": ";
14180 PrintSCEVWithTypeHint(OS, EC);
14181 OS << "\n Predicates:\n";
14182 for (const auto *P : Predicates)
14183 P->print(OS, 4);
14184 }
14185 }
14186 OS << "\n";
14187 }
14188
14189 OS << "Loop ";
14190 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14191 OS << ": ";
14192
14193 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14194 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14195 OS << "constant max backedge-taken count is ";
14196 PrintSCEVWithTypeHint(OS, ConstantBTC);
14198 OS << ", actual taken count either this or zero.";
14199 } else {
14200 OS << "Unpredictable constant max backedge-taken count. ";
14201 }
14202
14203 OS << "\n"
14204 "Loop ";
14205 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14206 OS << ": ";
14207
14208 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14209 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14210 OS << "symbolic max backedge-taken count is ";
14211 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14213 OS << ", actual taken count either this or zero.";
14214 } else {
14215 OS << "Unpredictable symbolic max backedge-taken count. ";
14216 }
14217 OS << "\n";
14218
14219 if (ExitingBlocks.size() > 1)
14220 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14221 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14222 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14224 PrintSCEVWithTypeHint(OS, ExitBTC);
14225 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14226 // Retry with predicates.
14228 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14230 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14231 OS << "\n predicated symbolic max exit count for "
14232 << ExitingBlock->getName() << ": ";
14233 PrintSCEVWithTypeHint(OS, ExitBTC);
14234 OS << "\n Predicates:\n";
14235 for (const auto *P : Predicates)
14236 P->print(OS, 4);
14237 }
14238 }
14239 OS << "\n";
14240 }
14241
14243 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14244 if (PBT != BTC) {
14245 OS << "Loop ";
14246 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14247 OS << ": ";
14248 if (!isa<SCEVCouldNotCompute>(PBT)) {
14249 OS << "Predicated backedge-taken count is ";
14250 PrintSCEVWithTypeHint(OS, PBT);
14251 } else
14252 OS << "Unpredictable predicated backedge-taken count.";
14253 OS << "\n";
14254 OS << " Predicates:\n";
14255 for (const auto *P : Preds)
14256 P->print(OS, 4);
14257 }
14258 Preds.clear();
14259
14260 auto *PredConstantMax =
14262 if (PredConstantMax != ConstantBTC) {
14263 OS << "Loop ";
14264 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14265 OS << ": ";
14266 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14267 OS << "Predicated constant max backedge-taken count is ";
14268 PrintSCEVWithTypeHint(OS, PredConstantMax);
14269 } else
14270 OS << "Unpredictable predicated constant max backedge-taken count.";
14271 OS << "\n";
14272 OS << " Predicates:\n";
14273 for (const auto *P : Preds)
14274 P->print(OS, 4);
14275 }
14276 Preds.clear();
14277
14278 auto *PredSymbolicMax =
14280 if (SymbolicBTC != PredSymbolicMax) {
14281 OS << "Loop ";
14282 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14283 OS << ": ";
14284 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14285 OS << "Predicated symbolic max backedge-taken count is ";
14286 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14287 } else
14288 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14289 OS << "\n";
14290 OS << " Predicates:\n";
14291 for (const auto *P : Preds)
14292 P->print(OS, 4);
14293 }
14294
14296 OS << "Loop ";
14297 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14298 OS << ": ";
14299 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14300 }
14301}
14302
14303namespace llvm {
14304// Note: these overloaded operators need to be in the llvm namespace for them
14305// to be resolved correctly. If we put them outside the llvm namespace, the
14306//
14307// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14308//
14309// code below "breaks" and start printing raw enum values as opposed to the
14310// string values.
14313 switch (LD) {
14315 OS << "Variant";
14316 break;
14318 OS << "Invariant";
14319 break;
14321 OS << "Uniform";
14322 break;
14324 OS << "Computable";
14325 break;
14326 }
14327 return OS;
14328}
14329
14332 switch (BD) {
14334 OS << "DoesNotDominate";
14335 break;
14337 OS << "Dominates";
14338 break;
14340 OS << "ProperlyDominates";
14341 break;
14342 }
14343 return OS;
14344}
14345} // namespace llvm
14346
14348 // ScalarEvolution's implementation of the print method is to print
14349 // out SCEV values of all instructions that are interesting. Doing
14350 // this potentially causes it to create new SCEV objects though,
14351 // which technically conflicts with the const qualifier. This isn't
14352 // observable from outside the class though, so casting away the
14353 // const isn't dangerous.
14354 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14355
14356 if (ClassifyExpressions) {
14357 OS << "Classifying expressions for: ";
14358 F.printAsOperand(OS, /*PrintType=*/false);
14359 OS << "\n";
14360 for (Instruction &I : instructions(F))
14361 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14362 OS << I << '\n';
14363 OS << " --> ";
14364 const SCEV *SV = SE.getSCEV(&I);
14365 SV->print(OS);
14366 if (!isa<SCEVCouldNotCompute>(SV)) {
14367 OS << " U: ";
14368 SE.getUnsignedRange(SV).print(OS);
14369 OS << " S: ";
14370 SE.getSignedRange(SV).print(OS);
14371 }
14372
14373 const Loop *L = LI.getLoopFor(I.getParent());
14374
14375 SCEVUse AtUse = SE.getSCEVAtScope(SV, L);
14376 if (AtUse != SV) {
14377 OS << " --> ";
14378 OS << AtUse;
14379 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14380 OS << " U: ";
14381 SE.getUnsignedRange(AtUse).print(OS);
14382 OS << " S: ";
14383 SE.getSignedRange(AtUse).print(OS);
14384 }
14385 }
14386
14387 if (L) {
14388 OS << "\t\t" "Exits: ";
14389 SCEVUse ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14390 if (!SE.isLoopInvariant(ExitValue, L)) {
14391 OS << "<<Unknown>>";
14392 } else {
14393 OS << ExitValue;
14394 }
14395
14396 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14397 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14398 OS << LS;
14399 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14400 OS << ": " << SE.getLoopDisposition(SV, Iter);
14401 }
14402
14403 for (const auto *InnerL : depth_first(L)) {
14404 if (InnerL == L)
14405 continue;
14406 OS << LS;
14407 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14408 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14409 }
14410
14411 OS << " }";
14412 }
14413
14414 OS << "\n";
14415 }
14416 }
14417
14418 OS << "Determining loop execution counts for: ";
14419 F.printAsOperand(OS, /*PrintType=*/false);
14420 OS << "\n";
14421 for (Loop *I : LI)
14422 PrintLoopInfo(OS, &SE, I);
14423}
14424
14427 if (isa<SCEVConstant>(S))
14428 return LoopInvariant;
14429
14430 auto &Values = LoopDispositions[S];
14431 for (auto &V : Values) {
14432 if (V.getPointer() == L)
14433 return V.getInt();
14434 }
14435 Values.emplace_back(L, LoopVariant);
14436 LoopDisposition D = computeLoopDisposition(S, L);
14437 auto &Values2 = LoopDispositions[S];
14438 for (auto &V : llvm::reverse(Values2)) {
14439 if (V.getPointer() == L) {
14440 V.setInt(D);
14441 break;
14442 }
14443 }
14444 return D;
14445}
14446
14448ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14449 switch (S->getSCEVType()) {
14450 case scConstant:
14451 case scVScale:
14452 return LoopInvariant;
14453 case scAddRecExpr: {
14454 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14455
14456 // If L is the addrec's loop, it's computable.
14457 if (AR->getLoop() == L)
14458 return LoopComputable;
14459
14460 // Add recurrences are never invariant in the function-body (null loop).
14461 if (!L)
14462 return LoopVariant;
14463
14464 // Everything that is not defined at loop entry is variant.
14465 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14466 if (L->contains(AR->getLoop()) &&
14467 llvm::all_of(AR->operands(),
14468 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14469 return LoopUniform;
14470
14471 return LoopVariant;
14472 }
14473 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14474 " dominate the contained loop's header?");
14475
14476 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14477 if (AR->getLoop()->contains(L))
14478 return LoopInvariant;
14479
14480 // This recurrence is variant w.r.t. L if any of its operands
14481 // are variant.
14482 for (SCEVUse Op : AR->operands())
14483 if (!isLoopInvariant(Op, L))
14484 return LoopVariant;
14485
14486 // Otherwise it's loop-invariant.
14487 return LoopInvariant;
14488 }
14489 case scTruncate:
14490 case scZeroExtend:
14491 case scSignExtend:
14492 case scPtrToAddr:
14493 case scAddExpr:
14494 case scMulExpr:
14495 case scUDivExpr:
14496 case scUMaxExpr:
14497 case scSMaxExpr:
14498 case scUMinExpr:
14499 case scSMinExpr:
14500 case scSequentialUMinExpr: {
14501 bool HasVarying = false;
14502 bool HasUniform = false;
14503 for (SCEVUse Op : S->operands()) {
14505 if (D == LoopVariant)
14506 return LoopVariant;
14507 if (D == LoopComputable)
14508 HasVarying = true;
14509 if (D == LoopUniform)
14510 HasUniform = true;
14511 }
14512 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14513 : (HasUniform ? LoopUniform : LoopInvariant);
14514 }
14515 case scUnknown:
14516 // All non-instruction values are loop invariant. All instructions are loop
14517 // invariant if they are not contained in the specified loop.
14518 // Instructions are never considered invariant in the function body
14519 // (null loop) because they are defined within the "loop".
14521 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14522 return LoopInvariant;
14523 case scCouldNotCompute:
14524 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14525 }
14526 llvm_unreachable("Unknown SCEV kind!");
14527}
14528
14529bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14531 return D == LoopUniform || D == LoopInvariant;
14532}
14533
14535 return getLoopDisposition(S, L) == LoopInvariant;
14536}
14537
14539 return getLoopDisposition(S, L) == LoopComputable;
14540}
14541
14544 if (isa<SCEVConstant>(S))
14546
14547 auto &Values = BlockDispositions[S];
14548 for (auto &V : Values) {
14549 if (V.getPointer() == BB)
14550 return V.getInt();
14551 }
14552 Values.emplace_back(BB, DoesNotDominateBlock);
14553 BlockDisposition D = computeBlockDisposition(S, BB);
14554 auto &Values2 = BlockDispositions[S];
14555 for (auto &V : llvm::reverse(Values2)) {
14556 if (V.getPointer() == BB) {
14557 V.setInt(D);
14558 break;
14559 }
14560 }
14561 return D;
14562}
14563
14565ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14566 switch (S->getSCEVType()) {
14567 case scConstant:
14568 case scVScale:
14570 case scAddRecExpr: {
14571 // This uses a "dominates" query instead of "properly dominates" query
14572 // to test for proper dominance too, because the instruction which
14573 // produces the addrec's value is a PHI, and a PHI effectively properly
14574 // dominates its entire containing block.
14575 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14576 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14577 return DoesNotDominateBlock;
14578
14579 // Fall through into SCEVNAryExpr handling.
14580 [[fallthrough]];
14581 }
14582 case scTruncate:
14583 case scZeroExtend:
14584 case scSignExtend:
14585 case scPtrToAddr:
14586 case scAddExpr:
14587 case scMulExpr:
14588 case scUDivExpr:
14589 case scUMaxExpr:
14590 case scSMaxExpr:
14591 case scUMinExpr:
14592 case scSMinExpr:
14593 case scSequentialUMinExpr: {
14594 bool Proper = true;
14595 for (const SCEV *NAryOp : S->operands()) {
14597 if (D == DoesNotDominateBlock)
14598 return DoesNotDominateBlock;
14599 if (D == DominatesBlock)
14600 Proper = false;
14601 }
14602 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14603 }
14604 case scUnknown:
14605 if (Instruction *I =
14607 if (I->getParent() == BB)
14608 return DominatesBlock;
14609 if (DT.properlyDominates(I->getParent(), BB))
14611 return DoesNotDominateBlock;
14612 }
14614 case scCouldNotCompute:
14615 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14616 }
14617 llvm_unreachable("Unknown SCEV kind!");
14618}
14619
14620bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14621 return getBlockDisposition(S, BB) >= DominatesBlock;
14622}
14623
14626}
14627
14628void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14629 bool Predicated) {
14630 auto &BECounts =
14631 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14632 auto It = BECounts.find(L);
14633 if (It != BECounts.end()) {
14634 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14635 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14636 if (!isa<SCEVConstant>(S)) {
14637 auto UserIt = BECountUsers.find(S);
14638 assert(UserIt != BECountUsers.end());
14639 UserIt->second.erase({L, Predicated});
14640 }
14641 }
14642 }
14643 BECounts.erase(It);
14644 }
14645}
14646
14647void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14648 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14649 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14650
14651 while (!Worklist.empty()) {
14652 const SCEV *Curr = Worklist.pop_back_val();
14653 auto Users = SCEVUsers.find(Curr);
14654 if (Users != SCEVUsers.end())
14655 for (const auto *User : Users->second)
14656 if (ToForget.insert(User).second)
14657 Worklist.push_back(User);
14658 }
14659
14660 for (const auto *S : ToForget)
14661 forgetMemoizedResultsImpl(S);
14662
14663 PredicatedSCEVRewrites.remove_if(
14664 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14665}
14666
14667void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14668 LoopDispositions.erase(S);
14669 BlockDispositions.erase(S);
14670 UnsignedRanges.erase(S);
14671 SignedRanges.erase(S);
14672 HasRecMap.erase(S);
14673 ConstantMultipleCache.erase(S);
14674
14675 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14676 UnsignedWrapViaInductionTried.erase(AR);
14677 SignedWrapViaInductionTried.erase(AR);
14678 }
14679
14680 auto ExprIt = ExprValueMap.find(S);
14681 if (ExprIt != ExprValueMap.end()) {
14682 for (Value *V : ExprIt->second) {
14683 auto ValueIt = ValueExprMap.find_as(V);
14684 if (ValueIt != ValueExprMap.end())
14685 ValueExprMap.erase(ValueIt);
14686 }
14687 ExprValueMap.erase(ExprIt);
14688 }
14689
14690 auto ScopeIt = ValuesAtScopes.find(S);
14691 if (ScopeIt != ValuesAtScopes.end()) {
14692 for (const auto &Pair : ScopeIt->second)
14693 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14694 llvm::erase(ValuesAtScopesUsers[Pair.second.getPointer()],
14695 std::make_pair(Pair.first, S));
14696 ValuesAtScopes.erase(ScopeIt);
14697 }
14698
14699 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14700 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14701 for (const auto &Pair : ScopeUserIt->second)
14702 // The recorded value at scope is a use of S, which may carry no-wrap
14703 // flags that are not part of this key.
14704 llvm::erase_if(ValuesAtScopes[Pair.second], [&](const auto &LS) {
14705 return LS.first == Pair.first && LS.second.getPointer() == S;
14706 });
14707 ValuesAtScopesUsers.erase(ScopeUserIt);
14708 }
14709
14710 auto BEUsersIt = BECountUsers.find(S);
14711 if (BEUsersIt != BECountUsers.end()) {
14712 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14713 auto Copy = BEUsersIt->second;
14714 for (const auto &Pair : Copy)
14715 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14716 BECountUsers.erase(BEUsersIt);
14717 }
14718
14719 auto FoldUser = FoldCacheUser.find(S);
14720 if (FoldUser != FoldCacheUser.end())
14721 for (auto &KV : FoldUser->second)
14722 FoldCache.erase(KV);
14723 FoldCacheUser.erase(S);
14724}
14725
14726void
14727ScalarEvolution::getUsedLoops(const SCEV *S,
14728 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14729 struct FindUsedLoops {
14730 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14731 : LoopsUsed(LoopsUsed) {}
14732 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14733 bool follow(const SCEV *S) {
14734 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14735 LoopsUsed.insert(AR->getLoop());
14736 return true;
14737 }
14738
14739 bool isDone() const { return false; }
14740 };
14741
14742 FindUsedLoops F(LoopsUsed);
14743 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14744}
14745
14746void ScalarEvolution::getReachableBlocks(
14749 Worklist.push_back(&F.getEntryBlock());
14750 while (!Worklist.empty()) {
14751 BasicBlock *BB = Worklist.pop_back_val();
14752 if (!Reachable.insert(BB).second)
14753 continue;
14754
14755 Value *Cond;
14756 BasicBlock *TrueBB, *FalseBB;
14757 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14758 m_BasicBlock(FalseBB)))) {
14759 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14760 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14761 continue;
14762 }
14763
14764 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14765 const SCEV *L = getSCEV(Cmp->getOperand(0));
14766 const SCEV *R = getSCEV(Cmp->getOperand(1));
14767 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14768 Worklist.push_back(TrueBB);
14769 continue;
14770 }
14771 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14772 R)) {
14773 Worklist.push_back(FalseBB);
14774 continue;
14775 }
14776 }
14777 }
14778
14779 append_range(Worklist, successors(BB));
14780 }
14781}
14782
14784 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14785 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14786
14787 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14788
14789 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14790 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14791 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14792
14793 const SCEV *visitConstant(const SCEVConstant *Constant) {
14794 return SE.getConstant(Constant->getAPInt());
14795 }
14796
14797 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14798 return SE.getUnknown(Expr->getValue());
14799 }
14800
14801 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14802 return SE.getCouldNotCompute();
14803 }
14804 };
14805
14806 SCEVMapper SCM(SE2);
14807 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14808 SE2.getReachableBlocks(ReachableBlocks, F);
14809
14810 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14811 if (containsUndefs(Old) || containsUndefs(New)) {
14812 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14813 // not propagate undef aggressively). This means we can (and do) fail
14814 // verification in cases where a transform makes a value go from "undef"
14815 // to "undef+1" (say). The transform is fine, since in both cases the
14816 // result is "undef", but SCEV thinks the value increased by 1.
14817 return nullptr;
14818 }
14819
14820 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14821 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14822 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14823 return nullptr;
14824
14825 return Delta;
14826 };
14827
14828 while (!LoopStack.empty()) {
14829 auto *L = LoopStack.pop_back_val();
14830 llvm::append_range(LoopStack, *L);
14831
14832 // Only verify BECounts in reachable loops. For an unreachable loop,
14833 // any BECount is legal.
14834 if (!ReachableBlocks.contains(L->getHeader()))
14835 continue;
14836
14837 // Only verify cached BECounts. Computing new BECounts may change the
14838 // results of subsequent SCEV uses.
14839 auto It = BackedgeTakenCounts.find(L);
14840 if (It == BackedgeTakenCounts.end())
14841 continue;
14842
14843 auto *CurBECount =
14844 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14845 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14846
14847 if (CurBECount == SE2.getCouldNotCompute() ||
14848 NewBECount == SE2.getCouldNotCompute()) {
14849 // NB! This situation is legal, but is very suspicious -- whatever pass
14850 // change the loop to make a trip count go from could not compute to
14851 // computable or vice-versa *should have* invalidated SCEV. However, we
14852 // choose not to assert here (for now) since we don't want false
14853 // positives.
14854 continue;
14855 }
14856
14857 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14858 SE.getTypeSizeInBits(NewBECount->getType()))
14859 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14860 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14861 SE.getTypeSizeInBits(NewBECount->getType()))
14862 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14863
14864 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14865 if (Delta && !Delta->isZero()) {
14866 dbgs() << "Trip Count for " << *L << " Changed!\n";
14867 dbgs() << "Old: " << *CurBECount << "\n";
14868 dbgs() << "New: " << *NewBECount << "\n";
14869 dbgs() << "Delta: " << *Delta << "\n";
14870 std::abort();
14871 }
14872 }
14873
14874 // Collect all valid loops currently in LoopInfo.
14875 SmallPtrSet<Loop *, 32> ValidLoops;
14876 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14877 while (!Worklist.empty()) {
14878 Loop *L = Worklist.pop_back_val();
14879 if (ValidLoops.insert(L).second)
14880 Worklist.append(L->begin(), L->end());
14881 }
14882 for (const auto &KV : ValueExprMap) {
14883#ifndef NDEBUG
14884 // Check for SCEV expressions referencing invalid/deleted loops.
14885 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14886 assert(ValidLoops.contains(AR->getLoop()) &&
14887 "AddRec references invalid loop");
14888 }
14889#endif
14890
14891 // Check that the value is also part of the reverse map.
14892 auto It = ExprValueMap.find(KV.second);
14893 if (It == ExprValueMap.end() || !is_contained(It->second, KV.first)) {
14894 dbgs() << "Value " << *KV.first
14895 << " is in ValueExprMap but not in ExprValueMap\n";
14896 std::abort();
14897 }
14898
14899 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14900 if (!ReachableBlocks.contains(I->getParent()))
14901 continue;
14902 const SCEV *OldSCEV = SCM.visit(KV.second);
14903 const SCEV *NewSCEV = SE2.getSCEV(I);
14904 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14905 if (Delta && !Delta->isZero()) {
14906 dbgs() << "SCEV for value " << *I << " changed!\n"
14907 << "Old: " << *OldSCEV << "\n"
14908 << "New: " << *NewSCEV << "\n"
14909 << "Delta: " << *Delta << "\n";
14910 std::abort();
14911 }
14912 }
14913 }
14914
14915 for (const auto &KV : ExprValueMap) {
14916 for (Value *V : KV.second) {
14917 const SCEV *S = ValueExprMap.lookup(V);
14918 if (!S) {
14919 dbgs() << "Value " << *V
14920 << " is in ExprValueMap but not in ValueExprMap\n";
14921 std::abort();
14922 }
14923 if (S != KV.first) {
14924 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
14925 << *KV.first << "\n";
14926 std::abort();
14927 }
14928 }
14929 }
14930
14931 // Verify integrity of SCEV users.
14932 for (const auto &S : UniqueSCEVs) {
14933 for (SCEVUse Op : S.operands()) {
14934 // We do not store dependencies of constants.
14935 if (isa<SCEVConstant>(Op))
14936 continue;
14937 auto It = SCEVUsers.find(Op);
14938 if (It != SCEVUsers.end() && It->second.count(&S))
14939 continue;
14940 dbgs() << "Use of operand " << *Op << " by user " << S
14941 << " is not being tracked!\n";
14942 std::abort();
14943 }
14944 }
14945
14946 // Verify integrity of ValuesAtScopes users.
14947 for (const auto &ValueAndVec : ValuesAtScopes) {
14948 const SCEV *Value = ValueAndVec.first;
14949 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
14950 const Loop *L = LoopAndValueAtScope.first;
14951 SCEVUse ValueAtScope = LoopAndValueAtScope.second;
14952 if (!isa<SCEVConstant>(ValueAtScope)) {
14953 auto It = ValuesAtScopesUsers.find(ValueAtScope.getPointer());
14954 if (It != ValuesAtScopesUsers.end() &&
14955 is_contained(It->second, std::make_pair(L, Value)))
14956 continue;
14957 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14958 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
14959 std::abort();
14960 }
14961 }
14962 }
14963
14964 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
14965 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
14966 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
14967 const Loop *L = LoopAndValue.first;
14968 const SCEV *Value = LoopAndValue.second;
14970 auto It = ValuesAtScopes.find(Value);
14971 // The recorded value at scope may carry no-wrap flags that are not part
14972 // of the key it is recorded under.
14973 if (It != ValuesAtScopes.end() && any_of(It->second, [&](const auto &LS) {
14974 return LS.first == L && LS.second.getPointer() == ValueAtScope;
14975 }))
14976 continue;
14977 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
14978 << *ValueAtScope << " missing in ValuesAtScopes\n";
14979 std::abort();
14980 }
14981 }
14982
14983 // Verify integrity of BECountUsers.
14984 auto VerifyBECountUsers = [&](bool Predicated) {
14985 auto &BECounts =
14986 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14987 for (const auto &LoopAndBEInfo : BECounts) {
14988 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
14989 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14990 if (!isa<SCEVConstant>(S)) {
14991 auto UserIt = BECountUsers.find(S);
14992 if (UserIt != BECountUsers.end() &&
14993 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
14994 continue;
14995 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
14996 << " missing from BECountUsers\n";
14997 std::abort();
14998 }
14999 }
15000 }
15001 }
15002 };
15003 VerifyBECountUsers(/* Predicated */ false);
15004 VerifyBECountUsers(/* Predicated */ true);
15005
15006 // Verify intergity of loop disposition cache.
15007 for (auto &[S, Values] : LoopDispositions) {
15008 for (auto [Loop, CachedDisposition] : Values) {
15009 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15010 if (CachedDisposition != RecomputedDisposition) {
15011 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15012 << " is incorrect: cached " << CachedDisposition << ", actual "
15013 << RecomputedDisposition << "\n";
15014 std::abort();
15015 }
15016 }
15017 }
15018
15019 // Verify integrity of the block disposition cache.
15020 for (auto &[S, Values] : BlockDispositions) {
15021 for (auto [BB, CachedDisposition] : Values) {
15022 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15023 if (CachedDisposition != RecomputedDisposition) {
15024 dbgs() << "Cached disposition of " << *S << " for block %"
15025 << BB->getName() << " is incorrect: cached " << CachedDisposition
15026 << ", actual " << RecomputedDisposition << "\n";
15027 std::abort();
15028 }
15029 }
15030 }
15031
15032 // Verify FoldCache/FoldCacheUser caches.
15033 for (auto [FoldID, Expr] : FoldCache) {
15034 auto I = FoldCacheUser.find(Expr);
15035 if (I == FoldCacheUser.end()) {
15036 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15037 << "!\n";
15038 std::abort();
15039 }
15040 if (!is_contained(I->second, FoldID)) {
15041 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15042 std::abort();
15043 }
15044 }
15045 for (auto [Expr, IDs] : FoldCacheUser) {
15046 for (auto &FoldID : IDs) {
15047 const SCEV *S = FoldCache.lookup(FoldID);
15048 if (!S) {
15049 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15050 << "!\n";
15051 std::abort();
15052 }
15053 if (S != Expr) {
15054 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15055 << " != " << *Expr << "!\n";
15056 std::abort();
15057 }
15058 }
15059 }
15060
15061 // Verify that ConstantMultipleCache computations are correct. We check that
15062 // cached multiples and recomputed multiples are multiples of each other to
15063 // verify correctness. It is possible that a recomputed multiple is different
15064 // from the cached multiple due to strengthened no wrap flags or changes in
15065 // KnownBits computations.
15066 for (auto [S, Multiple] : ConstantMultipleCache) {
15067 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15068 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15069 Multiple.urem(RecomputedMultiple) != 0 &&
15070 RecomputedMultiple.urem(Multiple) != 0)) {
15071 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15072 << *S << " : Computed " << RecomputedMultiple
15073 << " but cache contains " << Multiple << "!\n";
15074 std::abort();
15075 }
15076 }
15077}
15078
15080 Function &F, const PreservedAnalyses &PA,
15081 FunctionAnalysisManager::Invalidator &Inv) {
15082 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15083 // of its dependencies is invalidated.
15084 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15085 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15086 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15087 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15088 Inv.invalidate<LoopAnalysis>(F, PA);
15089}
15090
15091AnalysisKey ScalarEvolutionAnalysis::Key;
15092
15095 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15096 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15097 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15098 auto &LI = AM.getResult<LoopAnalysis>(F);
15099 return ScalarEvolution(F, TLI, AC, DT, LI);
15100}
15101
15107
15110 // For compatibility with opt's -analyze feature under legacy pass manager
15111 // which was not ported to NPM. This keeps tests using
15112 // update_analyze_test_checks.py working.
15113 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15114 << F.getName() << "':\n";
15116 return PreservedAnalyses::all();
15117}
15118
15120 "Scalar Evolution Analysis", false, true)
15126 "Scalar Evolution Analysis", false, true)
15127
15128char ScalarEvolutionWrapperPass::ID = 0;
15129
15131
15133 SE.reset(new ScalarEvolution(
15135 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15137 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15138 return false;
15139}
15140
15142
15144 SE->print(OS);
15145}
15146
15148 if (!VerifySCEV)
15149 return;
15150
15151 SE->verify();
15152}
15153
15161
15163 const SCEV *RHS) {
15164 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15165}
15166
15167const SCEVPredicate *
15169 const SCEV *LHS, const SCEV *RHS) {
15171 assert(LHS->getType() == RHS->getType() &&
15172 "Type mismatch between LHS and RHS");
15173 // Unique this node based on the arguments
15174 ID.AddInteger(SCEVPredicate::P_Compare);
15175 ID.AddInteger(Pred);
15176 ID.AddPointer(LHS);
15177 ID.AddPointer(RHS);
15179 if (const auto *S = UniquePreds.lookup(ID, Token))
15180 return S;
15181 SCEVComparePredicate *Eq = new (SCEVAllocator)
15182 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15183 UniquePreds.insert(Eq, Token);
15184 return Eq;
15185}
15186
15188 const SCEVAddRecExpr *AR,
15191 // Unique this node based on the arguments
15193 ID.AddPointer(AR);
15194 ID.AddInteger(AddedFlags);
15196 if (const auto *S = UniquePreds.lookup(ID, Token))
15197 return S;
15198 auto *OF = new (SCEVAllocator)
15199 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15200 UniquePreds.insert(OF, Token);
15201 return OF;
15202}
15203
15204namespace {
15205
15206class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15207public:
15208
15209 /// Rewrites \p S in the context of a loop L and the SCEV predication
15210 /// infrastructure.
15211 ///
15212 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15213 /// equivalences present in \p Pred.
15214 ///
15215 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15216 /// \p NewPreds such that the result will be an AddRecExpr.
15217 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15219 const SCEVPredicate *Pred) {
15220 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15221 return Rewriter.visit(S);
15222 }
15223
15224 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15225 if (Pred) {
15226 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15227 for (const auto *Pred : U->getPredicates())
15228 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15229 if (IPred->getLHS() == Expr &&
15230 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15231 return IPred->getRHS();
15232 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15233 if (IPred->getLHS() == Expr &&
15234 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15235 return IPred->getRHS();
15236 }
15237 }
15238 return convertToAddRecWithPreds(Expr);
15239 }
15240
15241 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15242 const SCEV *Operand = visit(Expr->getOperand());
15243 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15244 if (AR && AR->getLoop() == L && AR->isAffine()) {
15245 // This couldn't be folded because the operand didn't have the nuw
15246 // flag. Add the nusw flag as an assumption that we could make.
15247 const SCEV *Step = AR->getStepRecurrence(SE);
15248 Type *Ty = Expr->getType();
15249 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15250 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15251 SE.getSignExtendExpr(Step, Ty), L,
15252 AR->getNoWrapFlags());
15253 }
15254 return SE.getZeroExtendExpr(Operand, Expr->getType());
15255 }
15256
15257 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15258 const SCEV *Operand = visit(Expr->getOperand());
15259 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15260 if (AR && AR->getLoop() == L && AR->isAffine()) {
15261 // This couldn't be folded because the operand didn't have the nsw
15262 // flag. Add the nssw flag as an assumption that we could make.
15263 const SCEV *Step = AR->getStepRecurrence(SE);
15264 Type *Ty = Expr->getType();
15265 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15266 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15267 SE.getSignExtendExpr(Step, Ty), L,
15268 AR->getNoWrapFlags());
15269 }
15270 return SE.getSignExtendExpr(Operand, Expr->getType());
15271 }
15272
15273private:
15274 explicit SCEVPredicateRewriter(
15275 const Loop *L, ScalarEvolution &SE,
15276 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15277 const SCEVPredicate *Pred)
15278 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15279
15280 bool addOverflowAssumption(const SCEVPredicate *P) {
15281 if (!NewPreds) {
15282 // Check if we've already made this assumption.
15283 return Pred && Pred->implies(P, SE);
15284 }
15285 NewPreds->push_back(P);
15286 return true;
15287 }
15288
15289 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15291 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15292 return addOverflowAssumption(A);
15293 }
15294
15295 // If \p Expr represents a PHINode, we try to see if it can be represented
15296 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15297 // to add this predicate as a runtime overflow check, we return the AddRec.
15298 // If \p Expr does not meet these conditions (is not a PHI node, or we
15299 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15300 // return \p Expr.
15301 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15302 if (!isa<PHINode>(Expr->getValue()))
15303 return Expr;
15304 std::optional<
15305 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15306 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15307 if (!PredicatedRewrite)
15308 return Expr;
15309 for (const auto *P : PredicatedRewrite->second){
15310 // Wrap predicates from outer loops are not supported.
15311 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15312 if (L != WP->getExpr()->getLoop())
15313 return Expr;
15314 }
15315 if (!addOverflowAssumption(P))
15316 return Expr;
15317 }
15318 return PredicatedRewrite->first;
15319 }
15320
15321 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15322 const SCEVPredicate *Pred;
15323 const Loop *L;
15324};
15325
15326} // end anonymous namespace
15327
15328const SCEV *
15330 const SCEVPredicate &Preds) {
15331 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15332}
15333
15335 const SCEV *S, const Loop *L,
15338 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15339 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15340
15341 if (!AddRec)
15342 return nullptr;
15343
15344 // Check if any of the transformed predicates is known to be false. In that
15345 // case, it doesn't make sense to convert to a predicated AddRec, as the
15346 // versioned loop will never execute.
15347 for (const SCEVPredicate *Pred : TransformPreds) {
15348 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15349 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15350 continue;
15351
15352 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15353 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15354 if (isa<SCEVCouldNotCompute>(ExitCount))
15355 continue;
15356
15357 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15358 if (!Step->isOne())
15359 continue;
15360
15361 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15362 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15363 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15364 return nullptr;
15365 }
15366
15367 // Since the transformation was successful, we can now transfer the SCEV
15368 // predicates.
15369 Preds.append(TransformPreds.begin(), TransformPreds.end());
15370
15371 return AddRec;
15372}
15373
15374/// SCEV predicates
15378
15380 const ICmpInst::Predicate Pred,
15381 const SCEV *LHS, const SCEV *RHS)
15382 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15383 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15384 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15385}
15386
15388 ScalarEvolution &SE) const {
15389 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15390
15391 if (!Op)
15392 return false;
15393
15394 if (Pred != ICmpInst::ICMP_EQ)
15395 return false;
15396
15397 return Op->LHS == LHS && Op->RHS == RHS;
15398}
15399
15400bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15401
15403 if (Pred == ICmpInst::ICMP_EQ)
15404 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15405 else
15406 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15407 << *RHS << "\n";
15408
15409}
15410
15412 const SCEVAddRecExpr *AR,
15413 IncrementWrapFlags Flags)
15414 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15415
15416const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15417
15419 ScalarEvolution &SE) const {
15420 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15421 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15422 return false;
15423
15424 if (Op->AR == AR)
15425 return true;
15426
15427 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15429 return false;
15430
15431 const SCEV *Start = AR->getStart();
15432 const SCEV *OpStart = Op->AR->getStart();
15433 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15434 return false;
15435
15436 // Reject pointers to different address spaces.
15437 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15438 return false;
15439
15440 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15441 // narrower-type AddRec.
15442 if (SE.getTypeSizeInBits(AR->getType()) >
15443 SE.getTypeSizeInBits(Op->AR->getType()))
15444 return false;
15445
15446 const SCEV *Step = AR->getStepRecurrence(SE);
15447 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15448 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15449 return false;
15450
15451 // If both steps are positive, this implies N, if N's start and step are
15452 // ULE/SLE (for NSUW/NSSW) than this'.
15453 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15454 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15455 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15456
15457 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15458 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15459 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15460 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15461 : SE.getNoopOrSignExtend(Start, WiderTy);
15463 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15464 SE.isKnownPredicate(Pred, OpStart, Start);
15465}
15466
15468 SCEVFlags ScevFlags = AR->getNoWrapFlags();
15469 IncrementWrapFlags IFlags = Flags;
15470
15471 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15472 IFlags = clearFlags(IFlags, IncrementNSSW);
15473
15474 return IFlags == IncrementAnyWrap;
15475}
15476
15477void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15478 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15480 OS << "<nusw>";
15482 OS << "<nssw>";
15483 OS << "\n";
15484}
15485
15486/// Union predicates don't get cached so create a dummy set ID for it.
15488 ScalarEvolution &SE)
15490 for (const auto *P : Preds)
15491 add(P, SE);
15492}
15493
15495 return all_of(Preds,
15496 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15497}
15498
15500 ScalarEvolution &SE) const {
15501 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15502 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15503 return this->implies(I, SE);
15504 });
15505
15506 if (any_of(Preds,
15507 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15508 return true;
15509
15510 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15511 // equal predicates.
15512 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15513 if (!NWrap)
15514 return false;
15515 const Loop *L = NWrap->getExpr()->getLoop();
15516 return any_of(Preds, [&](const SCEVPredicate *I) {
15517 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15518 if (!IWrap)
15519 return false;
15520 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15521 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15522 return RewrittenAR &&
15523 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15524 });
15525}
15526
15528 for (const auto *Pred : Preds)
15529 Pred->print(OS, Depth);
15530}
15531
15532void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15533 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15534 for (const auto *Pred : Set->Preds)
15535 add(Pred, SE);
15536 return;
15537 }
15538
15539 // Implication checks are quadratic in the number of predicates. Stop doing
15540 // them if there are many predicates, as they should be too expensive to use
15541 // anyway at that point.
15542 bool CheckImplies = Preds.size() < 16;
15543
15544 // Only add predicate if it is not already implied by this union predicate.
15545 if (CheckImplies && implies(N, SE))
15546 return;
15547
15548 // Build a new vector containing the current predicates, except the ones that
15549 // are implied by the new predicate N.
15551 for (auto *P : Preds) {
15552 if (CheckImplies && N->implies(P, SE))
15553 continue;
15554 PrunedPreds.push_back(P);
15555 }
15556 Preds = std::move(PrunedPreds);
15557 Preds.push_back(N);
15558}
15559
15561 Loop &L)
15562 : SE(SE), L(L) {
15564 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15565}
15566
15568 for (const SCEV *Op : Ops)
15569 // We do not expect that forgetting cached data for SCEVConstants will ever
15570 // open any prospects for sharpening or introduce any correctness issues,
15571 // so we don't bother storing their dependencies.
15572 if (!isa<SCEVConstant>(Op))
15573 SCEVUsers[Op].insert(User);
15574}
15575
15577 const SCEV *Expr = SE.getSCEV(V);
15578 return getPredicatedSCEV(Expr);
15579}
15580
15582 RewriteEntry &Entry = RewriteMap[Expr];
15583
15584 // If we already have an entry and the version matches, return it.
15585 if (Entry.second && Generation == Entry.first)
15586 return Entry.second;
15587
15588 // We found an entry but it's stale. Rewrite the stale entry
15589 // according to the current predicate.
15590 if (Entry.second)
15591 Expr = Entry.second;
15592
15593 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15594 Entry = {Generation, NewSCEV};
15595
15596 return NewSCEV;
15597}
15598
15600 if (!BackedgeCount) {
15602 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15603 for (const auto *P : Preds)
15604 addPredicate(*P);
15605 }
15606 return BackedgeCount;
15607}
15608
15610 if (!SymbolicMaxBackedgeCount) {
15612 SymbolicMaxBackedgeCount =
15613 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15614 for (const auto *P : Preds)
15615 addPredicate(*P);
15616 }
15617 return SymbolicMaxBackedgeCount;
15618}
15619
15621 if (!SmallConstantMaxTripCount) {
15623 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15624 for (const auto *P : Preds)
15625 addPredicate(*P);
15626 }
15627 return *SmallConstantMaxTripCount;
15628}
15629
15631 if (Preds->implies(&Pred, SE))
15632 return;
15633
15634 Preds = std::make_unique<SCEVUnionPredicate>(Preds->getUnionWith(&Pred, SE));
15635 updateGeneration();
15636}
15637
15640 for (const SCEVPredicate *P : Preds)
15641 addPredicate(*P);
15642}
15643
15645 return *Preds;
15646}
15647
15648void PredicatedScalarEvolution::updateGeneration() {
15649 // If the generation number wrapped recompute everything.
15650 if (++Generation == 0) {
15651 for (auto &II : RewriteMap) {
15652 const SCEV *Rewritten = II.second.second;
15653 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15654 }
15655 }
15656}
15657
15660 const SCEV *Expr = this->getSCEV(V);
15662 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15663
15664 if (!New)
15665 return nullptr;
15666
15667 if (ExtraPreds) {
15668 ExtraPreds->append(NewPreds);
15669 return New;
15670 }
15671
15672 addPredicates(NewPreds);
15673
15674 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15675 return New;
15676}
15677
15680 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15681 Preds(std::make_unique<SCEVUnionPredicate>(*Init.Preds)),
15682 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15683
15685 // For each block.
15686 for (auto *BB : L.getBlocks())
15687 for (auto &I : *BB) {
15688 if (!SE.isSCEVable(I.getType()))
15689 continue;
15690
15691 auto *Expr = SE.getSCEV(&I);
15692 auto II = RewriteMap.find(Expr);
15693
15694 if (II == RewriteMap.end())
15695 continue;
15696
15697 // Don't print things that are not interesting.
15698 if (II->second.second == Expr)
15699 continue;
15700
15701 OS.indent(Depth) << "[PSE]" << I << ":\n";
15702 OS.indent(Depth + 2) << *Expr << "\n";
15703 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15704 }
15705}
15706
15707void ScalarEvolution::LoopGuards::collectPending() {
15708 const Loop *L = PendingLoop;
15709 if (!L)
15710 return;
15711 PendingLoop = nullptr;
15712 BasicBlock *Pred = L->getLoopPredecessor();
15713 if (!Pred)
15714 return;
15716 collectFromBlock(SE, *this, L->getHeader(), Pred, VisitedBlocks);
15717}
15718
15719void ScalarEvolution::LoopGuards::collectFromPHI(
15723 unsigned Depth) {
15724 if (!SE.isSCEVable(Phi.getType()))
15725 return;
15726
15727 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15728 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15729 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15730 if (!VisitedBlocks.insert(InBlock).second)
15731 return {nullptr, scCouldNotCompute};
15732
15733 // Avoid analyzing unreachable blocks so that we don't get trapped
15734 // traversing cycles with ill-formed dominance or infinite cycles
15735 if (!SE.DT.isReachableFromEntry(InBlock))
15736 return {nullptr, scCouldNotCompute};
15737
15738 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15739 if (Inserted)
15740 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15741 Depth + 1);
15742 auto &RewriteMap = G->second.RewriteMap;
15743 if (RewriteMap.empty())
15744 return {nullptr, scCouldNotCompute};
15745 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15746 if (S == RewriteMap.end())
15747 return {nullptr, scCouldNotCompute};
15748 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15749 if (!SM)
15750 return {nullptr, scCouldNotCompute};
15751 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15752 return {C0, SM->getSCEVType()};
15753 return {nullptr, scCouldNotCompute};
15754 };
15755 auto MergeMinMaxConst = [](MinMaxPattern P1,
15756 MinMaxPattern P2) -> MinMaxPattern {
15757 auto [C1, T1] = P1;
15758 auto [C2, T2] = P2;
15759 if (!C1 || !C2 || T1 != T2)
15760 return {nullptr, scCouldNotCompute};
15761 switch (T1) {
15762 case scUMaxExpr:
15763 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15764 case scSMaxExpr:
15765 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15766 case scUMinExpr:
15767 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15768 case scSMinExpr:
15769 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15770 default:
15771 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15772 }
15773 };
15774 auto P = GetMinMaxConst(0);
15775 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15776 if (!P.first)
15777 break;
15778 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15779 }
15780 if (P.first) {
15781 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15782 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15783 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15784 Guards.RewriteMap.insert({LHS, RHS});
15785 }
15786}
15787
15788// Return a new SCEV that modifies \p Expr to the closest number divides by
15789// \p Divisor and less or equal than Expr. For now, only handle constant
15790// Expr.
15792 const APInt &DivisorVal,
15793 ScalarEvolution &SE) {
15794 const APInt *ExprVal;
15795 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15796 DivisorVal.isNonPositive())
15797 return Expr;
15798 APInt Rem = ExprVal->urem(DivisorVal);
15799 // return the SCEV: Expr - Expr % Divisor
15800 return SE.getConstant(*ExprVal - Rem);
15801}
15802
15803// Return a new SCEV that modifies \p Expr to the closest number divides by
15804// \p Divisor and greater or equal than Expr. For now, only handle constant
15805// Expr.
15806static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15807 const APInt &DivisorVal,
15808 ScalarEvolution &SE) {
15809 const APInt *ExprVal;
15810 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15811 DivisorVal.isNonPositive())
15812 return Expr;
15813 APInt Rem = ExprVal->urem(DivisorVal);
15814 if (Rem.isZero())
15815 return Expr;
15816 // return the SCEV: Expr + Divisor - Expr % Divisor
15817 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15818}
15819
15821 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15824 // If we have LHS == 0, check if LHS is computing a property of some unknown
15825 // SCEV %v which we can rewrite %v to express explicitly.
15827 return false;
15828 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15829 // explicitly express that.
15830 const SCEVUnknown *URemLHS = nullptr;
15831 const SCEV *URemRHS = nullptr;
15832 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15833 return false;
15834
15835 const SCEV *Multiple =
15836 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15837 DivInfo[URemLHS] = Multiple;
15838 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15839 Multiples[URemLHS] = C->getAPInt();
15840 return true;
15841}
15842
15843// Check if the condition is a divisibility guard (A % B == 0).
15844static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15845 ScalarEvolution &SE) {
15846 const SCEV *X, *Y;
15847 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15848}
15849
15850// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15851// recursively. This is done by aligning up/down the constant value to the
15852// Divisor.
15853static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15854 APInt Divisor,
15855 ScalarEvolution &SE) {
15856 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15857 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15858 // the non-constant operand and in \p LHS the constant operand.
15859 auto IsMinMaxSCEVWithNonNegativeConstant =
15860 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15861 const SCEV *&RHS) {
15862 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15863 if (MinMax->getNumOperands() != 2)
15864 return false;
15865 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15866 if (C->getAPInt().isNegative())
15867 return false;
15868 SCTy = MinMax->getSCEVType();
15869 LHS = MinMax->getOperand(0);
15870 RHS = MinMax->getOperand(1);
15871 return true;
15872 }
15873 }
15874 return false;
15875 };
15876
15877 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
15878 SCEVTypes SCTy;
15879 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
15880 MinMaxRHS))
15881 return MinMaxExpr;
15882 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
15883 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
15884 auto *DivisibleExpr =
15885 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
15886 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
15888 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
15889 return SE.getMinMaxExpr(SCTy, Ops);
15890}
15891
15892void ScalarEvolution::LoopGuards::collectFromBlock(
15893 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
15894 const BasicBlock *Block, const BasicBlock *Pred,
15895 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
15896
15898
15899 SmallVector<SCEVUse> ExprsToRewrite;
15900 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
15901 const SCEV *RHS,
15902 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
15903 const LoopGuards &DivGuards) {
15904 // WARNING: It is generally unsound to apply any wrap flags to the proposed
15905 // replacement SCEV which isn't directly implied by the structure of that
15906 // SCEV. In particular, using contextual facts to imply flags is *NOT*
15907 // legal. See the scoping rules for flags in the header to understand why.
15908
15909 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
15910 // and \p FromRewritten are the same (i.e. there has been no rewrite
15911 // registered for \p From), then puts this value in the list of rewritten
15912 // expressions.
15913 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
15914 const SCEV *To) {
15915 if (From == FromRewritten)
15916 ExprsToRewrite.push_back(From);
15917 RewriteMap[From] = To;
15918 };
15919
15920 // Checks whether \p S has already been rewritten. In that case returns the
15921 // existing rewrite because we want to chain further rewrites onto the
15922 // already rewritten value. Otherwise returns \p S.
15923 auto GetMaybeRewritten = [&](const SCEV *S) {
15924 return RewriteMap.lookup_or(S, S);
15925 };
15926
15927 // Check for a condition of the form (-C1 + X < C2). InstCombine will
15928 // create this form when combining two checks of the form (X u< C2 + C1) and
15929 // (X >=u C1).
15930 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
15931 const SCEV *MatchLHS,
15932 const SCEV *MatchRHS) {
15933 const SCEVConstant *C1;
15934 const SCEVUnknown *LHSUnknown;
15935 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
15936 if (!match(MatchLHS,
15937 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
15938 !C2)
15939 return false;
15940
15941 auto ExactRegion =
15942 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
15943 .sub(C1->getAPInt());
15944
15945 // Tighten the raw range with what we already know about LHSUnknown
15946 // from prior guards recorded in RewriteMap, or from SCEV's own range
15947 // analysis.
15948 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
15949 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
15951
15952 // Bail if the guard is inconsistent with prior facts, or if the range
15953 // is still not a monotonic non-wrapping interval after tightening.
15954 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
15955 ExactRegion.isFullSet())
15956 return false;
15957
15958 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
15959 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
15960 const SCEV *ClampedLHS =
15961 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
15962 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
15963 return true;
15964 };
15965 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
15966 return;
15967
15968 // Do not apply information for constants or if RHS contains an AddRec.
15970 return;
15971
15972 // If RHS is SCEVUnknown, make sure the information is applied to it.
15974 std::swap(LHS, RHS);
15976 }
15977
15978 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
15979 // Apply divisibility information when computing the constant multiple.
15980 const APInt &DividesBy =
15981 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
15982
15983 // Collect rewrites for LHS and its transitive operands based on the
15984 // condition.
15985 // For min/max expressions, also apply the guard to its operands:
15986 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
15987 // 'min(a, b) > c' -> '(a > c) and (b > c)',
15988 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
15989 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
15990
15991 // We cannot express strict predicates in SCEV, so instead we replace them
15992 // with non-strict ones against plus or minus one of RHS depending on the
15993 // predicate.
15994 const SCEV *One = SE.getOne(RHS->getType());
15995 switch (Predicate) {
15996 case CmpInst::ICMP_ULT:
15997 if (RHS->getType()->isPointerTy())
15998 return;
15999 RHS = SE.getUMaxExpr(RHS, One);
16000 [[fallthrough]];
16001 case CmpInst::ICMP_SLT: {
16002 RHS = SE.getMinusSCEV(RHS, One);
16003 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16004 break;
16005 }
16006 case CmpInst::ICMP_UGT:
16007 case CmpInst::ICMP_SGT:
16008 RHS = SE.getAddExpr(RHS, One);
16009 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16010 break;
16011 case CmpInst::ICMP_ULE:
16012 case CmpInst::ICMP_SLE:
16013 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16014 break;
16015 case CmpInst::ICMP_UGE:
16016 case CmpInst::ICMP_SGE:
16017 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16018 break;
16019 default:
16020 break;
16021 }
16022
16023 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16024 SmallPtrSet<const SCEV *, 16> Visited;
16025
16026 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16027 append_range(Worklist, S->operands());
16028 };
16029
16030 while (!Worklist.empty()) {
16031 const SCEV *From = Worklist.pop_back_val();
16032 if (isa<SCEVConstant>(From))
16033 continue;
16034 if (!Visited.insert(From).second)
16035 continue;
16036 const SCEV *FromRewritten = GetMaybeRewritten(From);
16037 const SCEV *To = nullptr;
16038
16039 switch (Predicate) {
16040 case CmpInst::ICMP_ULT:
16041 case CmpInst::ICMP_ULE:
16042 To = SE.getUMinExpr(FromRewritten, RHS);
16043 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16044 EnqueueOperands(UMax);
16045 break;
16046 case CmpInst::ICMP_SLT:
16047 case CmpInst::ICMP_SLE:
16048 To = SE.getSMinExpr(FromRewritten, RHS);
16049 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16050 EnqueueOperands(SMax);
16051 break;
16052 case CmpInst::ICMP_UGT:
16053 case CmpInst::ICMP_UGE:
16054 To = SE.getUMaxExpr(FromRewritten, RHS);
16055 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16056 EnqueueOperands(UMin);
16057 break;
16058 case CmpInst::ICMP_SGT:
16059 case CmpInst::ICMP_SGE:
16060 To = SE.getSMaxExpr(FromRewritten, RHS);
16061 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16062 EnqueueOperands(SMin);
16063 break;
16064 case CmpInst::ICMP_EQ:
16066 To = RHS;
16067 break;
16068 case CmpInst::ICMP_NE:
16069 if (match(RHS, m_scev_Zero())) {
16070 const SCEV *OneAlignedUp =
16071 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16072 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16073 } else {
16074 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16075 // but creating the subtraction eagerly is expensive. Track the
16076 // inequalities in a separate map, and materialize the rewrite lazily
16077 // when encountering a suitable subtraction while re-writing.
16078 if (LHS->getType()->isPointerTy()) {
16079 LHS = SE.getPtrToAddrExpr(LHS);
16080 RHS = SE.getPtrToAddrExpr(RHS);
16082 break;
16083 }
16084 const SCEVConstant *C;
16085 const SCEV *A, *B;
16088 RHS = A;
16089 LHS = B;
16090 }
16091 if (LHS > RHS)
16092 std::swap(LHS, RHS);
16093 Guards.NotEqual.insert({LHS, RHS});
16094 continue;
16095 }
16096 break;
16097 default:
16098 break;
16099 }
16100
16101 if (To)
16102 AddRewrite(From, FromRewritten, To);
16103 }
16104 };
16105
16107 // First, collect information from assumptions dominating the loop.
16108 for (auto &AssumeVH : SE.AC.assumptions()) {
16109 if (!AssumeVH)
16110 continue;
16111 auto *AssumeI = cast<CallInst>(AssumeVH);
16112 if (!SE.DT.dominates(AssumeI, Block))
16113 continue;
16114 Terms.emplace_back(AssumeI->getOperand(0), true);
16115 }
16116
16117 // Second, collect information from llvm.experimental.guards dominating the loop.
16118 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16119 SE.F.getParent(), Intrinsic::experimental_guard);
16120 if (GuardDecl)
16121 for (const auto *GU : GuardDecl->users())
16122 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16123 if (Guard->getFunction() == Block->getParent() &&
16124 SE.DT.dominates(Guard, Block))
16125 Terms.emplace_back(Guard->getArgOperand(0), true);
16126
16127 // Third, collect conditions from dominating branches. Starting at the loop
16128 // predecessor, climb up the predecessor chain, as long as there are
16129 // predecessors that can be found that have unique successors leading to the
16130 // original header. If there is no such predecessor, continue at the
16131 // immediate dominator.
16132 // TODO: share this logic with isLoopEntryGuardedByCond.
16133 unsigned NumCollectedConditions = 0;
16134 unsigned NumDomTreeSteps = 0;
16136 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16137 for (;; Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16138 if (!Pair.first) {
16139 // At the first block without a unique predecessor, try to build
16140 // conditions for its phis by merging those of their incoming blocks.
16141 if (!NumDomTreeSteps && Depth < MaxLoopGuardCollectionDepth) {
16142 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16143 for (auto &Phi : Pair.second->phis())
16144 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16145 }
16146 const DomTreeNode *IDom = SE.DT.getNode(Pair.second)->getIDom();
16147 if (!IDom || ++NumDomTreeSteps > MaxGuardDomTreeSteps)
16148 break;
16149 Pair.first = IDom->getBlock();
16150 continue;
16151 }
16152 VisitedBlocks.insert(Pair.second);
16153 const CondBrInst *LoopEntryPredicate =
16154 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16155 if (!LoopEntryPredicate)
16156 continue;
16157
16158 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16159 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16160 NumCollectedConditions++;
16161
16162 // If we are recursively collecting guards stop after 2
16163 // conditions to limit compile-time impact for now.
16164 if (Depth > 0 && NumCollectedConditions == 2)
16165 break;
16166 }
16167
16168 // Now apply the information from the collected conditions to
16169 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16170 // earliest conditions is processed first, except guards with divisibility
16171 // information, which are moved to the back. This ensures the SCEVs with the
16172 // shortest dependency chains are constructed first.
16174 GuardsToProcess;
16175 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16176 SmallVector<Value *, 8> Worklist;
16177 SmallPtrSet<Value *, 8> Visited;
16178 Worklist.push_back(Term);
16179 while (!Worklist.empty()) {
16180 Value *Cond = Worklist.pop_back_val();
16181 if (!Visited.insert(Cond).second)
16182 continue;
16183
16184 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16185 auto Predicate =
16186 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16187 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16188 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16189 // If LHS is a constant, apply information to the other expression.
16190 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16191 // can improve results.
16192 if (isa<SCEVConstant>(LHS)) {
16193 std::swap(LHS, RHS);
16195 }
16196 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16197 continue;
16198 }
16199
16200 Value *L, *R;
16201 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16202 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16203 Worklist.push_back(L);
16204 Worklist.push_back(R);
16205 }
16206 }
16207 }
16208
16209 // Process divisibility guards in reverse order to populate DivGuards early.
16210 DenseMap<const SCEV *, APInt> Multiples;
16211 LoopGuards DivGuards(SE);
16212 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16213 if (!isDivisibilityGuard(LHS, RHS, SE))
16214 continue;
16215 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16216 Multiples, SE);
16217 }
16218
16219 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16220 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16221
16222 // Apply divisibility information last. This ensures it is applied to the
16223 // outermost expression after other rewrites for the given value.
16224 for (const auto &[K, Divisor] : Multiples) {
16225 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16226 Guards.RewriteMap[K] =
16228 Guards.rewrite(K), Divisor, SE),
16229 DivisorSCEV),
16230 DivisorSCEV);
16231 ExprsToRewrite.push_back(K);
16232 }
16233
16234 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16235 // the replacement expressions are contained in the ranges of the replaced
16236 // expressions.
16237 Guards.PreserveNUW = true;
16238 Guards.PreserveNSW = true;
16239 for (const SCEV *Expr : ExprsToRewrite) {
16240 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16241 Guards.PreserveNUW &=
16242 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16243 Guards.PreserveNSW &=
16244 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16245 }
16246
16247 // Now that all rewrite information is collect, rewrite the collected
16248 // expressions with the information in the map. This applies information to
16249 // sub-expressions.
16250 if (ExprsToRewrite.size() > 1) {
16251 for (const SCEV *Expr : ExprsToRewrite) {
16252 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16253 Guards.RewriteMap.erase(Expr);
16254 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16255 }
16256 }
16257}
16258
16260 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16261 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16262 /// replacement is loop invariant in the loop of the AddRec.
16263 class SCEVLoopGuardRewriter
16264 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16267
16268 SCEVFlags FlagMask = SCEV::FlagNone;
16269
16270 public:
16271 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16272 const ScalarEvolution::LoopGuards &Guards)
16273 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16274 NotEqual(Guards.NotEqual) {
16275 if (Guards.PreserveNUW)
16276 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16277 if (Guards.PreserveNSW)
16278 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16279 }
16280
16281 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16282
16283 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16284 return Map.lookup_or(Expr, Expr);
16285 }
16286
16287 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
16288 if (const SCEV *S = Map.lookup(Expr))
16289 return S;
16291 Expr);
16292 }
16293
16294 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16295 if (const SCEV *S = Map.lookup(Expr))
16296 return S;
16297
16298 // If we didn't find the extact ZExt expr in the map, check if there's
16299 // an entry for a smaller ZExt we can use instead.
16300 Type *Ty = Expr->getType();
16301 const SCEV *Op = Expr->getOperand(0);
16302 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16303 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16304 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16305 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16306 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16307 if (const SCEV *S = Map.lookup(NarrowExt))
16308 return SE.getZeroExtendExpr(S, Ty);
16309 Bitwidth = Bitwidth / 2;
16310 }
16311
16313 Expr);
16314 }
16315
16316 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16317 if (const SCEV *S = Map.lookup(Expr))
16318 return S;
16320 Expr);
16321 }
16322
16323 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16324 if (const SCEV *S = Map.lookup(Expr))
16325 return S;
16327 }
16328
16329 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16330 if (const SCEV *S = Map.lookup(Expr))
16331 return S;
16333 }
16334
16335 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16336 if (const SCEV *S = Map.lookup(Expr))
16337 return S;
16338
16339 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16340 // return UMax(S, 1).
16341 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16342 SCEVUse LHS, RHS;
16343 if (MatchBinarySub(S, LHS, RHS)) {
16344 if (LHS > RHS)
16345 std::swap(LHS, RHS);
16346 if (NotEqual.contains({LHS, RHS})) {
16347 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16348 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16349 return SE.getUMaxExpr(OneAlignedUp, S);
16350 }
16351 }
16352 return nullptr;
16353 };
16354
16355 // Check if Expr itself is a subtraction pattern with guard info.
16356 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16357 return Rewritten;
16358
16359 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16360 // (Const + A + B). There may be guard info for A + B, and if so, apply
16361 // it.
16362 // TODO: Could more generally apply guards to Add sub-expressions.
16363 if (isa<SCEVConstant>(Expr->getOperand(0))) {
16364 if (Expr->getNumOperands() == 3) {
16365 const SCEV *Add =
16366 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16367 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16368 return SE.getAddExpr(
16369 Expr->getOperand(0), Rewritten,
16370 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16371 if (const SCEV *S = Map.lookup(Add))
16372 return SE.getAddExpr(Expr->getOperand(0), S);
16373 }
16374
16375 // For expressions of the form (Const + A), check if we have guard info
16376 // for (Const + 1 + A), and rewrite to ((Const + 1 + A) - 1). This makes
16377 // sure we don't lose information when rewriting expressions based on
16378 // back-edge taken counts in some cases.
16379 if (Expr->getNumOperands() == 2) {
16380 const SCEV *S = nullptr;
16381 // Handle (-1 + 1 + A) without constructing SCEVs.
16382 if (match(Expr->getOperand(0), m_scev_AllOnes())) {
16383 S = Map.lookup(Expr->getOperand(1));
16384 } else {
16385 const SCEV *NewC =
16386 SE.getAddExpr(Expr->getOperand(0), SE.getOne(Expr->getType()));
16387 S = Map.lookup(SE.getAddExpr(NewC, Expr->getOperand(1)));
16388 }
16389 if (S)
16390 return SE.getAddExpr(S, SE.getMinusOne(Expr->getType()));
16391 }
16392 }
16394 bool Changed = false;
16395 for (SCEVUse Op : Expr->operands()) {
16396 Operands.push_back(
16398 Changed |= Op != Operands.back();
16399 }
16400 // We are only replacing operands with equivalent values, so transfer the
16401 // flags from the original expression.
16402 return !Changed ? Expr
16403 : SE.getAddExpr(Operands,
16405 Expr->getNoWrapFlags(), FlagMask));
16406 }
16407
16408 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16410 bool Changed = false;
16411 for (SCEVUse Op : Expr->operands()) {
16412 Operands.push_back(
16414 Changed |= Op != Operands.back();
16415 }
16416 // We are only replacing operands with equivalent values, so transfer the
16417 // flags from the original expression.
16418 return !Changed ? Expr
16419 : SE.getMulExpr(Operands,
16421 Expr->getNoWrapFlags(), FlagMask));
16422 }
16423 };
16424
16425 if (RewriteMap.empty() && NotEqual.empty())
16426 return Expr;
16427
16428 SCEVLoopGuardRewriter Rewriter(SE, *this);
16429 return Rewriter.visit(Expr);
16430}
16431
16432const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16433 LoopGuards Guards = LoopGuards::collectOnDemand(L, *this);
16434 return applyLoopGuards(Expr, Guards);
16435}
16436
16438 LoopGuards &Guards) {
16439 // Loop guards never rewrite constants and AddRecs, so there is no need to
16440 // collect pending guards for them.
16442 return Expr;
16443 if (Guards.PendingLoop)
16444 Guards.collectPending();
16445 return Guards.rewrite(Expr);
16446}
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:665
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:690
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
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
int64_t C1
int64_t C0
unsigned ExpectedFlags
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 std::optional< BinaryOp > MatchBinaryOp(Value *V, const DominatorTree &DT)
Try to map V into a BinaryOp, and return std::nullopt on failure.
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 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
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 getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
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:975
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.
#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)
SCEVBinaryExpr_match< SCEVAddExpr, Op0_t, Op1_t, SCEV::FlagNSW > m_scev_NSWAdd(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:375
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.