LLVM 24.0.0git
ScalarEvolution.cpp
Go to the documentation of this file.
1//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution analysis
10// engine, which is used primarily to analyze expressions involving induction
11// variables in loops.
12//
13// There are several aspects to this library. First is the representation of
14// scalar expressions, which are represented as subclasses of the SCEV class.
15// These classes are used to represent certain types of subexpressions that we
16// can handle. We only create one SCEV of a particular shape, so
17// pointer-comparisons for equality are legal.
18//
19// One important aspect of the SCEV objects is that they are never cyclic, even
20// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21// the PHI node is one of the idioms that we can represent (e.g., a polynomial
22// recurrence) then we represent it directly as a recurrence node, otherwise we
23// represent it as a SCEVUnknown node.
24//
25// In addition to being able to represent expressions of various types, we also
26// have folders that are used to build the *canonical* representation for a
27// particular expression. These folders are capable of using a variety of
28// rewrite rules to simplify the expressions.
29//
30// Once the folders are defined, we can implement the more interesting
31// higher-level code, such as the code that recognizes PHI nodes of various
32// types, computes the execution count of a loop, etc.
33//
34// TODO: We should use these routines and value representations to implement
35// dependence analysis!
36//
37//===----------------------------------------------------------------------===//
38//
39// There are several good references for the techniques used in this analysis.
40//
41// Chains of recurrences -- a method to expedite the evaluation
42// of closed-form functions
43// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
44//
45// On computational properties of chains of recurrences
46// Eugene V. Zima
47//
48// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49// Robert A. van Engelen
50//
51// Efficient Symbolic Analysis for Optimizing Compilers
52// Robert A. van Engelen
53//
54// Using the chains of recurrences algebra for data dependence testing and
55// induction variable substitution
56// MS Thesis, Johnie Birch
57//
58//===----------------------------------------------------------------------===//
59
61#include "llvm/ADT/APInt.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/DenseMap.h"
65#include "llvm/ADT/FoldingSet.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/Sequence.h"
71#include "llvm/ADT/Statistic.h"
73#include "llvm/ADT/StringRef.h"
83#include "llvm/Config/llvm-config.h"
84#include "llvm/IR/Argument.h"
85#include "llvm/IR/BasicBlock.h"
86#include "llvm/IR/CFG.h"
87#include "llvm/IR/Constant.h"
89#include "llvm/IR/Constants.h"
90#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/Dominators.h"
93#include "llvm/IR/Function.h"
94#include "llvm/IR/GlobalAlias.h"
95#include "llvm/IR/GlobalValue.h"
97#include "llvm/IR/InstrTypes.h"
98#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Intrinsics.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Operator.h"
104#include "llvm/IR/PatternMatch.h"
105#include "llvm/IR/Type.h"
106#include "llvm/IR/Use.h"
107#include "llvm/IR/User.h"
108#include "llvm/IR/Value.h"
109#include "llvm/IR/Verifier.h"
111#include "llvm/Pass.h"
112#include "llvm/Support/Casting.h"
115#include "llvm/Support/Debug.h"
121#include <algorithm>
122#include <cassert>
123#include <climits>
124#include <cstdint>
125#include <cstdlib>
126#include <map>
127#include <memory>
128#include <numeric>
129#include <optional>
130#include <tuple>
131#include <utility>
132#include <vector>
133
134using namespace llvm;
135using namespace PatternMatch;
136using namespace SCEVPatternMatch;
137
138#define DEBUG_TYPE "scalar-evolution"
139
140STATISTIC(NumExitCountsComputed,
141 "Number of loop exits with predictable exit counts");
142STATISTIC(NumExitCountsNotComputed,
143 "Number of loop exits without predictable exit counts");
144STATISTIC(NumBruteForceTripCountsComputed,
145 "Number of loops with trip counts computed by force");
146
147#ifdef EXPENSIVE_CHECKS
148bool llvm::VerifySCEV = true;
149#else
150bool llvm::VerifySCEV = false;
151#endif
152
154 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
155 cl::desc("Maximum number of iterations SCEV will "
156 "symbolically execute a constant "
157 "derived loop"),
158 cl::init(100));
159
161 "verify-scev", cl::Hidden, cl::location(VerifySCEV),
162 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
164 "verify-scev-strict", cl::Hidden,
165 cl::desc("Enable stricter verification with -verify-scev is passed"));
166
168 "scev-verify-ir", cl::Hidden,
169 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
170 cl::init(false));
171
173 "scev-mulops-inline-threshold", cl::Hidden,
174 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
175 cl::init(32));
176
178 "scev-addops-inline-threshold", cl::Hidden,
179 cl::desc("Threshold for inlining addition operands into a SCEV"),
180 cl::init(500));
181
183 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
184 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
185 cl::init(32));
186
188 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
189 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
190 cl::init(2));
191
193 "scalar-evolution-max-value-compare-depth", cl::Hidden,
194 cl::desc("Maximum depth of recursive value complexity comparisons"),
195 cl::init(2));
196
198 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
199 cl::desc("Maximum depth of recursive arithmetics"),
200 cl::init(32));
201
203 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
204 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
205
207 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
208 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
209 cl::init(8));
210
212 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
213 cl::desc("Max coefficients in AddRec during evolving"),
214 cl::init(8));
215
217 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
218 cl::desc("Size of the expression which is considered huge"),
219 cl::init(4096));
220
222 "scev-range-iter-threshold", cl::Hidden,
223 cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
224 cl::init(32));
225
227 "scalar-evolution-max-loop-guard-collection-depth", cl::Hidden,
228 cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1));
229
230static cl::opt<bool>
231ClassifyExpressions("scalar-evolution-classify-expressions",
232 cl::Hidden, cl::init(true),
233 cl::desc("When printing analysis, include information on every instruction"));
234
236 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
237 cl::init(false),
238 cl::desc("Use more powerful methods of sharpening expression ranges. May "
239 "be costly in terms of compile time"));
240
242 "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
243 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
244 "Phi strongly connected components"),
245 cl::init(8));
246
247static cl::opt<bool>
248 EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
249 cl::desc("Handle <= and >= in finite loops"),
250 cl::init(true));
251
253 "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
254 cl::desc("Infer nuw/nsw flags using context where suitable"),
255 cl::init(true));
256
257//===----------------------------------------------------------------------===//
258// SCEV class definitions
259//===----------------------------------------------------------------------===//
260
262 // Leaf nodes are always their own canonical.
263 switch (getSCEVType()) {
264 case scConstant:
265 case scVScale:
266 case scUnknown:
267 CanonicalSCEV = this;
268 return;
269 default:
270 break;
271 }
272
273 // For all other expressions, check whether any immediate operand has a
274 // different canonical. Since operands are always created before their parent,
275 // their canonical pointers are already set — no recursion needed.
276 bool Changed = false;
278 for (SCEVUse Op : operands()) {
279 CanonOps.push_back(Op->getCanonical());
280 Changed |= CanonOps.back() != Op.getPointer();
281 }
282
283 if (!Changed) {
284 CanonicalSCEV = this;
285 return;
286 }
287
288 auto *NAry = dyn_cast<SCEVNAryExpr>(this);
289 SCEV::NoWrapFlags Flags = NAry ? NAry->getNoWrapFlags() : SCEV::FlagAnyWrap;
290 switch (getSCEVType()) {
291 case scPtrToAddr:
292 CanonicalSCEV = SE.getPtrToAddrExpr(CanonOps[0]);
293 return;
294 case scPtrToInt:
295 CanonicalSCEV = SE.getPtrToIntExpr(CanonOps[0], getType());
296 return;
297 case scTruncate:
298 CanonicalSCEV = SE.getTruncateExpr(CanonOps[0], getType());
299 return;
300 case scZeroExtend:
301 CanonicalSCEV = SE.getZeroExtendExpr(CanonOps[0], getType());
302 return;
303 case scSignExtend:
304 CanonicalSCEV = SE.getSignExtendExpr(CanonOps[0], getType());
305 return;
306 case scUDivExpr:
307 CanonicalSCEV = SE.getUDivExpr(CanonOps[0], CanonOps[1]);
308 return;
309 case scAddExpr:
310 CanonicalSCEV = SE.getAddExpr(CanonOps, Flags);
311 return;
312 case scMulExpr:
313 CanonicalSCEV = SE.getMulExpr(CanonOps, Flags);
314 return;
315 case scAddRecExpr:
317 CanonOps, cast<SCEVAddRecExpr>(this)->getLoop(), Flags);
318 return;
319 case scSMaxExpr:
320 CanonicalSCEV = SE.getSMaxExpr(CanonOps);
321 return;
322 case scUMaxExpr:
323 CanonicalSCEV = SE.getUMaxExpr(CanonOps);
324 return;
325 case scSMinExpr:
326 CanonicalSCEV = SE.getSMinExpr(CanonOps);
327 return;
328 case scUMinExpr:
329 CanonicalSCEV = SE.getUMinExpr(CanonOps);
330 return;
332 CanonicalSCEV = SE.getUMinExpr(CanonOps, /*Sequential=*/true);
333 return;
334 default:
335 llvm_unreachable("Unknown SCEV type");
336 }
337}
338
339//===----------------------------------------------------------------------===//
340// Implementation of the SCEV class.
341//
342
343#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
345 print(dbgs());
346 dbgs() << '\n';
347}
348#endif
349
350void SCEV::print(raw_ostream &OS) const {
351 switch (getSCEVType()) {
352 case scConstant:
353 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
354 return;
355 case scVScale:
356 OS << "vscale";
357 return;
358 case scPtrToAddr:
359 case scPtrToInt: {
360 const SCEVCastExpr *PtrCast = cast<SCEVCastExpr>(this);
361 const SCEV *Op = PtrCast->getOperand();
362 StringRef OpS = getSCEVType() == scPtrToAddr ? "addr" : "int";
363 OS << "(ptrto" << OpS << " " << *Op->getType() << " " << *Op << " to "
364 << *PtrCast->getType() << ")";
365 return;
366 }
367 case scTruncate: {
368 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
369 const SCEV *Op = Trunc->getOperand();
370 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
371 << *Trunc->getType() << ")";
372 return;
373 }
374 case scZeroExtend: {
376 const SCEV *Op = ZExt->getOperand();
377 OS << "(zext " << *Op->getType() << " " << *Op << " to "
378 << *ZExt->getType() << ")";
379 return;
380 }
381 case scSignExtend: {
383 const SCEV *Op = SExt->getOperand();
384 OS << "(sext " << *Op->getType() << " " << *Op << " to "
385 << *SExt->getType() << ")";
386 return;
387 }
388 case scAddRecExpr: {
389 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
390 OS << "{" << *AR->getOperand(0);
391 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
392 OS << ",+," << *AR->getOperand(i);
393 OS << "}<";
394 if (AR->hasNoUnsignedWrap())
395 OS << "nuw><";
396 if (AR->hasNoSignedWrap())
397 OS << "nsw><";
398 if (AR->hasNoSelfWrap() && !AR->hasNoUnsignedWrap() &&
399 !AR->hasNoSignedWrap())
400 OS << "nw><";
401 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
402 OS << ">";
403 return;
404 }
405 case scAddExpr:
406 case scMulExpr:
407 case scUMaxExpr:
408 case scSMaxExpr:
409 case scUMinExpr:
410 case scSMinExpr:
412 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
413 const char *OpStr = nullptr;
414 switch (NAry->getSCEVType()) {
415 case scAddExpr: OpStr = " + "; break;
416 case scMulExpr: OpStr = " * "; break;
417 case scUMaxExpr: OpStr = " umax "; break;
418 case scSMaxExpr: OpStr = " smax "; break;
419 case scUMinExpr:
420 OpStr = " umin ";
421 break;
422 case scSMinExpr:
423 OpStr = " smin ";
424 break;
426 OpStr = " umin_seq ";
427 break;
428 default:
429 llvm_unreachable("There are no other nary expression types.");
430 }
431 OS << "("
433 << ")";
434 switch (NAry->getSCEVType()) {
435 case scAddExpr:
436 case scMulExpr:
437 if (NAry->hasNoUnsignedWrap())
438 OS << "<nuw>";
439 if (NAry->hasNoSignedWrap())
440 OS << "<nsw>";
441 break;
442 default:
443 // Nothing to print for other nary expressions.
444 break;
445 }
446 return;
447 }
448 case scUDivExpr: {
449 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
450 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
451 return;
452 }
453 case scUnknown:
454 cast<SCEVUnknown>(this)->getValue()->printAsOperand(OS, false);
455 return;
457 OS << "***COULDNOTCOMPUTE***";
458 return;
459 }
460 llvm_unreachable("Unknown SCEV kind!");
461}
462
464 switch (getSCEVType()) {
465 case scConstant:
466 return cast<SCEVConstant>(this)->getType();
467 case scVScale:
468 return cast<SCEVVScale>(this)->getType();
469 case scPtrToAddr:
470 case scPtrToInt:
471 case scTruncate:
472 case scZeroExtend:
473 case scSignExtend:
474 return cast<SCEVCastExpr>(this)->getType();
475 case scAddRecExpr:
476 return cast<SCEVAddRecExpr>(this)->getType();
477 case scMulExpr:
478 return cast<SCEVMulExpr>(this)->getType();
479 case scUMaxExpr:
480 case scSMaxExpr:
481 case scUMinExpr:
482 case scSMinExpr:
483 return cast<SCEVMinMaxExpr>(this)->getType();
485 return cast<SCEVSequentialMinMaxExpr>(this)->getType();
486 case scAddExpr:
487 return cast<SCEVAddExpr>(this)->getType();
488 case scUDivExpr:
489 return cast<SCEVUDivExpr>(this)->getType();
490 case scUnknown:
491 return cast<SCEVUnknown>(this)->getType();
493 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
494 }
495 llvm_unreachable("Unknown SCEV kind!");
496}
497
499 switch (getSCEVType()) {
500 case scConstant:
501 case scVScale:
502 case scUnknown:
503 return {};
504 case scPtrToAddr:
505 case scPtrToInt:
506 case scTruncate:
507 case scZeroExtend:
508 case scSignExtend:
509 return cast<SCEVCastExpr>(this)->operands();
510 case scAddRecExpr:
511 case scAddExpr:
512 case scMulExpr:
513 case scUMaxExpr:
514 case scSMaxExpr:
515 case scUMinExpr:
516 case scSMinExpr:
518 return cast<SCEVNAryExpr>(this)->operands();
519 case scUDivExpr:
520 return cast<SCEVUDivExpr>(this)->operands();
522 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
523 }
524 llvm_unreachable("Unknown SCEV kind!");
525}
526
527bool SCEV::isZero() const { return match(this, m_scev_Zero()); }
528
529bool SCEV::isOne() const { return match(this, m_scev_One()); }
530
531bool SCEV::isAllOnesValue() const { return match(this, m_scev_AllOnes()); }
532
535 if (!Mul) return false;
536
537 // If there is a constant factor, it will be first.
538 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
539 if (!SC) return false;
540
541 // Return true if the value is negative, this matches things like (-42 * V).
542 return SC->getAPInt().isNegative();
543}
544
547
549 return S->getSCEVType() == scCouldNotCompute;
550}
551
553 auto &Entry = ConstantSCEVs[V];
554 if (Entry)
555 return Entry;
556
558 ID.AddInteger(scConstant);
559 ID.AddPointer(V);
560 void *IP = nullptr;
561 if (SCEVConstant *S =
562 static_cast<SCEVConstant *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)))
563 return Entry = S;
564 SCEVConstant *S =
565 new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
566 UniqueSCEVs.InsertNode(S, IP);
567 S->computeAndSetCanonical(*this);
568 return Entry = S;
569}
570
572 return getConstant(ConstantInt::get(getContext(), Val));
573}
574
575const SCEV *
578 // TODO: Avoid implicit trunc?
579 // See https://github.com/llvm/llvm-project/issues/112510.
580 return getConstant(
581 ConstantInt::get(ITy, V, isSigned, /*ImplicitTrunc=*/true));
582}
583
586 ID.AddInteger(scVScale);
587 ID.AddPointer(Ty);
588 void *IP = nullptr;
589 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
590 return S;
591 SCEV *S = new (SCEVAllocator) SCEVVScale(ID.Intern(SCEVAllocator), Ty);
592 UniqueSCEVs.InsertNode(S, IP);
593 S->computeAndSetCanonical(*this);
594 return S;
595}
596
598 SCEV::NoWrapFlags Flags) {
599 const SCEV *Res = getConstant(Ty, EC.getKnownMinValue());
600 if (EC.isScalable())
601 Res = getMulExpr(Res, getVScale(Ty), Flags);
602 return Res;
603}
604
608
609SCEVPtrToAddrExpr::SCEVPtrToAddrExpr(const FoldingSetNodeIDRef ID,
610 const SCEV *Op, Type *ITy)
611 : SCEVCastExpr(ID, scPtrToAddr, Op, ITy) {
612 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
613 "Must be a non-bit-width-changing pointer-to-integer cast!");
614}
615
616SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, SCEVUse Op,
617 Type *ITy)
618 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
619 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
620 "Must be a non-bit-width-changing pointer-to-integer cast!");
621}
622
627
628SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
629 Type *ty)
631 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
632 "Cannot truncate non-integer value!");
633}
634
635SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
636 Type *ty)
638 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
639 "Cannot zero extend non-integer value!");
640}
641
642SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, SCEVUse op,
643 Type *ty)
645 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
646 "Cannot sign extend non-integer value!");
647}
648
650 // Clear this SCEVUnknown from various maps.
651 SE->forgetMemoizedResults({this});
652
653 // Remove this SCEVUnknown from the uniquing map.
654 SE->UniqueSCEVs.RemoveNode(this);
655
656 // Release the value.
657 setValPtr(nullptr);
658}
659
660void SCEVUnknown::allUsesReplacedWith(Value *New) {
661 // Clear this SCEVUnknown from various maps.
662 SE->forgetMemoizedResults({this});
663
664 // Remove this SCEVUnknown from the uniquing map.
665 SE->UniqueSCEVs.RemoveNode(this);
666
667 // Replace the value pointer in case someone is still using this SCEVUnknown.
668 setValPtr(New);
669}
670
671//===----------------------------------------------------------------------===//
672// SCEV Utilities
673//===----------------------------------------------------------------------===//
674
675/// Compare the two values \p LV and \p RV in terms of their "complexity" where
676/// "complexity" is a partial (and somewhat ad-hoc) relation used to order
677/// operands in SCEV expressions.
678static int CompareValueComplexity(const LoopInfo *const LI, Value *LV,
679 Value *RV, unsigned Depth) {
681 return 0;
682
683 // Order pointer values after integer values. This helps SCEVExpander form
684 // GEPs.
685 bool LIsPointer = LV->getType()->isPointerTy(),
686 RIsPointer = RV->getType()->isPointerTy();
687 if (LIsPointer != RIsPointer)
688 return (int)LIsPointer - (int)RIsPointer;
689
690 // Compare getValueID values.
691 unsigned LID = LV->getValueID(), RID = RV->getValueID();
692 if (LID != RID)
693 return (int)LID - (int)RID;
694
695 // Sort arguments by their position.
696 if (const auto *LA = dyn_cast<Argument>(LV)) {
697 const auto *RA = cast<Argument>(RV);
698 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
699 return (int)LArgNo - (int)RArgNo;
700 }
701
702 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
703 const auto *RGV = cast<GlobalValue>(RV);
704
705 if (auto L = LGV->getLinkage() - RGV->getLinkage())
706 return L;
707
708 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
709 auto LT = GV->getLinkage();
710 return !(GlobalValue::isPrivateLinkage(LT) ||
712 };
713
714 // Use the names to distinguish the two values, but only if the
715 // names are semantically important.
716 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
717 return LGV->getName().compare(RGV->getName());
718 }
719
720 // For instructions, compare their loop depth, and their operand count. This
721 // is pretty loose.
722 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
723 const auto *RInst = cast<Instruction>(RV);
724
725 // Compare loop depths.
726 const BasicBlock *LParent = LInst->getParent(),
727 *RParent = RInst->getParent();
728 if (LParent != RParent) {
729 unsigned LDepth = LI->getLoopDepth(LParent),
730 RDepth = LI->getLoopDepth(RParent);
731 if (LDepth != RDepth)
732 return (int)LDepth - (int)RDepth;
733 }
734
735 // Compare the number of operands.
736 unsigned LNumOps = LInst->getNumOperands(),
737 RNumOps = RInst->getNumOperands();
738 if (LNumOps != RNumOps)
739 return (int)LNumOps - (int)RNumOps;
740
741 for (unsigned Idx : seq(LNumOps)) {
742 int Result = CompareValueComplexity(LI, LInst->getOperand(Idx),
743 RInst->getOperand(Idx), Depth + 1);
744 if (Result != 0)
745 return Result;
746 }
747 }
748
749 return 0;
750}
751
752// Return negative, zero, or positive, if LHS is less than, equal to, or greater
753// than RHS, respectively. A three-way result allows recursive comparisons to be
754// more efficient.
755// If the max analysis depth was reached, return std::nullopt, assuming we do
756// not know if they are equivalent for sure.
757static std::optional<int>
758CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS,
759 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
760 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
761 if (LHS == RHS)
762 return 0;
763
764 // Primarily, sort the SCEVs by their getSCEVType().
765 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
766 if (LType != RType)
767 return (int)LType - (int)RType;
768
770 return std::nullopt;
771
772 // Aside from the getSCEVType() ordering, the particular ordering
773 // isn't very important except that it's beneficial to be consistent,
774 // so that (a + b) and (b + a) don't end up as different expressions.
775 switch (LType) {
776 case scUnknown: {
777 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
778 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
779
780 int X =
781 CompareValueComplexity(LI, LU->getValue(), RU->getValue(), Depth + 1);
782 return X;
783 }
784
785 case scConstant: {
788
789 // Compare constant values.
790 const APInt &LA = LC->getAPInt();
791 const APInt &RA = RC->getAPInt();
792 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
793 if (LBitWidth != RBitWidth)
794 return (int)LBitWidth - (int)RBitWidth;
795 return LA.ult(RA) ? -1 : 1;
796 }
797
798 case scVScale: {
799 const auto *LTy = cast<IntegerType>(cast<SCEVVScale>(LHS)->getType());
800 const auto *RTy = cast<IntegerType>(cast<SCEVVScale>(RHS)->getType());
801 return LTy->getBitWidth() - RTy->getBitWidth();
802 }
803
804 case scAddRecExpr: {
807
808 // There is always a dominance between two recs that are used by one SCEV,
809 // so we can safely sort recs by loop header dominance. We require such
810 // order in getAddExpr.
811 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
812 if (LLoop != RLoop) {
813 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
814 assert(LHead != RHead && "Two loops share the same header?");
815 if (DT.dominates(LHead, RHead))
816 return 1;
817 assert(DT.dominates(RHead, LHead) &&
818 "No dominance between recurrences used by one SCEV?");
819 return -1;
820 }
821
822 [[fallthrough]];
823 }
824
825 case scTruncate:
826 case scZeroExtend:
827 case scSignExtend:
828 case scPtrToAddr:
829 case scPtrToInt:
830 case scAddExpr:
831 case scMulExpr:
832 case scUDivExpr:
833 case scSMaxExpr:
834 case scUMaxExpr:
835 case scSMinExpr:
836 case scUMinExpr:
838 ArrayRef<SCEVUse> LOps = LHS->operands();
839 ArrayRef<SCEVUse> ROps = RHS->operands();
840
841 // Lexicographically compare n-ary-like expressions.
842 unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
843 if (LNumOps != RNumOps)
844 return (int)LNumOps - (int)RNumOps;
845
846 for (unsigned i = 0; i != LNumOps; ++i) {
847 auto X = CompareSCEVComplexity(LI, LOps[i].getPointer(),
848 ROps[i].getPointer(), DT, Depth + 1);
849 if (X != 0)
850 return X;
851 }
852 return 0;
853 }
854
856 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
857 }
858 llvm_unreachable("Unknown SCEV kind!");
859}
860
861/// Given a list of SCEV objects, order them by their complexity, and group
862/// objects of the same complexity together by value. When this routine is
863/// finished, we know that any duplicates in the vector are consecutive and that
864/// complexity is monotonically increasing.
865///
866/// Note that we go take special precautions to ensure that we get deterministic
867/// results from this routine. In other words, we don't want the results of
868/// this to depend on where the addresses of various SCEV objects happened to
869/// land in memory.
871 DominatorTree &DT) {
872 if (Ops.size() < 2) return; // Noop
873
874 // Whether LHS has provably less complexity than RHS.
875 auto IsLessComplex = [&](SCEVUse LHS, SCEVUse RHS) {
876 auto Complexity = CompareSCEVComplexity(LI, LHS, RHS, DT);
877 return Complexity && *Complexity < 0;
878 };
879 if (Ops.size() == 2) {
880 // This is the common case, which also happens to be trivially simple.
881 // Special case it.
882 SCEVUse &LHS = Ops[0], &RHS = Ops[1];
883 if (IsLessComplex(RHS, LHS))
884 std::swap(LHS, RHS);
885 return;
886 }
887
888 // Do the rough sort by complexity.
890 Ops, [&](SCEVUse LHS, SCEVUse RHS) { return IsLessComplex(LHS, RHS); });
891
892 // Now that we are sorted by complexity, group elements of the same
893 // complexity. Note that this is, at worst, N^2, but the vector is likely to
894 // be extremely short in practice. Note that we take this approach because we
895 // do not want to depend on the addresses of the objects we are grouping.
896 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
897 const SCEV *S = Ops[i];
898 unsigned Complexity = S->getSCEVType();
899
900 // If there are any objects of the same complexity and same value as this
901 // one, group them.
902 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
903 if (Ops[j] == S) { // Found a duplicate.
904 // Move it to immediately after i'th element.
905 std::swap(Ops[i+1], Ops[j]);
906 ++i; // no need to rescan it.
907 if (i == e-2) return; // Done!
908 }
909 }
910 }
911}
912
913/// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
914/// least HugeExprThreshold nodes).
916 return any_of(Ops, [](const SCEV *S) {
918 });
919}
920
921/// Performs a number of common optimizations on the passed \p Ops. If the
922/// whole expression reduces down to a single operand, it will be returned.
923///
924/// The following optimizations are performed:
925/// * Fold constants using the \p Fold function.
926/// * Remove identity constants satisfying \p IsIdentity.
927/// * If a constant satisfies \p IsAbsorber, return it.
928/// * Sort operands by complexity.
929template <typename FoldT, typename IsIdentityT, typename IsAbsorberT>
930static const SCEV *
932 SmallVectorImpl<SCEVUse> &Ops, FoldT Fold,
933 IsIdentityT IsIdentity, IsAbsorberT IsAbsorber) {
934 const SCEVConstant *Folded = nullptr;
935 for (unsigned Idx = 0; Idx < Ops.size();) {
936 const SCEV *Op = Ops[Idx];
937 if (const auto *C = dyn_cast<SCEVConstant>(Op)) {
938 if (!Folded)
939 Folded = C;
940 else
941 Folded = cast<SCEVConstant>(
942 SE.getConstant(Fold(Folded->getAPInt(), C->getAPInt())));
943 Ops.erase(Ops.begin() + Idx);
944 continue;
945 }
946 ++Idx;
947 }
948
949 if (Ops.empty()) {
950 assert(Folded && "Must have folded value");
951 return Folded;
952 }
953
954 if (Folded && IsAbsorber(Folded->getAPInt()))
955 return Folded;
956
957 GroupByComplexity(Ops, &LI, DT);
958 if (Folded && !IsIdentity(Folded->getAPInt()))
959 Ops.insert(Ops.begin(), Folded);
960
961 return Ops.size() == 1 ? Ops[0] : nullptr;
962}
963
964//===----------------------------------------------------------------------===//
965// Simple SCEV method implementations
966//===----------------------------------------------------------------------===//
967
968/// Compute BC(It, K). The result has width W. Assume, K > 0.
969static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
970 ScalarEvolution &SE,
971 Type *ResultTy) {
972 // Handle the simplest case efficiently.
973 if (K == 1)
974 return SE.getTruncateOrZeroExtend(It, ResultTy);
975
976 // We are using the following formula for BC(It, K):
977 //
978 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
979 //
980 // Suppose, W is the bitwidth of the return value. We must be prepared for
981 // overflow. Hence, we must assure that the result of our computation is
982 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
983 // safe in modular arithmetic.
984 //
985 // However, this code doesn't use exactly that formula; the formula it uses
986 // is something like the following, where T is the number of factors of 2 in
987 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
988 // exponentiation:
989 //
990 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
991 //
992 // This formula is trivially equivalent to the previous formula. However,
993 // this formula can be implemented much more efficiently. The trick is that
994 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
995 // arithmetic. To do exact division in modular arithmetic, all we have
996 // to do is multiply by the inverse. Therefore, this step can be done at
997 // width W.
998 //
999 // The next issue is how to safely do the division by 2^T. The way this
1000 // is done is by doing the multiplication step at a width of at least W + T
1001 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1002 // when we perform the division by 2^T (which is equivalent to a right shift
1003 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1004 // truncated out after the division by 2^T.
1005 //
1006 // In comparison to just directly using the first formula, this technique
1007 // is much more efficient; using the first formula requires W * K bits,
1008 // but this formula less than W + K bits. Also, the first formula requires
1009 // a division step, whereas this formula only requires multiplies and shifts.
1010 //
1011 // It doesn't matter whether the subtraction step is done in the calculation
1012 // width or the input iteration count's width; if the subtraction overflows,
1013 // the result must be zero anyway. We prefer here to do it in the width of
1014 // the induction variable because it helps a lot for certain cases; CodeGen
1015 // isn't smart enough to ignore the overflow, which leads to much less
1016 // efficient code if the width of the subtraction is wider than the native
1017 // register width.
1018 //
1019 // (It's possible to not widen at all by pulling out factors of 2 before
1020 // the multiplication; for example, K=2 can be calculated as
1021 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1022 // extra arithmetic, so it's not an obvious win, and it gets
1023 // much more complicated for K > 3.)
1024
1025 // Protection from insane SCEVs; this bound is conservative,
1026 // but it probably doesn't matter.
1027 if (K > 1000)
1028 return SE.getCouldNotCompute();
1029
1030 unsigned W = SE.getTypeSizeInBits(ResultTy);
1031
1032 // Calculate K! / 2^T and T; we divide out the factors of two before
1033 // multiplying for calculating K! / 2^T to avoid overflow.
1034 // Other overflow doesn't matter because we only care about the bottom
1035 // W bits of the result.
1036 APInt OddFactorial(W, 1);
1037 unsigned T = 1;
1038 for (unsigned i = 3; i <= K; ++i) {
1039 unsigned TwoFactors = countr_zero(i);
1040 T += TwoFactors;
1041 OddFactorial *= (i >> TwoFactors);
1042 }
1043
1044 // We need at least W + T bits for the multiplication step
1045 unsigned CalculationBits = W + T;
1046
1047 // Calculate 2^T, at width T+W.
1048 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1049
1050 // Calculate the multiplicative inverse of K! / 2^T;
1051 // this multiplication factor will perform the exact division by
1052 // K! / 2^T.
1053 APInt MultiplyFactor = OddFactorial.multiplicativeInverse();
1054
1055 // Calculate the product, at width T+W
1056 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1057 CalculationBits);
1058 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1059 for (unsigned i = 1; i != K; ++i) {
1060 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1061 Dividend = SE.getMulExpr(Dividend,
1062 SE.getTruncateOrZeroExtend(S, CalculationTy));
1063 }
1064
1065 // Divide by 2^T
1066 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1067
1068 // Truncate the result, and divide by K! / 2^T.
1069
1070 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1071 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1072}
1073
1074/// Return the value of this chain of recurrences at the specified iteration
1075/// number. We can evaluate this recurrence by multiplying each element in the
1076/// chain by the binomial coefficient corresponding to it. In other words, we
1077/// can evaluate {A,+,B,+,C,+,D} as:
1078///
1079/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1080///
1081/// where BC(It, k) stands for binomial coefficient.
1083 ScalarEvolution &SE) const {
1084 return evaluateAtIteration(operands(), It, SE);
1085}
1086
1088 const SCEV *It,
1089 ScalarEvolution &SE) {
1090 assert(Operands.size() > 0);
1091 const SCEV *Result = Operands[0].getPointer();
1092 for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
1093 // The computation is correct in the face of overflow provided that the
1094 // multiplication is performed _after_ the evaluation of the binomial
1095 // coefficient.
1096 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
1097 if (isa<SCEVCouldNotCompute>(Coeff))
1098 return Coeff;
1099
1100 Result =
1101 SE.getAddExpr(Result, SE.getMulExpr(Operands[i].getPointer(), Coeff));
1102 }
1103 return Result;
1104}
1105
1106//===----------------------------------------------------------------------===//
1107// SCEV Expression folder implementations
1108//===----------------------------------------------------------------------===//
1109
1110/// The SCEVCastSinkingRewriter takes a scalar evolution expression,
1111/// which computes a pointer-typed value, and rewrites the whole expression
1112/// tree so that *all* the computations are done on integers, and the only
1113/// pointer-typed operands in the expression are SCEVUnknown.
1114/// The CreatePtrCast callback is invoked to create the actual conversion
1115/// (ptrtoint or ptrtoaddr) at the SCEVUnknown leaves.
1117 : public SCEVRewriteVisitor<SCEVCastSinkingRewriter> {
1119 using ConversionFn = function_ref<const SCEV *(const SCEVUnknown *)>;
1120 Type *TargetTy;
1121 ConversionFn CreatePtrCast;
1122
1123public:
1125 ConversionFn CreatePtrCast)
1126 : Base(SE), TargetTy(TargetTy), CreatePtrCast(std::move(CreatePtrCast)) {}
1127
1128 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
1129 Type *TargetTy, ConversionFn CreatePtrCast) {
1130 SCEVCastSinkingRewriter Rewriter(SE, TargetTy, std::move(CreatePtrCast));
1131 return Rewriter.visit(Scev);
1132 }
1133
1134 const SCEV *visit(const SCEV *S) {
1135 Type *STy = S->getType();
1136 // If the expression is not pointer-typed, just keep it as-is.
1137 if (!STy->isPointerTy())
1138 return S;
1139 // Else, recursively sink the cast down into it.
1140 return Base::visit(S);
1141 }
1142
1143 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
1144 // Preserve wrap flags on rewritten SCEVAddExpr, which the default
1145 // implementation drops.
1146 SmallVector<SCEVUse, 2> Operands;
1147 bool Changed = false;
1148 for (SCEVUse Op : Expr->operands()) {
1149 Operands.push_back(visit(Op.getPointer()));
1150 Changed |= Op.getPointer() != Operands.back();
1151 }
1152 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
1153 }
1154
1155 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
1156 SmallVector<SCEVUse, 2> Operands;
1157 bool Changed = false;
1158 for (SCEVUse Op : Expr->operands()) {
1159 Operands.push_back(visit(Op.getPointer()));
1160 Changed |= Op.getPointer() != Operands.back();
1161 }
1162 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
1163 }
1164
1165 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
1166 assert(Expr->getType()->isPointerTy() &&
1167 "Should only reach pointer-typed SCEVUnknown's.");
1168 // Perform some basic constant folding. If the operand of the cast is a
1169 // null pointer, don't create a cast SCEV expression (that will be left
1170 // as-is), but produce a zero constant.
1172 return SE.getZero(TargetTy);
1173 return CreatePtrCast(Expr);
1174 }
1175};
1176
1178 assert(Op->getType()->isPointerTy() && "Op must be a pointer");
1179
1180 // Treat pointers with unstable representation conservatively, since the
1181 // address bits may change.
1182 if (DL.hasUnstableRepresentation(Op->getType()))
1183 return getCouldNotCompute();
1184
1185 Type *Ty = DL.getAddressType(Op->getType());
1186
1187 // Use the rewriter to sink the cast down to SCEVUnknown leaves.
1188 // The rewriter handles null pointer constant folding.
1190 Op, *this, Ty, [this, Ty](const SCEVUnknown *U) {
1192 ID.AddInteger(scPtrToAddr);
1193 ID.AddPointer(U);
1194 ID.AddPointer(Ty);
1195 void *IP = nullptr;
1196 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1197 return S;
1198 SCEV *S = new (SCEVAllocator)
1199 SCEVPtrToAddrExpr(ID.Intern(SCEVAllocator), U, Ty);
1200 UniqueSCEVs.InsertNode(S, IP);
1201 S->computeAndSetCanonical(*this);
1202 registerUser(S, U);
1203 return static_cast<const SCEV *>(S);
1204 });
1205 assert(IntOp->getType()->isIntegerTy() &&
1206 "We must have succeeded in sinking the cast, "
1207 "and ending up with an integer-typed expression!");
1208 return IntOp;
1209}
1210
1212 assert(Ty->isIntegerTy() && "Target type must be an integer type!");
1213
1214 // We don't model ptrtoint in SCEV. Return CouldNotCompute, which will cause
1215 // callers to fall back to SCEVUnknown.
1216 return getCouldNotCompute();
1217}
1218
1220 unsigned Depth) {
1221 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1222 "This is not a truncating conversion!");
1223 assert(isSCEVable(Ty) &&
1224 "This is not a conversion to a SCEVable type!");
1225 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
1226 Ty = getEffectiveSCEVType(Ty);
1227
1229 ID.AddInteger(scTruncate);
1230 ID.AddPointer(Op);
1231 ID.AddPointer(Ty);
1232 void *IP = nullptr;
1233 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1234
1235 // Fold if the operand is constant.
1236 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1237 return getConstant(
1238 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1239
1240 // trunc(trunc(x)) --> trunc(x)
1242 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1243
1244 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1246 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1247
1248 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1250 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1251
1252 if (Depth > MaxCastDepth) {
1253 SCEV *S =
1254 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1255 UniqueSCEVs.InsertNode(S, IP);
1256 S->computeAndSetCanonical(*this);
1257 registerUser(S, Op);
1258 return S;
1259 }
1260
1261 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1262 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1263 // if after transforming we have at most one truncate, not counting truncates
1264 // that replace other casts.
1266 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1267 SmallVector<SCEVUse, 4> Operands;
1268 unsigned numTruncs = 0;
1269 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1270 ++i) {
1271 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1272 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
1274 numTruncs++;
1275 Operands.push_back(S);
1276 }
1277 if (numTruncs < 2) {
1278 if (isa<SCEVAddExpr>(Op))
1279 return getAddExpr(Operands);
1280 if (isa<SCEVMulExpr>(Op))
1281 return getMulExpr(Operands);
1282 llvm_unreachable("Unexpected SCEV type for Op.");
1283 }
1284 // Although we checked in the beginning that ID is not in the cache, it is
1285 // possible that during recursion and different modification ID was inserted
1286 // into the cache. So if we find it, just return it.
1287 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1288 return S;
1289 }
1290
1291 // If the input value is a chrec scev, truncate the chrec's operands.
1292 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1293 SmallVector<SCEVUse, 4> Operands;
1294 for (const SCEV *Op : AddRec->operands())
1295 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1296 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1297 }
1298
1299 // Return zero if truncating to known zeros.
1300 uint32_t MinTrailingZeros = getMinTrailingZeros(Op);
1301 if (MinTrailingZeros >= getTypeSizeInBits(Ty))
1302 return getZero(Ty);
1303
1304 // The cast wasn't folded; create an explicit cast node. We can reuse
1305 // the existing insert position since if we get here, we won't have
1306 // made any changes which would invalidate it.
1307 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1308 Op, Ty);
1309 UniqueSCEVs.InsertNode(S, IP);
1310 S->computeAndSetCanonical(*this);
1311 registerUser(S, Op);
1312 return S;
1313}
1314
1315// Get the limit of a recurrence such that incrementing by Step cannot cause
1316// signed overflow as long as the value of the recurrence within the
1317// loop does not exceed this limit before incrementing.
1318static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1319 ICmpInst::Predicate *Pred,
1320 ScalarEvolution *SE) {
1321 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1322 if (SE->isKnownPositive(Step)) {
1323 *Pred = ICmpInst::ICMP_SLT;
1325 SE->getSignedRangeMax(Step));
1326 }
1327 if (SE->isKnownNegative(Step)) {
1328 *Pred = ICmpInst::ICMP_SGT;
1330 SE->getSignedRangeMin(Step));
1331 }
1332 return nullptr;
1333}
1334
1335// Get the limit of a recurrence such that incrementing by Step cannot cause
1336// unsigned overflow as long as the value of the recurrence within the loop does
1337// not exceed this limit before incrementing.
1339 ICmpInst::Predicate *Pred,
1340 ScalarEvolution *SE) {
1341 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1342 *Pred = ICmpInst::ICMP_ULT;
1343
1345 SE->getUnsignedRangeMax(Step));
1346}
1347
1348namespace {
1349
1350struct ExtendOpTraitsBase {
1351 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1352 unsigned);
1353};
1354
1355// Used to make code generic over signed and unsigned overflow.
1356template <typename ExtendOp> struct ExtendOpTraits {
1357 // Members present:
1358 //
1359 // static const SCEV::NoWrapFlags WrapType;
1360 //
1361 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1362 //
1363 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1364 // ICmpInst::Predicate *Pred,
1365 // ScalarEvolution *SE);
1366};
1367
1368template <>
1369struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1370 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1371
1372 static const GetExtendExprTy GetExtendExpr;
1373
1374 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1375 ICmpInst::Predicate *Pred,
1376 ScalarEvolution *SE) {
1377 return getSignedOverflowLimitForStep(Step, Pred, SE);
1378 }
1379};
1380
1381const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1383
1384template <>
1385struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1386 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1387
1388 static const GetExtendExprTy GetExtendExpr;
1389
1390 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1391 ICmpInst::Predicate *Pred,
1392 ScalarEvolution *SE) {
1393 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1394 }
1395};
1396
1397const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1399
1400} // end anonymous namespace
1401
1402// The recurrence AR has been shown to have no signed/unsigned wrap or something
1403// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1404// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1405// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1406// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1407// expression "Step + sext/zext(PreIncAR)" is congruent with
1408// "sext/zext(PostIncAR)"
1409template <typename ExtendOpTy>
1410static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1411 ScalarEvolution *SE, unsigned Depth) {
1412 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1413 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1414
1415 const Loop *L = AR->getLoop();
1416 const SCEV *Start = AR->getStart();
1417 const SCEV *Step = AR->getStepRecurrence(*SE);
1418
1419 // Check for a simple looking step prior to loop entry.
1420 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1421 if (!SA)
1422 return nullptr;
1423
1424 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1425 // subtraction is expensive. For this purpose, perform a quick and dirty
1426 // difference, by checking for Step in the operand list. Note, that
1427 // SA might have repeated ops, like %a + %a + ..., so only remove one.
1428 SmallVector<SCEVUse, 4> DiffOps(SA->operands());
1429 for (auto It = DiffOps.begin(); It != DiffOps.end(); ++It)
1430 if (*It == Step) {
1431 DiffOps.erase(It);
1432 break;
1433 }
1434
1435 if (DiffOps.size() == SA->getNumOperands())
1436 return nullptr;
1437
1438 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1439 // `Step`:
1440
1441 // 1. NSW/NUW flags on the step increment.
1442 auto PreStartFlags =
1444 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1446 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1447
1448 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1449 // "S+X does not sign/unsign-overflow".
1450 //
1451
1452 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1453 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
1454 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1455 return PreStart;
1456
1457 // 2. Direct overflow check on the step operation's expression.
1458 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1459 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1460 const SCEV *OperandExtendedStart =
1461 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1462 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1463 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1464 if (PreAR && any(AR->getNoWrapFlags(WrapType))) {
1465 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1466 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1467 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1468 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
1469 }
1470 return PreStart;
1471 }
1472
1473 // 3. Loop precondition.
1475 const SCEV *OverflowLimit =
1476 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1477
1478 if (OverflowLimit &&
1479 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1480 return PreStart;
1481
1482 return nullptr;
1483}
1484
1485// Get the normalized zero or sign extended expression for this AddRec's Start.
1486template <typename ExtendOpTy>
1487static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1488 ScalarEvolution *SE,
1489 unsigned Depth) {
1490 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1491
1492 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1493 if (!PreStart)
1494 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1495
1496 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1497 Depth),
1498 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1499}
1500
1501// Try to prove away overflow by looking at "nearby" add recurrences. A
1502// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1503// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1504//
1505// Formally:
1506//
1507// {S,+,X} == {S-T,+,X} + T
1508// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1509//
1510// If ({S-T,+,X} + T) does not overflow ... (1)
1511//
1512// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1513//
1514// If {S-T,+,X} does not overflow ... (2)
1515//
1516// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1517// == {Ext(S-T)+Ext(T),+,Ext(X)}
1518//
1519// If (S-T)+T does not overflow ... (3)
1520//
1521// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1522// == {Ext(S),+,Ext(X)} == LHS
1523//
1524// Thus, if (1), (2) and (3) are true for some T, then
1525// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1526//
1527// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1528// does not overflow" restricted to the 0th iteration. Therefore we only need
1529// to check for (1) and (2).
1530//
1531// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1532// is `Delta` (defined below).
1533template <typename ExtendOpTy>
1534bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1535 const SCEV *Step,
1536 const Loop *L) {
1537 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1538
1539 // We restrict `Start` to a constant to prevent SCEV from spending too much
1540 // time here. It is correct (but more expensive) to continue with a
1541 // non-constant `Start` and do a general SCEV subtraction to compute
1542 // `PreStart` below.
1543 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1544 if (!StartC)
1545 return false;
1546
1547 APInt StartAI = StartC->getAPInt();
1548
1549 for (unsigned Delta : {-2, -1, 1, 2}) {
1550 const SCEV *PreStart = getConstant(StartAI - Delta);
1551
1552 FoldingSetNodeID ID;
1553 ID.AddInteger(scAddRecExpr);
1554 ID.AddPointer(PreStart);
1555 ID.AddPointer(Step);
1556 ID.AddPointer(L);
1557 void *IP = nullptr;
1558 const auto *PreAR =
1559 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1560
1561 // Give up if we don't already have the add recurrence we need because
1562 // actually constructing an add recurrence is relatively expensive.
1563 if (PreAR && any(PreAR->getNoWrapFlags(WrapType))) { // proves (2)
1564 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1566 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1567 DeltaS, &Pred, this);
1568 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1569 return true;
1570 }
1571 }
1572
1573 return false;
1574}
1575
1576// Finds an integer D for an expression (C + x + y + ...) such that the top
1577// level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1578// unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1579// maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1580// the (C + x + y + ...) expression is \p WholeAddExpr.
1582 const SCEVConstant *ConstantTerm,
1583 const SCEVAddExpr *WholeAddExpr) {
1584 const APInt &C = ConstantTerm->getAPInt();
1585 const unsigned BitWidth = C.getBitWidth();
1586 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1587 uint32_t TZ = BitWidth;
1588 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1589 TZ = std::min(TZ, SE.getMinTrailingZeros(WholeAddExpr->getOperand(I)));
1590 if (TZ) {
1591 // Set D to be as many least significant bits of C as possible while still
1592 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1593 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1594 }
1595 return APInt(BitWidth, 0);
1596}
1597
1598// Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1599// level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1600// number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1601// ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1603 const APInt &ConstantStart,
1604 const SCEV *Step) {
1605 const unsigned BitWidth = ConstantStart.getBitWidth();
1606 const uint32_t TZ = SE.getMinTrailingZeros(Step);
1607 if (TZ)
1608 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1609 : ConstantStart;
1610 return APInt(BitWidth, 0);
1611}
1612
1614 const ScalarEvolution::FoldID &ID, const SCEV *S,
1617 &FoldCacheUser) {
1618 auto I = FoldCache.insert({ID, S});
1619 if (!I.second) {
1620 // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
1621 // entry.
1622 auto &UserIDs = FoldCacheUser[I.first->second];
1623 assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
1624 for (unsigned I = 0; I != UserIDs.size(); ++I)
1625 if (UserIDs[I] == ID) {
1626 std::swap(UserIDs[I], UserIDs.back());
1627 break;
1628 }
1629 UserIDs.pop_back();
1630 I.first->second = S;
1631 }
1632 FoldCacheUser[S].push_back(ID);
1633}
1634
1635const SCEV *
1637 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1638 "This is not an extending conversion!");
1639 assert(isSCEVable(Ty) &&
1640 "This is not a conversion to a SCEVable type!");
1641 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1642 Ty = getEffectiveSCEVType(Ty);
1643
1644 FoldID ID(scZeroExtend, Op, Ty);
1645 if (const SCEV *S = FoldCache.lookup(ID))
1646 return S;
1647
1648 const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
1650 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
1651 return S;
1652}
1653
1655 unsigned Depth) {
1656 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1657 "This is not an extending conversion!");
1658 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
1659 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1660
1661 // Fold if the operand is constant.
1662 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1663 return getConstant(SC->getAPInt().zext(getTypeSizeInBits(Ty)));
1664
1665 // zext(zext(x)) --> zext(x)
1667 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1668
1669 // If the operand is an affine AddRec with the no-unsigned-wrap flag, the
1670 // zero-extension distributes over the recurrence.
1671 const SCEV *Start, *Step;
1672 const Loop *L;
1673 if (Depth <= MaxCastDepth &&
1674 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1675 const auto *AR = cast<SCEVAddRecExpr>(Op);
1676 if (AR->hasNoUnsignedWrap()) {
1677 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1678 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1679 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1680 }
1681 }
1682
1683 // Before doing any expensive analysis, check to see if we've already
1684 // computed a SCEV for this Op and Ty.
1686 ID.AddInteger(scZeroExtend);
1687 ID.AddPointer(Op);
1688 ID.AddPointer(Ty);
1689 void *IP = nullptr;
1690 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1691 if (Depth > MaxCastDepth) {
1692 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1693 Op, Ty);
1694 UniqueSCEVs.InsertNode(S, IP);
1695 S->computeAndSetCanonical(*this);
1696 registerUser(S, Op);
1697 return S;
1698 }
1699
1700 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1702 // It's possible the bits taken off by the truncate were all zero bits. If
1703 // so, we should be able to simplify this further.
1704 const SCEV *X = ST->getOperand();
1706 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1707 unsigned NewBits = getTypeSizeInBits(Ty);
1708 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1709 CR.zextOrTrunc(NewBits)))
1710 return getTruncateOrZeroExtend(X, Ty, Depth);
1711 }
1712
1713 // If the input value is a chrec scev, and we can prove that the value
1714 // did not overflow the old, smaller, value, we can zero extend all of the
1715 // operands (often constants). This allows analysis of something like
1716 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1717 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
1718 const auto *AR = cast<SCEVAddRecExpr>(Op);
1719 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1720
1721 // The no-unsigned-wrap case is handled before the uniquing lookup above.
1722
1723 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1724 // Note that this serves two purposes: It filters out loops that are
1725 // simply not analyzable, and it covers the case where this code is
1726 // being called from within backedge-taken count analysis, such that
1727 // attempting to ask for the backedge-taken count would likely result
1728 // in infinite recursion. In the later case, the analysis code will
1729 // cope with a conservative value, and it will take care to purge
1730 // that value once it has finished.
1731 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1732 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1733 // Manually compute the final value for AR, checking for overflow.
1734
1735 // Check whether the backedge-taken count can be losslessly casted to
1736 // the addrec's type. The count is always unsigned.
1737 const SCEV *CastedMaxBECount =
1738 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1739 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1740 CastedMaxBECount, MaxBECount->getType(), Depth);
1741 if (MaxBECount == RecastedMaxBECount) {
1742 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1743 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1744 const SCEV *ZMul =
1745 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
1746 const SCEV *ZAdd = getZeroExtendExpr(
1747 getAddExpr(Start, ZMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
1748 Depth + 1);
1749 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1750 const SCEV *WideMaxBECount =
1751 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1752 const SCEV *OperandExtendedAdd =
1753 getAddExpr(WideStart,
1754 getMulExpr(WideMaxBECount,
1755 getZeroExtendExpr(Step, WideTy, Depth + 1),
1758 if (ZAdd == OperandExtendedAdd) {
1759 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1760 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1761 // Return the expression with the addrec on the outside.
1762 Start =
1764 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1765 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1766 }
1767 // Similar to above, only this time treat the step value as signed.
1768 // This covers loops that count down.
1769 OperandExtendedAdd =
1770 getAddExpr(WideStart,
1771 getMulExpr(WideMaxBECount,
1772 getSignExtendExpr(Step, WideTy, Depth + 1),
1775 if (ZAdd == OperandExtendedAdd) {
1776 // Cache knowledge of AR NW, which is propagated to this AddRec.
1777 // Negative step causes unsigned wrap, but it still can't self-wrap.
1778 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1779 // Return the expression with the addrec on the outside.
1780 Start =
1782 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1783 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1784 }
1785 }
1786 }
1787
1788 // Normally, in the cases we can prove no-overflow via a
1789 // backedge guarding condition, we can also compute a backedge
1790 // taken count for the loop. The exceptions are assumptions and
1791 // guards present in the loop -- SCEV is not great at exploiting
1792 // these to compute max backedge taken counts, but can still use
1793 // these to prove lack of overflow. Use this fact to avoid
1794 // doing extra work that may not pay off.
1795 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1796 !AC.assumptions().empty()) {
1797
1798 auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
1799 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
1800 if (AR->hasNoUnsignedWrap()) {
1801 // Same as nuw case above - duplicated here to avoid a compile time
1802 // issue. It's not clear that the order of checks does matter, but
1803 // it's one of two issue possible causes for a change which was
1804 // reverted. Be conservative for the moment.
1805 Start =
1807 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1808 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1809 }
1810
1811 // For a negative step, we can extend the operands iff doing so only
1812 // traverses values in the range zext([0,UINT_MAX]).
1813 if (isKnownNegative(Step)) {
1814 const SCEV *N =
1818 // Cache knowledge of AR NW, which is propagated to this
1819 // AddRec. Negative step causes unsigned wrap, but it
1820 // still can't self-wrap.
1821 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
1822 // Return the expression with the addrec on the outside.
1823 Start =
1825 Step = getSignExtendExpr(Step, Ty, Depth + 1);
1826 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1827 }
1828 }
1829 }
1830
1831 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1832 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1833 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1834 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1835 const APInt &C = SC->getAPInt();
1836 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1837 if (D != 0) {
1838 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1839 const SCEV *SResidual =
1840 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1841 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1842 return getAddExpr(SZExtD, SZExtR, SCEV::FlagNSW | SCEV::FlagNUW,
1843 Depth + 1);
1844 }
1845 }
1846
1847 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1848 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
1849 Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
1850 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
1851 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
1852 }
1853 }
1854
1855 // zext(A % B) --> zext(A) % zext(B)
1856 {
1857 const SCEV *LHS;
1858 const SCEV *RHS;
1859 if (match(Op, m_scev_URem(m_SCEV(LHS), m_SCEV(RHS), *this)))
1860 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1861 getZeroExtendExpr(RHS, Ty, Depth + 1));
1862 }
1863
1864 // zext(A / B) --> zext(A) / zext(B).
1865 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1866 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1867 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1868
1869 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1870 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1871 if (SA->hasNoUnsignedWrap()) {
1872 // If the addition does not unsign overflow then we can, by definition,
1873 // commute the zero extension with the addition operation.
1875 for (SCEVUse Op : SA->operands())
1876 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1877 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1878 }
1879
1880 const APInt *C, *C2;
1881 // zext (C + A)<nsw> -> (sext(C) + sext(A))<nsw> if zext (C + A)<nsw> >=s 0.
1882 // Currently the non-negative check is done manually, as isKnownNonNegative
1883 // is too expensive.
1884 if (SA->hasNoSignedWrap() &&
1886 m_scev_SMax(m_scev_APInt(C2), m_SCEV()))) &&
1887 C->isNegative() && !C->isMinSignedValue() && C2->sge(C->abs())) {
1888 assert(isKnownNonNegative(SA) && "incorrectly determined non-negative");
1889 return getAddExpr(getSignExtendExpr(SA->getOperand(0), Ty, Depth + 1),
1890 getSignExtendExpr(SA->getOperand(1), Ty, Depth + 1),
1891 SCEV::FlagNSW, Depth + 1);
1892 }
1893
1894 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1895 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1896 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1897 //
1898 // Often address arithmetics contain expressions like
1899 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1900 // This transformation is useful while proving that such expressions are
1901 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1902 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1903 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1904 if (D != 0) {
1905 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1906 const SCEV *SResidual =
1908 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1909 return getAddExpr(SZExtD, SZExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
1910 Depth + 1);
1911 }
1912 }
1913 }
1914
1915 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1916 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1917 if (SM->hasNoUnsignedWrap()) {
1918 // If the multiply does not unsign overflow then we can, by definition,
1919 // commute the zero extension with the multiply operation.
1921 for (SCEVUse Op : SM->operands())
1922 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1923 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1924 }
1925
1926 // zext(2^K * (trunc X to iN)) to iM ->
1927 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1928 //
1929 // Proof:
1930 //
1931 // zext(2^K * (trunc X to iN)) to iM
1932 // = zext((trunc X to iN) << K) to iM
1933 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1934 // (because shl removes the top K bits)
1935 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1936 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1937 //
1938 const APInt *C;
1939 const SCEV *TruncRHS;
1940 if (match(SM,
1941 m_scev_Mul(m_scev_APInt(C), m_scev_Trunc(m_SCEV(TruncRHS)))) &&
1942 C->isPowerOf2()) {
1943 int NewTruncBits =
1944 getTypeSizeInBits(SM->getOperand(1)->getType()) - C->logBase2();
1945 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1946 return getMulExpr(
1947 getZeroExtendExpr(SM->getOperand(0), Ty),
1948 getZeroExtendExpr(getTruncateExpr(TruncRHS, NewTruncTy), Ty),
1949 SCEV::FlagNUW, Depth + 1);
1950 }
1951 }
1952
1953 // zext(umin(x, y)) -> umin(zext(x), zext(y))
1954 // zext(umax(x, y)) -> umax(zext(x), zext(y))
1957 SmallVector<SCEVUse, 4> Operands;
1958 for (SCEVUse Operand : MinMax->operands())
1959 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1961 return getUMinExpr(Operands);
1962 return getUMaxExpr(Operands);
1963 }
1964
1965 // zext(umin_seq(x, y)) -> umin_seq(zext(x), zext(y))
1967 assert(isa<SCEVSequentialUMinExpr>(MinMax) && "Not supported!");
1968 SmallVector<SCEVUse, 4> Operands;
1969 for (SCEVUse Operand : MinMax->operands())
1970 Operands.push_back(getZeroExtendExpr(Operand, Ty));
1971 return getUMinExpr(Operands, /*Sequential*/ true);
1972 }
1973
1974 // The cast wasn't folded; create an explicit cast node.
1975 // Recompute the insert position, as it may have been invalidated.
1976 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1977 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1978 Op, Ty);
1979 UniqueSCEVs.InsertNode(S, IP);
1980 S->computeAndSetCanonical(*this);
1981 registerUser(S, Op);
1982 return S;
1983}
1984
1985const SCEV *
1987 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1988 "This is not an extending conversion!");
1989 assert(isSCEVable(Ty) &&
1990 "This is not a conversion to a SCEVable type!");
1991 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
1992 Ty = getEffectiveSCEVType(Ty);
1993
1994 FoldID ID(scSignExtend, Op, Ty);
1995 if (const SCEV *S = FoldCache.lookup(ID))
1996 return S;
1997
1998 const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
2000 insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
2001 return S;
2002}
2003
2005 unsigned Depth) {
2006 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2007 "This is not an extending conversion!");
2008 assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
2009 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
2010 Ty = getEffectiveSCEVType(Ty);
2011
2012 // Fold if the operand is constant.
2013 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2014 return getConstant(SC->getAPInt().sext(getTypeSizeInBits(Ty)));
2015
2016 // sext(sext(x)) --> sext(x)
2018 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
2019
2020 // sext(zext(x)) --> zext(x)
2022 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
2023
2024 // If the operand is an affine AddRec with the no-signed-wrap flag, the
2025 // sign-extension distributes over the recurrence.
2026 const SCEV *Start, *Step;
2027 const Loop *L;
2028 if (Depth <= MaxCastDepth &&
2029 match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2030 const auto *AR = cast<SCEVAddRecExpr>(Op);
2031 if (AR->hasNoSignedWrap()) {
2032 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2033 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2034 return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
2035 }
2036 }
2037
2038 // Before doing any expensive analysis, check to see if we've already
2039 // computed a SCEV for this Op and Ty.
2041 ID.AddInteger(scSignExtend);
2042 ID.AddPointer(Op);
2043 ID.AddPointer(Ty);
2044 void *IP = nullptr;
2045 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2046 // Limit recursion depth.
2047 if (Depth > MaxCastDepth) {
2048 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2049 Op, Ty);
2050 UniqueSCEVs.InsertNode(S, IP);
2051 S->computeAndSetCanonical(*this);
2052 registerUser(S, Op);
2053 return S;
2054 }
2055
2056 // sext(trunc(x)) --> sext(x) or x or trunc(x)
2058 // It's possible the bits taken off by the truncate were all sign bits. If
2059 // so, we should be able to simplify this further.
2060 const SCEV *X = ST->getOperand();
2062 unsigned TruncBits = getTypeSizeInBits(ST->getType());
2063 unsigned NewBits = getTypeSizeInBits(Ty);
2064 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
2065 CR.sextOrTrunc(NewBits)))
2066 return getTruncateOrSignExtend(X, Ty, Depth);
2067 }
2068
2069 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
2070 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
2071 if (SA->hasNoSignedWrap()) {
2072 // If the addition does not sign overflow then we can, by definition,
2073 // commute the sign extension with the addition operation.
2075 for (SCEVUse Op : SA->operands())
2076 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2077 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2078 }
2079
2080 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2081 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2082 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2083 //
2084 // For instance, this will bring two seemingly different expressions:
2085 // 1 + sext(5 + 20 * %x + 24 * %y) and
2086 // sext(6 + 20 * %x + 24 * %y)
2087 // to the same form:
2088 // 2 + sext(4 + 20 * %x + 24 * %y)
2089 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2090 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2091 if (D != 0) {
2092 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2093 const SCEV *SResidual =
2095 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2096 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2097 Depth + 1);
2098 }
2099 }
2100 }
2101 // If the input value is a chrec scev, and we can prove that the value
2102 // did not overflow the old, smaller, value, we can sign extend all of the
2103 // operands (often constants). This allows analysis of something like
2104 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2105 if (match(Op, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Step), m_Loop(L)))) {
2106 const auto *AR = cast<SCEVAddRecExpr>(Op);
2107 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2108
2109 // The no-signed-wrap case is handled before the uniquing lookup above.
2110
2111 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2112 // Note that this serves two purposes: It filters out loops that are
2113 // simply not analyzable, and it covers the case where this code is
2114 // being called from within backedge-taken count analysis, such that
2115 // attempting to ask for the backedge-taken count would likely result
2116 // in infinite recursion. In the later case, the analysis code will
2117 // cope with a conservative value, and it will take care to purge
2118 // that value once it has finished.
2119 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2120 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2121 // Manually compute the final value for AR, checking for
2122 // overflow.
2123
2124 // Check whether the backedge-taken count can be losslessly casted to
2125 // the addrec's type. The count is always unsigned.
2126 const SCEV *CastedMaxBECount =
2127 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2128 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2129 CastedMaxBECount, MaxBECount->getType(), Depth);
2130 if (MaxBECount == RecastedMaxBECount) {
2131 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2132 // Check whether Start+Step*MaxBECount has no signed overflow.
2133 const SCEV *SMul =
2134 getMulExpr(CastedMaxBECount, Step, SCEV::FlagAnyWrap, Depth + 1);
2135 const SCEV *SAdd = getSignExtendExpr(
2136 getAddExpr(Start, SMul, SCEV::FlagAnyWrap, Depth + 1), WideTy,
2137 Depth + 1);
2138 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2139 const SCEV *WideMaxBECount =
2140 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2141 const SCEV *OperandExtendedAdd =
2142 getAddExpr(WideStart,
2143 getMulExpr(WideMaxBECount,
2144 getSignExtendExpr(Step, WideTy, Depth + 1),
2147 if (SAdd == OperandExtendedAdd) {
2148 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2149 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2150 // Return the expression with the addrec on the outside.
2151 Start =
2153 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2154 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2155 }
2156 // Similar to above, only this time treat the step value as unsigned.
2157 // This covers loops that count up with an unsigned step.
2158 OperandExtendedAdd =
2159 getAddExpr(WideStart,
2160 getMulExpr(WideMaxBECount,
2161 getZeroExtendExpr(Step, WideTy, Depth + 1),
2164 if (SAdd == OperandExtendedAdd) {
2165 // If AR wraps around then
2166 //
2167 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2168 // => SAdd != OperandExtendedAdd
2169 //
2170 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2171 // (SAdd == OperandExtendedAdd => AR is NW)
2172
2173 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
2174
2175 // Return the expression with the addrec on the outside.
2176 Start =
2178 Step = getZeroExtendExpr(Step, Ty, Depth + 1);
2179 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2180 }
2181 }
2182 }
2183
2184 auto NewFlags = proveNoSignedWrapViaInduction(AR);
2185 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
2186 if (AR->hasNoSignedWrap()) {
2187 // Same as nsw case above - duplicated here to avoid a compile time
2188 // issue. It's not clear that the order of checks does matter, but
2189 // it's one of two issue possible causes for a change which was
2190 // reverted. Be conservative for the moment.
2191 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2192 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2193 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2194 }
2195
2196 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2197 // if D + (C - D + Step * n) could be proven to not signed wrap
2198 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2199 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2200 const APInt &C = SC->getAPInt();
2201 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2202 if (D != 0) {
2203 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2204 const SCEV *SResidual =
2205 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2206 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2207 return getAddExpr(SSExtD, SSExtR, (SCEV::FlagNSW | SCEV::FlagNUW),
2208 Depth + 1);
2209 }
2210 }
2211
2212 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2213 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
2214 Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
2215 Step = getSignExtendExpr(Step, Ty, Depth + 1);
2216 return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
2217 }
2218 }
2219
2220 // If the input value is provably positive and we could not simplify
2221 // away the sext build a zext instead.
2223 return getZeroExtendExpr(Op, Ty, Depth + 1);
2224
2225 // sext(smin(x, y)) -> smin(sext(x), sext(y))
2226 // sext(smax(x, y)) -> smax(sext(x), sext(y))
2229 SmallVector<SCEVUse, 4> Operands;
2230 for (SCEVUse Operand : MinMax->operands())
2231 Operands.push_back(getSignExtendExpr(Operand, Ty));
2233 return getSMinExpr(Operands);
2234 return getSMaxExpr(Operands);
2235 }
2236
2237 // The cast wasn't folded; create an explicit cast node.
2238 // Recompute the insert position, as it may have been invalidated.
2239 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2240 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2241 Op, Ty);
2242 UniqueSCEVs.InsertNode(S, IP);
2243 S->computeAndSetCanonical(*this);
2244 registerUser(S, Op);
2245 return S;
2246}
2247
2249 Type *Ty) {
2250 switch (Kind) {
2251 case scTruncate:
2252 return getTruncateExpr(Op, Ty);
2253 case scZeroExtend:
2254 return getZeroExtendExpr(Op, Ty);
2255 case scSignExtend:
2256 return getSignExtendExpr(Op, Ty);
2257 case scPtrToAddr: {
2258 const SCEV *Expr = getPtrToAddrExpr(Op);
2259 assert(Expr->getType() == Ty && "requested type must match");
2260 return Expr;
2261 }
2262 case scPtrToInt:
2263 return getPtrToIntExpr(Op, Ty);
2264 default:
2265 llvm_unreachable("Not a SCEV cast expression!");
2266 }
2267}
2268
2269/// getAnyExtendExpr - Return a SCEV for the given operand extended with
2270/// unspecified bits out to the given type.
2272 Type *Ty) {
2273 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2274 "This is not an extending conversion!");
2275 assert(isSCEVable(Ty) &&
2276 "This is not a conversion to a SCEVable type!");
2277 Ty = getEffectiveSCEVType(Ty);
2278
2279 // Sign-extend negative constants.
2280 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2281 if (SC->getAPInt().isNegative())
2282 return getSignExtendExpr(Op, Ty);
2283
2284 // Peel off a truncate cast.
2286 const SCEV *NewOp = T->getOperand();
2287 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2288 return getAnyExtendExpr(NewOp, Ty);
2289 return getTruncateOrNoop(NewOp, Ty);
2290 }
2291
2292 // Next try a zext cast. If the cast is folded, use it.
2293 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2294 if (!isa<SCEVZeroExtendExpr>(ZExt))
2295 return ZExt;
2296
2297 // Next try a sext cast. If the cast is folded, use it.
2298 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2299 if (!isa<SCEVSignExtendExpr>(SExt))
2300 return SExt;
2301
2302 // Force the cast to be folded into the operands of an addrec.
2303 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2305 for (const SCEV *Op : AR->operands())
2306 Ops.push_back(getAnyExtendExpr(Op, Ty));
2307 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2308 }
2309
2310 // If the expression is obviously signed, use the sext cast value.
2311 if (isa<SCEVSMaxExpr>(Op))
2312 return SExt;
2313
2314 // Absent any other information, use the zext cast value.
2315 return ZExt;
2316}
2317
2318/// Process the given Ops list, which is a list of operands to be added under
2319/// the given scale, update the given map. This is a helper function for
2320/// getAddRecExpr. As an example of what it does, given a sequence of operands
2321/// that would form an add expression like this:
2322///
2323/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2324///
2325/// where A and B are constants, update the map with these values:
2326///
2327/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2328///
2329/// and add 13 + A*B*29 to AccumulatedConstant.
2330/// This will allow getAddRecExpr to produce this:
2331///
2332/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2333///
2334/// This form often exposes folding opportunities that are hidden in
2335/// the original operand list.
2336///
2337/// Return true iff it appears that any interesting folding opportunities
2338/// may be exposed. This helps getAddRecExpr short-circuit extra work in
2339/// the common case where no interesting opportunities are present, and
2340/// is also used as a check to avoid infinite recursion.
2343 APInt &AccumulatedConstant,
2345 const APInt &Scale,
2346 ScalarEvolution &SE) {
2347 bool Interesting = false;
2348
2349 // Iterate over the add operands. They are sorted, with constants first.
2350 unsigned i = 0;
2351 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2352 ++i;
2353 // Pull a buried constant out to the outside.
2354 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2355 Interesting = true;
2356 AccumulatedConstant += Scale * C->getAPInt();
2357 }
2358
2359 // Next comes everything else. We're especially interested in multiplies
2360 // here, but they're in the middle, so just visit the rest with one loop.
2361 for (; i != Ops.size(); ++i) {
2363 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2364 APInt NewScale =
2365 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2366 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2367 // A multiplication of a constant with another add; recurse.
2368 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2369 Interesting |= CollectAddOperandsWithScales(
2370 M, NewOps, AccumulatedConstant, Add->operands(), NewScale, SE);
2371 } else {
2372 // A multiplication of a constant with some other value. Update
2373 // the map.
2374 SmallVector<SCEVUse, 4> MulOps(drop_begin(Mul->operands()));
2375 const SCEV *Key = SE.getMulExpr(MulOps);
2376 auto Pair = M.insert({Key, NewScale});
2377 if (Pair.second) {
2378 NewOps.push_back(Pair.first->first);
2379 } else {
2380 Pair.first->second += NewScale;
2381 // The map already had an entry for this value, which may indicate
2382 // a folding opportunity.
2383 Interesting = true;
2384 }
2385 }
2386 } else {
2387 // An ordinary operand. Update the map.
2388 auto Pair = M.insert({Ops[i], Scale});
2389 if (Pair.second) {
2390 NewOps.push_back(Pair.first->first);
2391 } else {
2392 Pair.first->second += Scale;
2393 // The map already had an entry for this value, which may indicate
2394 // a folding opportunity.
2395 Interesting = true;
2396 }
2397 }
2398 }
2399
2400 return Interesting;
2401}
2402
2404 const SCEV *LHS, const SCEV *RHS,
2405 const Instruction *CtxI) {
2407 unsigned);
2408 switch (BinOp) {
2409 default:
2410 llvm_unreachable("Unsupported binary op");
2411 case Instruction::Add:
2413 break;
2414 case Instruction::Sub:
2416 break;
2417 case Instruction::Mul:
2419 break;
2420 }
2421
2422 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
2425
2426 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
2427 auto *NarrowTy = cast<IntegerType>(LHS->getType());
2428 auto *WideTy =
2429 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
2430
2431 const SCEV *A = (this->*Extension)(
2432 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
2433 const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
2434 const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
2435 const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
2436 if (A == B)
2437 return true;
2438 // Can we use context to prove the fact we need?
2439 if (!CtxI)
2440 return false;
2441 // TODO: Support mul.
2442 if (BinOp == Instruction::Mul)
2443 return false;
2444 auto *RHSC = dyn_cast<SCEVConstant>(RHS);
2445 // TODO: Lift this limitation.
2446 if (!RHSC)
2447 return false;
2448 APInt C = RHSC->getAPInt();
2449 unsigned NumBits = C.getBitWidth();
2450 bool IsSub = (BinOp == Instruction::Sub);
2451 bool IsNegativeConst = (Signed && C.isNegative());
2452 // Compute the direction and magnitude by which we need to check overflow.
2453 bool OverflowDown = IsSub ^ IsNegativeConst;
2454 APInt Magnitude = C;
2455 if (IsNegativeConst) {
2456 if (C == APInt::getSignedMinValue(NumBits))
2457 // TODO: SINT_MIN on inversion gives the same negative value, we don't
2458 // want to deal with that.
2459 return false;
2460 Magnitude = -C;
2461 }
2462
2464 if (OverflowDown) {
2465 // To avoid overflow down, we need to make sure that MIN + Magnitude <= LHS.
2466 APInt Min = Signed ? APInt::getSignedMinValue(NumBits)
2467 : APInt::getMinValue(NumBits);
2468 APInt Limit = Min + Magnitude;
2469 return isKnownPredicateAt(Pred, getConstant(Limit), LHS, CtxI);
2470 } else {
2471 // To avoid overflow up, we need to make sure that LHS <= MAX - Magnitude.
2472 APInt Max = Signed ? APInt::getSignedMaxValue(NumBits)
2473 : APInt::getMaxValue(NumBits);
2474 APInt Limit = Max - Magnitude;
2475 return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
2476 }
2477}
2478
2479std::optional<SCEV::NoWrapFlags>
2481 const OverflowingBinaryOperator *OBO) {
2482 // It cannot be done any better.
2483 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
2484 return std::nullopt;
2485
2486 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
2487
2488 if (OBO->hasNoUnsignedWrap())
2490 if (OBO->hasNoSignedWrap())
2492
2493 bool Deduced = false;
2494
2496 const SCEV *LHS = getSCEV(OBO->getOperand(0));
2497 const SCEV *RHS = getSCEV(OBO->getOperand(1));
2498
2499 bool CanUseNSW = true;
2500 const APInt *ShiftAmt;
2501 // Treat `shl %a, C` as `mul %a, 1 << C`.
2502 if (match(OBO, m_Shl(m_Value(), m_APInt(ShiftAmt)))) {
2503 unsigned BitWidth = ShiftAmt->getBitWidth();
2504 if (ShiftAmt->uge(BitWidth))
2505 return std::nullopt;
2506 // NSW only transfers if the shift amount is < BitWidth - 1, as INT_MIN * -1
2507 // overflows.
2508 CanUseNSW = ShiftAmt->ult(BitWidth - 1);
2509 Opcode = Instruction::Mul;
2511 } else if (Opcode != Instruction::Add && Opcode != Instruction::Sub &&
2512 Opcode != Instruction::Mul) {
2513 return std::nullopt;
2514 }
2515
2516 const Instruction *CtxI =
2518 if (!OBO->hasNoUnsignedWrap() &&
2519 willNotOverflow(Opcode, /* Signed */ false, LHS, RHS, CtxI)) {
2521 Deduced = true;
2522 }
2523
2524 if (CanUseNSW && !OBO->hasNoSignedWrap() &&
2525 willNotOverflow(Opcode, /* Signed */ true, LHS, RHS, CtxI)) {
2527 Deduced = true;
2528 }
2529
2530 if (Deduced)
2531 return Flags;
2532 return std::nullopt;
2533}
2534
2535// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2536// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2537// can't-overflow flags for the operation if possible.
2541 SCEV::NoWrapFlags Flags) {
2542 using namespace std::placeholders;
2543
2544 using OBO = OverflowingBinaryOperator;
2545
2546 bool CanAnalyze =
2548 (void)CanAnalyze;
2549 assert(CanAnalyze && "don't call from other places!");
2550
2551 SCEV::NoWrapFlags SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2552 SCEV::NoWrapFlags SignOrUnsignWrap =
2553 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2554
2555 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2556 auto IsKnownNonNegative = [&](SCEVUse U) {
2557 return SE->isKnownNonNegative(U);
2558 };
2559
2560 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2561 Flags = ScalarEvolution::setFlags(Flags, SignOrUnsignMask);
2562
2563 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2564
2565 if (SignOrUnsignWrap != SignOrUnsignMask &&
2566 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2567 isa<SCEVConstant>(Ops[0])) {
2568
2569 auto Opcode = [&] {
2570 switch (Type) {
2571 case scAddExpr:
2572 return Instruction::Add;
2573 case scMulExpr:
2574 return Instruction::Mul;
2575 default:
2576 llvm_unreachable("Unexpected SCEV op.");
2577 }
2578 }();
2579
2580 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2581
2582 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2583 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2585 Opcode, C, OBO::NoSignedWrap);
2586 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2588 }
2589
2590 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2591 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2593 Opcode, C, OBO::NoUnsignedWrap);
2594 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2596 }
2597 }
2598
2599 // <0,+,nonnegative><nw> is also nuw
2600 // TODO: Add corresponding nsw case
2602 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
2603 Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
2605
2606 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
2608 Ops.size() == 2) {
2609 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
2610 if (UDiv->getOperand(1) == Ops[1])
2612 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
2613 if (UDiv->getOperand(1) == Ops[0])
2615 }
2616
2617 return Flags;
2618}
2619
2621 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2622}
2623
2624/// Get a canonical add expression, or something simpler if possible.
2626 SCEV::NoWrapFlags OrigFlags,
2627 unsigned Depth) {
2628 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2629 "only nuw or nsw allowed");
2630 assert(!Ops.empty() && "Cannot get empty add!");
2631 if (Ops.size() == 1) return Ops[0];
2632#ifndef NDEBUG
2633 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2634 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2635 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2636 "SCEVAddExpr operand types don't match!");
2637 unsigned NumPtrs = count_if(
2638 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
2639 assert(NumPtrs <= 1 && "add has at most one pointer operand");
2640#endif
2641
2642 const SCEV *Folded = constantFoldAndGroupOps(
2643 *this, LI, DT, Ops,
2644 [](const APInt &C1, const APInt &C2) { return C1 + C2; },
2645 [](const APInt &C) { return C.isZero(); }, // identity
2646 [](const APInt &C) { return false; }); // absorber
2647 if (Folded)
2648 return Folded;
2649
2650 unsigned Idx = isa<SCEVConstant>(Ops[0]) ? 1 : 0;
2651
2652 // Delay expensive flag strengthening until necessary.
2653 auto ComputeFlags = [this, OrigFlags](ArrayRef<SCEVUse> Ops) {
2654 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
2655 };
2656
2657 // Limit recursion calls depth.
2659 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
2660
2661 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
2662 // Don't strengthen flags if we have no new information.
2663 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
2664 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
2665 Add->setNoWrapFlags(ComputeFlags(Ops));
2666 return S;
2667 }
2668
2669 // Okay, check to see if the same value occurs in the operand list more than
2670 // once. If so, merge them together into an multiply expression. Since we
2671 // sorted the list, these values are required to be adjacent.
2672 Type *Ty = Ops[0]->getType();
2673 bool FoundMatch = false;
2674 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2675 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2676 // Scan ahead to count how many equal operands there are.
2677 unsigned Count = 2;
2678 while (i+Count != e && Ops[i+Count] == Ops[i])
2679 ++Count;
2680 // Merge the values into a multiply.
2681 SCEVUse Scale = getConstant(Ty, Count);
2682 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2683 if (Ops.size() == Count)
2684 return Mul;
2685 Ops[i] = Mul;
2686 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2687 --i; e -= Count - 1;
2688 FoundMatch = true;
2689 }
2690 if (FoundMatch)
2691 return getAddExpr(Ops, OrigFlags, Depth + 1);
2692
2693 // Check for truncates. If all the operands are truncated from the same
2694 // type, see if factoring out the truncate would permit the result to be
2695 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2696 // if the contents of the resulting outer trunc fold to something simple.
2697 auto FindTruncSrcType = [&]() -> Type * {
2698 // We're ultimately looking to fold an addrec of truncs and muls of only
2699 // constants and truncs, so if we find any other types of SCEV
2700 // as operands of the addrec then we bail and return nullptr here.
2701 // Otherwise, we return the type of the operand of a trunc that we find.
2702 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2703 return T->getOperand()->getType();
2704 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2705 SCEVUse LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2706 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2707 return T->getOperand()->getType();
2708 }
2709 return nullptr;
2710 };
2711 if (auto *SrcType = FindTruncSrcType()) {
2712 SmallVector<SCEVUse, 8> LargeOps;
2713 bool Ok = true;
2714 // Check all the operands to see if they can be represented in the
2715 // source type of the truncate.
2716 for (const SCEV *Op : Ops) {
2718 if (T->getOperand()->getType() != SrcType) {
2719 Ok = false;
2720 break;
2721 }
2722 LargeOps.push_back(T->getOperand());
2723 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Op)) {
2724 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2725 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Op)) {
2726 SmallVector<SCEVUse, 8> LargeMulOps;
2727 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2728 if (const SCEVTruncateExpr *T =
2729 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2730 if (T->getOperand()->getType() != SrcType) {
2731 Ok = false;
2732 break;
2733 }
2734 LargeMulOps.push_back(T->getOperand());
2735 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2736 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2737 } else {
2738 Ok = false;
2739 break;
2740 }
2741 }
2742 if (Ok)
2743 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2744 } else {
2745 Ok = false;
2746 break;
2747 }
2748 }
2749 if (Ok) {
2750 // Evaluate the expression in the larger type.
2751 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2752 // If it folds to something simple, use it. Otherwise, don't.
2753 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2754 return getTruncateExpr(Fold, Ty);
2755 }
2756 }
2757
2758 if (Ops.size() == 2) {
2759 // Check if we have an expression of the form ((X + C1) - C2), where C1 and
2760 // C2 can be folded in a way that allows retaining wrapping flags of (X +
2761 // C1).
2762 const SCEV *A = Ops[0];
2763 const SCEV *B = Ops[1];
2764 auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
2765 auto *C = dyn_cast<SCEVConstant>(A);
2766 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
2767 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
2768 auto C2 = C->getAPInt();
2769 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
2770
2771 APInt ConstAdd = C1 + C2;
2772 auto AddFlags = AddExpr->getNoWrapFlags();
2773 // Adding a smaller constant is NUW if the original AddExpr was NUW.
2775 ConstAdd.ule(C1)) {
2776 PreservedFlags =
2778 }
2779
2780 // Adding a constant with the same sign and small magnitude is NSW, if the
2781 // original AddExpr was NSW.
2783 C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
2784 ConstAdd.abs().ule(C1.abs())) {
2785 PreservedFlags =
2787 }
2788
2789 if (PreservedFlags != SCEV::FlagAnyWrap) {
2790 SmallVector<SCEVUse, 4> NewOps(AddExpr->operands());
2791 NewOps[0] = getConstant(ConstAdd);
2792 return getAddExpr(NewOps, PreservedFlags);
2793 }
2794 }
2795
2796 // Try to push the constant operand into a ZExt: A + zext (-A + B) -> zext
2797 // (B), if trunc (A) + -A + B does not unsigned-wrap.
2798 const SCEVAddExpr *InnerAdd;
2799 if (match(B, m_scev_ZExt(m_scev_Add(InnerAdd)))) {
2800 const SCEV *NarrowA = getTruncateExpr(A, InnerAdd->getType());
2801 if (NarrowA == getNegativeSCEV(InnerAdd->getOperand(0)) &&
2802 getZeroExtendExpr(NarrowA, B->getType()) == A &&
2803 hasFlags(StrengthenNoWrapFlags(this, scAddExpr, {NarrowA, InnerAdd},
2805 SCEV::FlagNUW)) {
2806 return getZeroExtendExpr(getAddExpr(NarrowA, InnerAdd), B->getType());
2807 }
2808 }
2809 }
2810
2811 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
2812 const SCEV *Y;
2813 if (Ops.size() == 2 &&
2814 match(Ops[0],
2816 m_scev_URem(m_scev_Specific(Ops[1]), m_SCEV(Y), *this))))
2817 return getMulExpr(Y, getUDivExpr(Ops[1], Y));
2818
2819 // Skip past any other cast SCEVs.
2820 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2821 ++Idx;
2822
2823 // If there are add operands they would be next.
2824 if (Idx < Ops.size()) {
2825 bool DeletedAdd = false;
2826 // If the original flags and all inlined SCEVAddExprs are NUW, use the
2827 // common NUW flag for expression after inlining. Other flags cannot be
2828 // preserved, because they may depend on the original order of operations.
2829 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
2830 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2831 if (Ops.size() > AddOpsInlineThreshold ||
2832 Add->getNumOperands() > AddOpsInlineThreshold)
2833 break;
2834 // If we have an add, expand the add operands onto the end of the operands
2835 // list.
2836 Ops.erase(Ops.begin()+Idx);
2837 append_range(Ops, Add->operands());
2838 DeletedAdd = true;
2839 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
2840 }
2841
2842 // If we deleted at least one add, we added operands to the end of the list,
2843 // and they are not necessarily sorted. Recurse to resort and resimplify
2844 // any operands we just acquired.
2845 if (DeletedAdd)
2846 return getAddExpr(Ops, CommonFlags, Depth + 1);
2847 }
2848
2849 // Skip over the add expression until we get to a multiply.
2850 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2851 ++Idx;
2852
2853 // Check to see if there are any folding opportunities present with
2854 // operands multiplied by constant values.
2855 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2859 APInt AccumulatedConstant(BitWidth, 0);
2860 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2861 Ops, APInt(BitWidth, 1), *this)) {
2862 struct APIntCompare {
2863 bool operator()(const APInt &LHS, const APInt &RHS) const {
2864 return LHS.ult(RHS);
2865 }
2866 };
2867
2868 // Some interesting folding opportunity is present, so its worthwhile to
2869 // re-generate the operands list. Group the operands by constant scale,
2870 // to avoid multiplying by the same constant scale multiple times.
2871 std::map<APInt, SmallVector<SCEVUse, 4>, APIntCompare> MulOpLists;
2872 for (const SCEV *NewOp : NewOps)
2873 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2874 // Re-generate the operands list.
2875 Ops.clear();
2876 if (AccumulatedConstant != 0)
2877 Ops.push_back(getConstant(AccumulatedConstant));
2878 for (auto &MulOp : MulOpLists) {
2879 if (MulOp.first == 1) {
2880 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
2881 } else if (MulOp.first != 0) {
2882 Ops.push_back(getMulExpr(
2883 getConstant(MulOp.first),
2884 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2885 SCEV::FlagAnyWrap, Depth + 1));
2886 }
2887 }
2888 if (Ops.empty())
2889 return getZero(Ty);
2890 if (Ops.size() == 1)
2891 return Ops[0];
2892 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2893 }
2894 }
2895
2896 // Given a SCEVMulExpr and an operand index, return the product of all
2897 // operands except the one at OpIdx.
2898 auto StripFactor = [&](const SCEVMulExpr *M, unsigned OpIdx) -> SCEVUse {
2899 if (M->getNumOperands() == 2)
2900 return M->getOperand(OpIdx == 0);
2901 SmallVector<SCEVUse, 4> Remaining(M->operands().take_front(OpIdx));
2902 append_range(Remaining, M->operands().drop_front(OpIdx + 1));
2903 return getMulExpr(Remaining, SCEV::FlagAnyWrap, Depth + 1);
2904 };
2905
2906 // If we are adding something to a multiply expression, make sure the
2907 // something is not already an operand of the multiply. If so, merge it into
2908 // the multiply.
2909 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2910 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2911 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2912 // Scan all terms to find every occurrence of common factor MulOpSCEV
2913 // and fold them in one shot:
2914 // A1*X + A2*X + ... + An*X --> X * (A1 + A2 + ... + An)
2915 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2916 if (isa<SCEVConstant>(MulOpSCEV))
2917 continue;
2918
2919 // Cofactors: 1 for bare addends matching MulOpSCEV, or the
2920 // remaining product for multiply terms containing MulOpSCEV.
2921 SmallVector<SCEVUse, 4> Cofactors;
2922 SmallVector<unsigned, 4> DeadIndices;
2923 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) {
2924 if (MulOpSCEV == Ops[AddOp]) {
2925 // W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2926 Cofactors.push_back(getOne(Ty));
2927 DeadIndices.push_back(AddOp);
2928 continue;
2929 }
2930
2931 if (AddOp <= Idx || !isa<SCEVMulExpr>(Ops[AddOp]))
2932 continue;
2933
2934 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[AddOp]);
2935 for (unsigned OMulOp = 0, OE = OtherMul->getNumOperands(); OMulOp != OE;
2936 ++OMulOp) {
2937 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2938 // (A*B*C) + (A*D*E) --> A * (B*C + D*E)
2939 Cofactors.push_back(StripFactor(OtherMul, OMulOp));
2940 DeadIndices.push_back(AddOp);
2941 break;
2942 }
2943 }
2944 }
2945
2946 // Fold all collected cofactors with the anchor multiply's cofactor:
2947 // MulOpSCEV * (Cofactor_1 + ... + Cofactor_n + AnchorCofactor)
2948 if (!Cofactors.empty()) {
2949 Cofactors.push_back(StripFactor(Mul, MulOp));
2950
2951 SCEVUse InnerSum = getAddExpr(Cofactors, SCEV::FlagAnyWrap, Depth + 1);
2952 SCEVUse OuterMul =
2953 getMulExpr(MulOpSCEV, InnerSum, SCEV::FlagAnyWrap, Depth + 1);
2954
2955 // DeadIndices does not include Idx (the anchor), hence +1.
2956 if (Ops.size() == DeadIndices.size() + 1)
2957 return OuterMul;
2958
2959 // Erase Ops[Idx] first, then erase DeadIndices in reverse order.
2960 // The -1 adjustment accounts for the shift from removing Idx;
2961 // reverse order means each erasure only shifts later positions,
2962 // which have already been processed.
2963 Ops.erase(Ops.begin() + Idx);
2964 for (unsigned Dead : reverse(DeadIndices))
2965 Ops.erase(Ops.begin() + (Dead > Idx ? Dead - 1 : Dead));
2966
2967 Ops.push_back(OuterMul);
2968 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2969 }
2970 }
2971 }
2972
2973 // If there are any add recurrences in the operands list, see if any other
2974 // added values are loop invariant. If so, we can fold them into the
2975 // recurrence.
2976 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2977 ++Idx;
2978
2979 // Scan over all recurrences, trying to fold loop invariants into them.
2980 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2981 // Scan all of the other operands to this add and add them to the vector if
2982 // they are loop invariant w.r.t. the recurrence.
2984 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2985 const Loop *AddRecLoop = AddRec->getLoop();
2986 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2987 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2988 LIOps.push_back(Ops[i]);
2989 Ops.erase(Ops.begin()+i);
2990 --i; --e;
2991 }
2992
2993 // If we found some loop invariants, fold them into the recurrence.
2994 if (!LIOps.empty()) {
2995 // Compute nowrap flags for the addition of the loop-invariant ops and
2996 // the addrec. Temporarily push it as an operand for that purpose. These
2997 // flags are valid in the scope of the addrec only.
2998 LIOps.push_back(AddRec);
2999 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
3000 LIOps.pop_back();
3001
3002 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
3003 LIOps.push_back(AddRec->getStart());
3004
3005 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3006
3007 // It is not in general safe to propagate flags valid on an add within
3008 // the addrec scope to one outside it. We must prove that the inner
3009 // scope is guaranteed to execute if the outer one does to be able to
3010 // safely propagate. We know the program is undefined if poison is
3011 // produced on the inner scoped addrec. We also know that *for this use*
3012 // the outer scoped add can't overflow (because of the flags we just
3013 // computed for the inner scoped add) without the program being undefined.
3014 // Proving that entry to the outer scope neccesitates entry to the inner
3015 // scope, thus proves the program undefined if the flags would be violated
3016 // in the outer scope.
3017 SCEV::NoWrapFlags AddFlags = Flags;
3018 if (AddFlags != SCEV::FlagAnyWrap) {
3019 auto *DefI = getDefiningScopeBound(LIOps);
3020 auto *ReachI = &*AddRecLoop->getHeader()->begin();
3021 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
3022 AddFlags = SCEV::FlagAnyWrap;
3023 }
3024 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
3025
3026 // Build the new addrec. Propagate the NUW and NSW flags if both the
3027 // outer add and the inner addrec are guaranteed to have no overflow.
3028 // Always propagate NW.
3029 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
3030 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
3031
3032 // If all of the other operands were loop invariant, we are done.
3033 if (Ops.size() == 1) return NewRec;
3034
3035 // Otherwise, add the folded AddRec by the non-invariant parts.
3036 for (unsigned i = 0;; ++i)
3037 if (Ops[i] == AddRec) {
3038 Ops[i] = NewRec;
3039 break;
3040 }
3041 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3042 }
3043
3044 // Okay, if there weren't any loop invariants to be folded, check to see if
3045 // there are multiple AddRec's with the same loop induction variable being
3046 // added together. If so, we can fold them.
3047 for (unsigned OtherIdx = Idx+1;
3048 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3049 ++OtherIdx) {
3050 // We expect the AddRecExpr's to be sorted in reverse dominance order,
3051 // so that the 1st found AddRecExpr is dominated by all others.
3052 assert(DT.dominates(
3053 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
3054 AddRec->getLoop()->getHeader()) &&
3055 "AddRecExprs are not sorted in reverse dominance order?");
3056 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
3057 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
3058 SmallVector<SCEVUse, 4> AddRecOps(AddRec->operands());
3059 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3060 ++OtherIdx) {
3061 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3062 if (OtherAddRec->getLoop() == AddRecLoop) {
3063 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
3064 i != e; ++i) {
3065 if (i >= AddRecOps.size()) {
3066 append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
3067 break;
3068 }
3069 AddRecOps[i] =
3070 getAddExpr(AddRecOps[i], OtherAddRec->getOperand(i),
3072 }
3073 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3074 }
3075 }
3076 // Step size has changed, so we cannot guarantee no self-wraparound.
3077 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
3078 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3079 }
3080 }
3081
3082 // Otherwise couldn't fold anything into this recurrence. Move onto the
3083 // next one.
3084 }
3085
3086 // Okay, it looks like we really DO need an add expr. Check to see if we
3087 // already have one, otherwise create a new one.
3088 return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
3089}
3090
3091const SCEV *ScalarEvolution::getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
3092 SCEV::NoWrapFlags Flags) {
3094 ID.AddInteger(scAddExpr);
3095 for (const SCEV *Op : Ops)
3096 ID.AddPointer(Op);
3097 void *IP = nullptr;
3098 SCEVAddExpr *S =
3099 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3100 if (!S) {
3101 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3103 S = new (SCEVAllocator)
3104 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
3105 UniqueSCEVs.InsertNode(S, IP);
3106 S->computeAndSetCanonical(*this);
3107 registerUser(S, Ops);
3108 }
3109 S->setNoWrapFlags(Flags);
3110 return S;
3111}
3112
3113const SCEV *ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops,
3114 const Loop *L,
3115 SCEV::NoWrapFlags Flags) {
3116 FoldingSetNodeID ID;
3117 ID.AddInteger(scAddRecExpr);
3118 for (const SCEV *Op : Ops)
3119 ID.AddPointer(Op);
3120 ID.AddPointer(L);
3121 void *IP = nullptr;
3122 SCEVAddRecExpr *S =
3123 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3124 if (!S) {
3125 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3127 S = new (SCEVAllocator)
3128 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
3129 UniqueSCEVs.InsertNode(S, IP);
3130 S->computeAndSetCanonical(*this);
3131 LoopUsers[L].push_back(S);
3132 registerUser(S, Ops);
3133 }
3134 setNoWrapFlags(S, Flags);
3135 return S;
3136}
3137
3138const SCEV *ScalarEvolution::getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
3139 SCEV::NoWrapFlags Flags) {
3140 FoldingSetNodeID ID;
3141 ID.AddInteger(scMulExpr);
3142 for (const SCEV *Op : Ops)
3143 ID.AddPointer(Op);
3144 void *IP = nullptr;
3145 SCEVMulExpr *S =
3146 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
3147 if (!S) {
3148 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
3150 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
3151 O, Ops.size());
3152 UniqueSCEVs.InsertNode(S, IP);
3153 S->computeAndSetCanonical(*this);
3154 registerUser(S, Ops);
3155 }
3156 S->setNoWrapFlags(Flags);
3157 return S;
3158}
3159
3160static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
3161 uint64_t k = i*j;
3162 if (j > 1 && k / j != i) Overflow = true;
3163 return k;
3164}
3165
3166/// Compute the result of "n choose k", the binomial coefficient. If an
3167/// intermediate computation overflows, Overflow will be set and the return will
3168/// be garbage. Overflow is not cleared on absence of overflow.
3169static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
3170 // We use the multiplicative formula:
3171 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
3172 // At each iteration, we take the n-th term of the numeral and divide by the
3173 // (k-n)th term of the denominator. This division will always produce an
3174 // integral result, and helps reduce the chance of overflow in the
3175 // intermediate computations. However, we can still overflow even when the
3176 // final result would fit.
3177
3178 if (n == 0 || n == k) return 1;
3179 if (k > n) return 0;
3180
3181 if (k > n/2)
3182 k = n-k;
3183
3184 uint64_t r = 1;
3185 for (uint64_t i = 1; i <= k; ++i) {
3186 r = umul_ov(r, n-(i-1), Overflow);
3187 r /= i;
3188 }
3189 return r;
3190}
3191
3192/// Determine if any of the operands in this SCEV are a constant or if
3193/// any of the add or multiply expressions in this SCEV contain a constant.
3194static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
3195 struct FindConstantInAddMulChain {
3196 bool FoundConstant = false;
3197
3198 bool follow(const SCEV *S) {
3199 FoundConstant |= isa<SCEVConstant>(S);
3200 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
3201 }
3202
3203 bool isDone() const {
3204 return FoundConstant;
3205 }
3206 };
3207
3208 FindConstantInAddMulChain F;
3210 ST.visitAll(StartExpr);
3211 return F.FoundConstant;
3212}
3213
3214/// Get a canonical multiply expression, or something simpler if possible.
3216 SCEV::NoWrapFlags OrigFlags,
3217 unsigned Depth) {
3218 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
3219 "only nuw or nsw allowed");
3220 assert(!Ops.empty() && "Cannot get empty mul!");
3221 if (Ops.size() == 1) return Ops[0];
3222#ifndef NDEBUG
3223 Type *ETy = Ops[0]->getType();
3224 assert(!ETy->isPointerTy());
3225 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3226 assert(Ops[i]->getType() == ETy &&
3227 "SCEVMulExpr operand types don't match!");
3228#endif
3229
3230 const SCEV *Folded = constantFoldAndGroupOps(
3231 *this, LI, DT, Ops,
3232 [](const APInt &C1, const APInt &C2) { return C1 * C2; },
3233 [](const APInt &C) { return C.isOne(); }, // identity
3234 [](const APInt &C) { return C.isZero(); }); // absorber
3235 if (Folded)
3236 return Folded;
3237
3238 // Delay expensive flag strengthening until necessary.
3239 auto ComputeFlags = [this, OrigFlags](const ArrayRef<SCEVUse> Ops) {
3240 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
3241 };
3242
3243 // Limit recursion calls depth.
3245 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3246
3247 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
3248 // Don't strengthen flags if we have no new information.
3249 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
3250 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
3251 Mul->setNoWrapFlags(ComputeFlags(Ops));
3252 return S;
3253 }
3254
3255 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3256 if (Ops.size() == 2) {
3257 // C1*(C2+V) -> C1*C2 + C1*V
3258 // If any of Add's ops are Adds or Muls with a constant, apply this
3259 // transformation as well.
3260 //
3261 // TODO: There are some cases where this transformation is not
3262 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
3263 // this transformation should be narrowed down.
3264 const SCEV *Op0, *Op1;
3265 if (match(Ops[1], m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))) &&
3267 const SCEV *LHS = getMulExpr(LHSC, Op0, SCEV::FlagAnyWrap, Depth + 1);
3268 const SCEV *RHS = getMulExpr(LHSC, Op1, SCEV::FlagAnyWrap, Depth + 1);
3269 return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
3270 }
3271
3272 if (Ops[0]->isAllOnesValue()) {
3273 // If we have a mul by -1 of an add, try distributing the -1 among the
3274 // add operands.
3275 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
3277 bool AnyFolded = false;
3278 for (const SCEV *AddOp : Add->operands()) {
3279 const SCEV *Mul = getMulExpr(Ops[0], SCEVUse(AddOp),
3281 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
3282 NewOps.push_back(Mul);
3283 }
3284 if (AnyFolded)
3285 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
3286 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
3287 // Negation preserves a recurrence's no self-wrap property.
3288 SmallVector<SCEVUse, 4> Operands;
3289 for (const SCEV *AddRecOp : AddRec->operands())
3290 Operands.push_back(getMulExpr(Ops[0], SCEVUse(AddRecOp),
3291 SCEV::FlagAnyWrap, Depth + 1));
3292 // Let M be the minimum representable signed value. AddRec with nsw
3293 // multiplied by -1 can have signed overflow if and only if it takes a
3294 // value of M: M * (-1) would stay M and (M + 1) * (-1) would be the
3295 // maximum signed value. In all other cases signed overflow is
3296 // impossible.
3297 auto FlagsMask = SCEV::FlagNW;
3298 if (AddRec->hasNoSignedWrap()) {
3299 auto MinInt =
3300 APInt::getSignedMinValue(getTypeSizeInBits(AddRec->getType()));
3301 if (getSignedRangeMin(AddRec) != MinInt)
3302 FlagsMask = setFlags(FlagsMask, SCEV::FlagNSW);
3303 }
3304 return getAddRecExpr(Operands, AddRec->getLoop(),
3305 AddRec->getNoWrapFlags(FlagsMask));
3306 }
3307 }
3308
3309 // Try to push the constant operand into a ZExt: C * zext (A + B) ->
3310 // zext (C*A + C*B) if trunc (C) * (A + B) does not unsigned-wrap.
3311 const SCEVAddExpr *InnerAdd;
3312 if (match(Ops[1], m_scev_ZExt(m_scev_Add(InnerAdd)))) {
3313 const SCEV *NarrowC = getTruncateExpr(LHSC, InnerAdd->getType());
3314 if (isa<SCEVConstant>(InnerAdd->getOperand(0)) &&
3315 getZeroExtendExpr(NarrowC, Ops[1]->getType()) == LHSC &&
3316 hasFlags(StrengthenNoWrapFlags(this, scMulExpr, {NarrowC, InnerAdd},
3318 SCEV::FlagNUW)) {
3319 auto *Res = getMulExpr(NarrowC, InnerAdd, SCEV::FlagNUW, Depth + 1);
3320 return getZeroExtendExpr(Res, Ops[1]->getType(), Depth + 1);
3321 };
3322 }
3323
3324 // Try to fold (C1 * D /u C2) -> C1/C2 * D, if C1 and C2 are powers-of-2,
3325 // D is a multiple of C2, and C1 is a multiple of C2. If C2 is a multiple
3326 // of C1, fold to (D /u (C2 /u C1)).
3327 const SCEV *D;
3328 APInt C1V = LHSC->getAPInt();
3329 // (C1 * D /u C2) == -1 * -C1 * D /u C2 when C1 != INT_MIN. Don't treat -1
3330 // as -1 * 1, as it won't enable additional folds.
3331 if (C1V.isNegative() && !C1V.isMinSignedValue() && !C1V.isAllOnes())
3332 C1V = C1V.abs();
3333 const SCEVConstant *C2;
3334 if (C1V.isPowerOf2() &&
3336 C2->getAPInt().isPowerOf2() &&
3337 C1V.logBase2() <= getMinTrailingZeros(D)) {
3338 const SCEV *NewMul = nullptr;
3339 if (C1V.uge(C2->getAPInt())) {
3340 NewMul = getMulExpr(getUDivExpr(getConstant(C1V), C2), D);
3341 } else if (C2->getAPInt().logBase2() <= getMinTrailingZeros(D)) {
3342 assert(C1V.ugt(1) && "C1 <= 1 should have been folded earlier");
3343 NewMul = getUDivExpr(D, getUDivExpr(C2, getConstant(C1V)));
3344 }
3345 if (NewMul)
3346 return C1V == LHSC->getAPInt() ? NewMul : getNegativeSCEV(NewMul);
3347 }
3348 }
3349 }
3350
3351 // Skip over the add expression until we get to a multiply.
3352 unsigned Idx = 0;
3353 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3354 ++Idx;
3355
3356 // If there are mul operands inline them all into this expression.
3357 if (Idx < Ops.size()) {
3358 bool DeletedMul = false;
3359 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3360 if (Ops.size() > MulOpsInlineThreshold)
3361 break;
3362 // If we have an mul, expand the mul operands onto the end of the
3363 // operands list.
3364 Ops.erase(Ops.begin()+Idx);
3365 append_range(Ops, Mul->operands());
3366 DeletedMul = true;
3367 }
3368
3369 // If we deleted at least one mul, we added operands to the end of the
3370 // list, and they are not necessarily sorted. Recurse to resort and
3371 // resimplify any operands we just acquired.
3372 if (DeletedMul)
3373 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3374 }
3375
3376 // If there are any add recurrences in the operands list, see if any other
3377 // added values are loop invariant. If so, we can fold them into the
3378 // recurrence.
3379 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3380 ++Idx;
3381
3382 // Scan over all recurrences, trying to fold loop invariants into them.
3383 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3384 // Scan all of the other operands to this mul and add them to the vector
3385 // if they are loop invariant w.r.t. the recurrence.
3387 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3388 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3389 if (isAvailableAtLoopEntry(Ops[i], AddRec->getLoop())) {
3390 LIOps.push_back(Ops[i]);
3391 Ops.erase(Ops.begin()+i);
3392 --i; --e;
3393 }
3394
3395 // If we found some loop invariants, fold them into the recurrence.
3396 if (!LIOps.empty()) {
3397 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3399 NewOps.reserve(AddRec->getNumOperands());
3400 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3401
3402 // If both the mul and addrec are nuw, we can preserve nuw.
3403 // If both the mul and addrec are nsw, we can only preserve nsw if either
3404 // a) they are also nuw, or
3405 // b) all multiplications of addrec operands with scale are nsw.
3406 SCEV::NoWrapFlags Flags =
3407 AddRec->getNoWrapFlags(ComputeFlags({Scale, AddRec}));
3408
3409 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3410 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3411 SCEV::FlagAnyWrap, Depth + 1));
3412
3413 if (hasFlags(Flags, SCEV::FlagNSW) && !hasFlags(Flags, SCEV::FlagNUW)) {
3415 Instruction::Mul, getSignedRange(Scale),
3417 if (!NSWRegion.contains(getSignedRange(AddRec->getOperand(i))))
3418 Flags = clearFlags(Flags, SCEV::FlagNSW);
3419 }
3420 }
3421
3422 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(), Flags);
3423
3424 // If all of the other operands were loop invariant, we are done.
3425 if (Ops.size() == 1) return NewRec;
3426
3427 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3428 for (unsigned i = 0;; ++i)
3429 if (Ops[i] == AddRec) {
3430 Ops[i] = NewRec;
3431 break;
3432 }
3433 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3434 }
3435
3436 // Okay, if there weren't any loop invariants to be folded, check to see
3437 // if there are multiple AddRec's with the same loop induction variable
3438 // being multiplied together. If so, we can fold them.
3439
3440 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3441 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3442 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3443 // ]]],+,...up to x=2n}.
3444 // Note that the arguments to choose() are always integers with values
3445 // known at compile time, never SCEV objects.
3446 //
3447 // The implementation avoids pointless extra computations when the two
3448 // addrec's are of different length (mathematically, it's equivalent to
3449 // an infinite stream of zeros on the right).
3450 bool OpsModified = false;
3451 for (unsigned OtherIdx = Idx+1;
3452 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3453 ++OtherIdx) {
3454 const SCEVAddRecExpr *OtherAddRec =
3455 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3456 if (!OtherAddRec || OtherAddRec->getLoop() != AddRec->getLoop())
3457 continue;
3458
3459 // Limit max number of arguments to avoid creation of unreasonably big
3460 // SCEVAddRecs with very complex operands.
3461 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3462 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
3463 continue;
3464
3465 bool Overflow = false;
3466 Type *Ty = AddRec->getType();
3467 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3468 SmallVector<SCEVUse, 7> AddRecOps;
3469 for (int x = 0, xe = AddRec->getNumOperands() +
3470 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3472 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3473 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3474 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3475 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3476 z < ze && !Overflow; ++z) {
3477 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3478 uint64_t Coeff;
3479 if (LargerThan64Bits)
3480 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3481 else
3482 Coeff = Coeff1*Coeff2;
3483 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3484 const SCEV *Term1 = AddRec->getOperand(y-z);
3485 const SCEV *Term2 = OtherAddRec->getOperand(z);
3486 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3487 SCEV::FlagAnyWrap, Depth + 1));
3488 }
3489 }
3490 if (SumOps.empty())
3491 SumOps.push_back(getZero(Ty));
3492 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3493 }
3494 if (!Overflow) {
3495 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
3497 if (Ops.size() == 2) return NewAddRec;
3498 Ops[Idx] = NewAddRec;
3499 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3500 OpsModified = true;
3501 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3502 if (!AddRec)
3503 break;
3504 }
3505 }
3506 if (OpsModified)
3507 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3508
3509 // Otherwise couldn't fold anything into this recurrence. Move onto the
3510 // next one.
3511 }
3512
3513 // Okay, it looks like we really DO need an mul expr. Check to see if we
3514 // already have one, otherwise create a new one.
3515 return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
3516}
3517
3518/// Represents an unsigned remainder expression based on unsigned division.
3520 assert(getEffectiveSCEVType(LHS->getType()) ==
3521 getEffectiveSCEVType(RHS->getType()) &&
3522 "SCEVURemExpr operand types don't match!");
3523
3524 // Short-circuit easy cases
3525 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3526 // If constant is one, the result is trivial
3527 if (RHSC->getValue()->isOne())
3528 return getZero(LHS->getType()); // X urem 1 --> 0
3529
3530 // If constant is a power of two, fold into a zext(trunc(LHS)).
3531 if (RHSC->getAPInt().isPowerOf2()) {
3532 Type *FullTy = LHS->getType();
3533 Type *TruncTy =
3534 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3535 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3536 }
3537 }
3538
3539 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3540 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3541 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3542 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3543}
3544
3545/// Get a canonical unsigned division expression, or something simpler if
3546/// possible.
3548 assert(!LHS->getType()->isPointerTy() &&
3549 "SCEVUDivExpr operand can't be pointer!");
3550 assert(LHS->getType() == RHS->getType() &&
3551 "SCEVUDivExpr operand types don't match!");
3552
3554 ID.AddInteger(scUDivExpr);
3555 ID.AddPointer(LHS);
3556 ID.AddPointer(RHS);
3557 void *IP = nullptr;
3558 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3559 return S;
3560
3561 // 0 udiv Y == 0
3562 if (match(LHS, m_scev_Zero()))
3563 return LHS;
3564
3565 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3566 if (RHSC->getValue()->isOne())
3567 return LHS; // X udiv 1 --> x
3568 // If the denominator is zero, the result of the udiv is undefined. Don't
3569 // try to analyze it, because the resolution chosen here may differ from
3570 // the resolution chosen in other parts of the compiler.
3571 if (!RHSC->getValue()->isZero()) {
3572 // Determine if the division can be folded into the operands of
3573 // its operands.
3574 // TODO: Generalize this to non-constants by using known-bits information.
3575 Type *Ty = LHS->getType();
3576 unsigned LZ = RHSC->getAPInt().countl_zero();
3577 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3578 // For non-power-of-two values, effectively round the value up to the
3579 // nearest power of two.
3580 if (!RHSC->getAPInt().isPowerOf2())
3581 ++MaxShiftAmt;
3582 IntegerType *ExtTy =
3583 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3584 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3585 if (const SCEVConstant *Step =
3586 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3587 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3588 const APInt &StepInt = Step->getAPInt();
3589 const APInt &DivInt = RHSC->getAPInt();
3590 if (!StepInt.urem(DivInt) &&
3591 getZeroExtendExpr(AR, ExtTy) ==
3592 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3593 getZeroExtendExpr(Step, ExtTy),
3594 AR->getLoop(), SCEV::FlagAnyWrap)) {
3595 SmallVector<SCEVUse, 4> Operands;
3596 for (const SCEV *Op : AR->operands())
3597 Operands.push_back(getUDivExpr(Op, RHS));
3598 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3599 }
3600 /// Get a canonical UDivExpr for a recurrence.
3601 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3602 const APInt *StartRem;
3603 if (!DivInt.urem(StepInt) && match(getURemExpr(AR->getStart(), Step),
3604 m_scev_APInt(StartRem))) {
3605 bool NoWrap =
3606 getZeroExtendExpr(AR, ExtTy) ==
3607 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3608 getZeroExtendExpr(Step, ExtTy), AR->getLoop(),
3610
3611 // With N <= C and both N, C as powers-of-2, the transformation
3612 // {X,+,N}/C => {(X - X%N),+,N}/C preserves division results even
3613 // if wrapping occurs, as the division results remain equivalent for
3614 // all offsets in [[(X - X%N), X).
3615 bool CanFoldWithWrap = StepInt.ule(DivInt) && // N <= C
3616 StepInt.isPowerOf2() && DivInt.isPowerOf2();
3617 // Only fold if the subtraction can be folded in the start
3618 // expression.
3619 const SCEV *NewStart =
3620 getMinusSCEV(AR->getStart(), getConstant(*StartRem));
3621 if (*StartRem != 0 && (NoWrap || CanFoldWithWrap) &&
3622 !isa<SCEVAddExpr>(NewStart)) {
3623 const SCEV *NewLHS =
3624 getAddRecExpr(NewStart, Step, AR->getLoop(),
3625 NoWrap ? SCEV::FlagNW : SCEV::FlagAnyWrap);
3626 if (LHS != NewLHS) {
3627 LHS = NewLHS;
3628
3629 // Reset the ID to include the new LHS, and check if it is
3630 // already cached.
3631 ID.clear();
3632 ID.AddInteger(scUDivExpr);
3633 ID.AddPointer(LHS);
3634 ID.AddPointer(RHS);
3635 IP = nullptr;
3636 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
3637 return S;
3638 }
3639 }
3640 }
3641 }
3642 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3643 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3644 SmallVector<SCEVUse, 4> Operands;
3645 for (const SCEV *Op : M->operands())
3646 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3647 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) {
3648 // Find an operand that's safely divisible.
3649 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3650 const SCEV *Op = M->getOperand(i);
3651 const SCEV *Div = getUDivExpr(Op, RHSC);
3652 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3653 Operands = SmallVector<SCEVUse, 4>(M->operands());
3654 Operands[i] = Div;
3655 return getMulExpr(Operands);
3656 }
3657 }
3658
3659 // Even if it's not divisible, try to remove a common factor.
3660 if (const auto *LHSC = dyn_cast<SCEVConstant>(M->getOperand(0))) {
3661 APInt Factor = APIntOps::GreatestCommonDivisor(LHSC->getAPInt(),
3662 RHSC->getAPInt());
3663 if (!Factor.isIntN(1)) {
3664 SmallVector<SCEVUse, 2> NewOperands;
3665 NewOperands.push_back(getConstant(LHSC->getAPInt().udiv(Factor)));
3666 append_range(NewOperands, M->operands().drop_front());
3667 const SCEV *NewMul = getMulExpr(NewOperands);
3668 return getUDivExpr(NewMul,
3669 getConstant(RHSC->getAPInt().udiv(Factor)));
3670 }
3671 }
3672 }
3673 }
3674
3675 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3676 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3677 if (auto *DivisorConstant =
3678 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3679 bool Overflow = false;
3680 APInt NewRHS =
3681 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3682 if (Overflow) {
3683 return getConstant(RHSC->getType(), 0, false);
3684 }
3685 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3686 }
3687 }
3688
3689 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3690 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3691 SmallVector<SCEVUse, 4> Operands;
3692 for (const SCEV *Op : A->operands())
3693 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3694 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3695 Operands.clear();
3696 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3697 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3698 if (isa<SCEVUDivExpr>(Op) ||
3699 getMulExpr(Op, RHS) != A->getOperand(i))
3700 break;
3701 Operands.push_back(Op);
3702 }
3703 if (Operands.size() == A->getNumOperands())
3704 return getAddExpr(Operands);
3705 }
3706 }
3707
3708 // ((N - M) + (M * A)) / N --> ((N - 1) + (M * A)) / N
3709 // This is an idiom for rounding A up to the next multiple of N, where A
3710 // is aready known to be a multiple of M. In this case, instcombine can
3711 // see that some low bits of the added constant are unused, so can clear
3712 // them, but we want to canonicalise to set the low bits. This makes the
3713 // pattern easier to match, without needing to check for known bits in
3714 // A*M.
3715 const APInt &N = RHSC->getAPInt();
3716 const APInt *NMinusM, *M;
3717 const SCEV *A;
3718 if (match(LHS, m_scev_Add(m_scev_APInt(NMinusM),
3719 m_scev_Mul(m_scev_APInt(M), m_SCEV(A))))) {
3720 if (N.isPowerOf2() && M->isPowerOf2() && M->ult(N) &&
3721 *NMinusM == N - *M) {
3722 return getUDivExpr(
3724 RHS);
3725 }
3726 }
3727
3728 // Fold if both operands are constant.
3729 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
3730 return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
3731 }
3732 }
3733
3734 // ((-C + (C smax %x)) /u %x) evaluates to zero, for any positive constant C.
3735 const APInt *NegC, *C;
3736 if (match(LHS,
3739 NegC->isNegative() && !NegC->isMinSignedValue() && *C == -*NegC)
3740 return getZero(LHS->getType());
3741
3742 // (%a * %b)<nuw> / %b -> %a
3743 const auto *Mul = dyn_cast<SCEVMulExpr>(LHS);
3744 if (Mul && Mul->hasNoUnsignedWrap()) {
3745 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3746 if (Mul->getOperand(i) == RHS) {
3747 SmallVector<SCEVUse, 2> Operands;
3748 append_range(Operands, Mul->operands().take_front(i));
3749 append_range(Operands, Mul->operands().drop_front(i + 1));
3750 return getMulExpr(Operands);
3751 }
3752 }
3753 }
3754
3755 // TODO: Generalize to handle any common factors.
3756 // udiv (mul nuw a, vscale), (mul nuw b, vscale) --> udiv a, b
3757 const SCEV *NewLHS, *NewRHS;
3758 if (match(LHS, m_scev_c_NUWMul(m_SCEV(NewLHS), m_SCEVVScale())) &&
3759 match(RHS, m_scev_c_NUWMul(m_SCEV(NewRHS), m_SCEVVScale())))
3760 return getUDivExpr(NewLHS, NewRHS);
3761
3762 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
3763 // changes). Make sure we get a new one.
3764 IP = nullptr;
3765 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3766 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3767 LHS, RHS);
3768 UniqueSCEVs.InsertNode(S, IP);
3769 S->computeAndSetCanonical(*this);
3770 registerUser(S, ArrayRef<SCEVUse>({LHS, RHS}));
3771 return S;
3772}
3773
3774APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3775 APInt A = C1->getAPInt().abs();
3776 APInt B = C2->getAPInt().abs();
3777 uint32_t ABW = A.getBitWidth();
3778 uint32_t BBW = B.getBitWidth();
3779
3780 if (ABW > BBW)
3781 B = B.zext(ABW);
3782 else if (ABW < BBW)
3783 A = A.zext(BBW);
3784
3785 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3786}
3787
3788/// Get a canonical unsigned division expression, or something simpler if
3789/// possible. There is no representation for an exact udiv in SCEV IR, but we
3790/// can attempt to optimize it prior to construction.
3792 // Currently there is no exact specific logic.
3793
3794 return getUDivExpr(LHS, RHS);
3795}
3796
3797/// Get an add recurrence expression for the specified loop. Simplify the
3798/// expression as much as possible.
3800 const Loop *L,
3801 SCEV::NoWrapFlags Flags) {
3802 SmallVector<SCEVUse, 4> Operands;
3803 Operands.push_back(Start);
3804 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3805 if (StepChrec->getLoop() == L) {
3806 append_range(Operands, StepChrec->operands());
3807 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3808 }
3809
3810 Operands.push_back(Step);
3811 return getAddRecExpr(Operands, L, Flags);
3812}
3813
3814/// Get an add recurrence expression for the specified loop. Simplify the
3815/// expression as much as possible.
3817 const Loop *L,
3818 SCEV::NoWrapFlags Flags) {
3819 if (Operands.size() == 1) return Operands[0];
3820#ifndef NDEBUG
3821 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3822 for (const SCEV *Op : llvm::drop_begin(Operands)) {
3823 assert(getEffectiveSCEVType(Op->getType()) == ETy &&
3824 "SCEVAddRecExpr operand types don't match!");
3825 assert(!Op->getType()->isPointerTy() && "Step must be integer");
3826 }
3827 for (const SCEV *Op : Operands)
3829 "SCEVAddRecExpr operand is not available at loop entry!");
3830#endif
3831
3832 if (Operands.back()->isZero()) {
3833 Operands.pop_back();
3834 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3835 }
3836
3837 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3838 // use that information to infer NUW and NSW flags. However, computing a
3839 // BE count requires calling getAddRecExpr, so we may not yet have a
3840 // meaningful BE count at this point (and if we don't, we'd be stuck
3841 // with a SCEVCouldNotCompute as the cached BE count).
3842
3843 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3844
3845 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3846 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3847 const Loop *NestedLoop = NestedAR->getLoop();
3848 if (L->contains(NestedLoop)
3849 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3850 : (!NestedLoop->contains(L) &&
3851 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3852 SmallVector<SCEVUse, 4> NestedOperands(NestedAR->operands());
3853 Operands[0] = NestedAR->getStart();
3854 // AddRecs require their operands be loop-invariant with respect to their
3855 // loops. Don't perform this transformation if it would break this
3856 // requirement.
3857 bool AllInvariant = all_of(
3858 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3859
3860 if (AllInvariant) {
3861 // Create a recurrence for the outer loop with the same step size.
3862 //
3863 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3864 // inner recurrence has the same property.
3865 SCEV::NoWrapFlags OuterFlags =
3866 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3867
3868 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3869 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3870 return isLoopInvariant(Op, NestedLoop);
3871 });
3872
3873 if (AllInvariant) {
3874 // Ok, both add recurrences are valid after the transformation.
3875 //
3876 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3877 // the outer recurrence has the same property.
3878 SCEV::NoWrapFlags InnerFlags =
3879 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3880 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3881 }
3882 }
3883 // Reset Operands to its original state.
3884 Operands[0] = NestedAR;
3885 }
3886 }
3887
3888 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3889 // already have one, otherwise create a new one.
3890 return getOrCreateAddRecExpr(Operands, L, Flags);
3891}
3892
3894 ArrayRef<SCEVUse> IndexExprs) {
3895 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3896 // getSCEV(Base)->getType() has the same address space as Base->getType()
3897 // because SCEV::getType() preserves the address space.
3898 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
3899 if (NW != GEPNoWrapFlags::none()) {
3900 // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
3901 // but to do that, we have to ensure that said flag is valid in the entire
3902 // defined scope of the SCEV.
3903 // TODO: non-instructions have global scope. We might be able to prove
3904 // some global scope cases
3905 auto *GEPI = dyn_cast<Instruction>(GEP);
3906 if (!GEPI || !isSCEVExprNeverPoison(GEPI))
3907 NW = GEPNoWrapFlags::none();
3908 }
3909
3910 return getGEPExpr(BaseExpr, IndexExprs, GEP->getSourceElementType(), NW);
3911}
3912
3914 ArrayRef<SCEVUse> IndexExprs,
3915 Type *SrcElementTy, GEPNoWrapFlags NW) {
3917 if (NW.hasNoUnsignedSignedWrap())
3918 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNSW);
3919 if (NW.hasNoUnsignedWrap())
3920 OffsetWrap = setFlags(OffsetWrap, SCEV::FlagNUW);
3921
3922 Type *CurTy = BaseExpr->getType();
3923 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
3924 bool FirstIter = true;
3926 for (SCEVUse IndexExpr : IndexExprs) {
3927 // Compute the (potentially symbolic) offset in bytes for this index.
3928 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3929 // For a struct, add the member offset.
3930 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3931 unsigned FieldNo = Index->getZExtValue();
3932 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
3933 Offsets.push_back(FieldOffset);
3934
3935 // Update CurTy to the type of the field at Index.
3936 CurTy = STy->getTypeAtIndex(Index);
3937 } else {
3938 // Update CurTy to its element type.
3939 if (FirstIter) {
3940 assert(isa<PointerType>(CurTy) &&
3941 "The first index of a GEP indexes a pointer");
3942 CurTy = SrcElementTy;
3943 FirstIter = false;
3944 } else {
3946 }
3947 // For an array, add the element offset, explicitly scaled.
3948 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
3949 // Getelementptr indices are signed.
3950 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
3951
3952 // Multiply the index by the element size to compute the element offset.
3953 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
3954 Offsets.push_back(LocalOffset);
3955 }
3956 }
3957
3958 // Handle degenerate case of GEP without offsets.
3959 if (Offsets.empty())
3960 return BaseExpr;
3961
3962 // Add the offsets together, assuming nsw if inbounds.
3963 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
3964 // Add the base address and the offset. We cannot use the nsw flag, as the
3965 // base address is unsigned. However, if we know that the offset is
3966 // non-negative, we can use nuw.
3967 bool NUW = NW.hasNoUnsignedWrap() ||
3970 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
3971 assert(BaseExpr->getType() == GEPExpr->getType() &&
3972 "GEP should not change type mid-flight.");
3973 return GEPExpr;
3974}
3975
3976SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3979 ID.AddInteger(SCEVType);
3980 for (const SCEV *Op : Ops)
3981 ID.AddPointer(Op);
3982 void *IP = nullptr;
3983 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3984}
3985
3986SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
3989 ID.AddInteger(SCEVType);
3990 for (const SCEV *Op : Ops)
3991 ID.AddPointer(Op);
3992 void *IP = nullptr;
3993 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
3994}
3995
3996const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
3998 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
3999}
4000
4003 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
4004 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4005 if (Ops.size() == 1) return Ops[0];
4006#ifndef NDEBUG
4007 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4008 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4009 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4010 "Operand types don't match!");
4011 assert(Ops[0]->getType()->isPointerTy() ==
4012 Ops[i]->getType()->isPointerTy() &&
4013 "min/max should be consistently pointerish");
4014 }
4015#endif
4016
4017 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
4018 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
4019
4020 const SCEV *Folded = constantFoldAndGroupOps(
4021 *this, LI, DT, Ops,
4022 [&](const APInt &C1, const APInt &C2) {
4023 switch (Kind) {
4024 case scSMaxExpr:
4025 return APIntOps::smax(C1, C2);
4026 case scSMinExpr:
4027 return APIntOps::smin(C1, C2);
4028 case scUMaxExpr:
4029 return APIntOps::umax(C1, C2);
4030 case scUMinExpr:
4031 return APIntOps::umin(C1, C2);
4032 default:
4033 llvm_unreachable("Unknown SCEV min/max opcode");
4034 }
4035 },
4036 [&](const APInt &C) {
4037 // identity
4038 if (IsMax)
4039 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4040 else
4041 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4042 },
4043 [&](const APInt &C) {
4044 // absorber
4045 if (IsMax)
4046 return IsSigned ? C.isMaxSignedValue() : C.isMaxValue();
4047 else
4048 return IsSigned ? C.isMinSignedValue() : C.isMinValue();
4049 });
4050 if (Folded)
4051 return Folded;
4052
4053 // Check if we have created the same expression before.
4054 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
4055 return S;
4056 }
4057
4058 // Find the first operation of the same kind
4059 unsigned Idx = 0;
4060 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
4061 ++Idx;
4062
4063 // Check to see if one of the operands is of the same kind. If so, expand its
4064 // operands onto our operand list, and recurse to simplify.
4065 if (Idx < Ops.size()) {
4066 bool DeletedAny = false;
4067 while (Ops[Idx]->getSCEVType() == Kind) {
4068 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
4069 Ops.erase(Ops.begin()+Idx);
4070 append_range(Ops, SMME->operands());
4071 DeletedAny = true;
4072 }
4073
4074 if (DeletedAny)
4075 return getMinMaxExpr(Kind, Ops);
4076 }
4077
4078 // Okay, check to see if the same value occurs in the operand list twice. If
4079 // so, delete one. Since we sorted the list, these values are required to
4080 // be adjacent.
4085 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
4086 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
4087 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
4088 if (Ops[i] == Ops[i + 1] ||
4089 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
4090 // X op Y op Y --> X op Y
4091 // X op Y --> X, if we know X, Y are ordered appropriately
4092 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
4093 --i;
4094 --e;
4095 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
4096 Ops[i + 1])) {
4097 // X op Y --> Y, if we know X, Y are ordered appropriately
4098 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
4099 --i;
4100 --e;
4101 }
4102 }
4103
4104 if (Ops.size() == 1) return Ops[0];
4105
4106 assert(!Ops.empty() && "Reduced smax down to nothing!");
4107
4108 // Okay, it looks like we really DO need an expr. Check to see if we
4109 // already have one, otherwise create a new one.
4111 ID.AddInteger(Kind);
4112 for (const SCEV *Op : Ops)
4113 ID.AddPointer(Op);
4114 void *IP = nullptr;
4115 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4116 if (ExistingSCEV)
4117 return ExistingSCEV;
4118 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4120 SCEV *S = new (SCEVAllocator)
4121 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4122
4123 UniqueSCEVs.InsertNode(S, IP);
4124 S->computeAndSetCanonical(*this);
4125 registerUser(S, Ops);
4126 return S;
4127}
4128
4129namespace {
4130
4131class SCEVSequentialMinMaxDeduplicatingVisitor final
4132 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
4133 std::optional<const SCEV *>> {
4134 using RetVal = std::optional<const SCEV *>;
4136
4137 ScalarEvolution &SE;
4138 const SCEVTypes RootKind; // Must be a sequential min/max expression.
4139 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
4141
4142 bool canRecurseInto(SCEVTypes Kind) const {
4143 // We can only recurse into the SCEV expression of the same effective type
4144 // as the type of our root SCEV expression.
4145 return RootKind == Kind || NonSequentialRootKind == Kind;
4146 };
4147
4148 RetVal visitAnyMinMaxExpr(const SCEV *S) {
4150 "Only for min/max expressions.");
4151 SCEVTypes Kind = S->getSCEVType();
4152
4153 if (!canRecurseInto(Kind))
4154 return S;
4155
4156 auto *NAry = cast<SCEVNAryExpr>(S);
4157 SmallVector<SCEVUse> NewOps;
4158 bool Changed = visit(Kind, NAry->operands(), NewOps);
4159
4160 if (!Changed)
4161 return S;
4162 if (NewOps.empty())
4163 return std::nullopt;
4164
4166 ? SE.getSequentialMinMaxExpr(Kind, NewOps)
4167 : SE.getMinMaxExpr(Kind, NewOps);
4168 }
4169
4170 RetVal visit(const SCEV *S) {
4171 // Has the whole operand been seen already?
4172 if (!SeenOps.insert(S).second)
4173 return std::nullopt;
4174 return Base::visit(S);
4175 }
4176
4177public:
4178 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
4179 SCEVTypes RootKind)
4180 : SE(SE), RootKind(RootKind),
4181 NonSequentialRootKind(
4182 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
4183 RootKind)) {}
4184
4185 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<SCEVUse> OrigOps,
4186 SmallVectorImpl<SCEVUse> &NewOps) {
4187 bool Changed = false;
4189 Ops.reserve(OrigOps.size());
4190
4191 for (const SCEV *Op : OrigOps) {
4192 RetVal NewOp = visit(Op);
4193 if (NewOp != Op)
4194 Changed = true;
4195 if (NewOp)
4196 Ops.emplace_back(*NewOp);
4197 }
4198
4199 if (Changed)
4200 NewOps = std::move(Ops);
4201 return Changed;
4202 }
4203
4204 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
4205
4206 RetVal visitVScale(const SCEVVScale *VScale) { return VScale; }
4207
4208 RetVal visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) { return Expr; }
4209
4210 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
4211
4212 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
4213
4214 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
4215
4216 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
4217
4218 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
4219
4220 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
4221
4222 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
4223
4224 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
4225
4226 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
4227 return visitAnyMinMaxExpr(Expr);
4228 }
4229
4230 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
4231 return visitAnyMinMaxExpr(Expr);
4232 }
4233
4234 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
4235 return visitAnyMinMaxExpr(Expr);
4236 }
4237
4238 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
4239 return visitAnyMinMaxExpr(Expr);
4240 }
4241
4242 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
4243 return visitAnyMinMaxExpr(Expr);
4244 }
4245
4246 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
4247
4248 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
4249};
4250
4251} // namespace
4252
4254 switch (Kind) {
4255 case scConstant:
4256 case scVScale:
4257 case scTruncate:
4258 case scZeroExtend:
4259 case scSignExtend:
4260 case scPtrToAddr:
4261 case scPtrToInt:
4262 case scAddExpr:
4263 case scMulExpr:
4264 case scUDivExpr:
4265 case scAddRecExpr:
4266 case scUMaxExpr:
4267 case scSMaxExpr:
4268 case scUMinExpr:
4269 case scSMinExpr:
4270 case scUnknown:
4271 // If any operand is poison, the whole expression is poison.
4272 return true;
4274 // FIXME: if the *first* operand is poison, the whole expression is poison.
4275 return false; // Pessimistically, say that it does not propagate poison.
4276 case scCouldNotCompute:
4277 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
4278 }
4279 llvm_unreachable("Unknown SCEV kind!");
4280}
4281
4282namespace {
4283// The only way poison may be introduced in a SCEV expression is from a
4284// poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
4285// not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
4286// introduce poison -- they encode guaranteed, non-speculated knowledge.
4287//
4288// Additionally, all SCEV nodes propagate poison from inputs to outputs,
4289// with the notable exception of umin_seq, where only poison from the first
4290// operand is (unconditionally) propagated.
4291struct SCEVPoisonCollector {
4292 bool LookThroughMaybePoisonBlocking;
4293 SmallPtrSet<const SCEVUnknown *, 4> MaybePoison;
4294 SCEVPoisonCollector(bool LookThroughMaybePoisonBlocking)
4295 : LookThroughMaybePoisonBlocking(LookThroughMaybePoisonBlocking) {}
4296
4297 bool follow(const SCEV *S) {
4298 if (!LookThroughMaybePoisonBlocking &&
4300 return false;
4301
4302 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
4303 if (!isGuaranteedNotToBePoison(SU->getValue()))
4304 MaybePoison.insert(SU);
4305 }
4306 return true;
4307 }
4308 bool isDone() const { return false; }
4309};
4310} // namespace
4311
4312/// Return true if V is poison given that AssumedPoison is already poison.
4313static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
4314 // First collect all SCEVs that might result in AssumedPoison to be poison.
4315 // We need to look through potentially poison-blocking operations here,
4316 // because we want to find all SCEVs that *might* result in poison, not only
4317 // those that are *required* to.
4318 SCEVPoisonCollector PC1(/* LookThroughMaybePoisonBlocking */ true);
4319 visitAll(AssumedPoison, PC1);
4320
4321 // AssumedPoison is never poison. As the assumption is false, the implication
4322 // is true. Don't bother walking the other SCEV in this case.
4323 if (PC1.MaybePoison.empty())
4324 return true;
4325
4326 // Collect all SCEVs in S that, if poison, *will* result in S being poison
4327 // as well. We cannot look through potentially poison-blocking operations
4328 // here, as their arguments only *may* make the result poison.
4329 SCEVPoisonCollector PC2(/* LookThroughMaybePoisonBlocking */ false);
4330 visitAll(S, PC2);
4331
4332 // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
4333 // it will also make S poison by being part of PC2.MaybePoison.
4334 return llvm::set_is_subset(PC1.MaybePoison, PC2.MaybePoison);
4335}
4336
4338 SmallPtrSetImpl<const Value *> &Result, const SCEV *S) {
4339 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ false);
4340 visitAll(S, PC);
4341 for (const SCEVUnknown *SU : PC.MaybePoison)
4342 Result.insert(SU->getValue());
4343}
4344
4346 const SCEV *S, Instruction *I,
4347 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
4348 // If the instruction cannot be poison, it's always safe to reuse.
4350 return true;
4351
4352 // Otherwise, it is possible that I is more poisonous that S. Collect the
4353 // poison-contributors of S, and then check whether I has any additional
4354 // poison-contributors. Poison that is contributed through poison-generating
4355 // flags is handled by dropping those flags instead.
4357 getPoisonGeneratingValues(PoisonVals, S);
4358
4359 SmallVector<Value *> Worklist;
4361 Worklist.push_back(I);
4362 while (!Worklist.empty()) {
4363 Value *V = Worklist.pop_back_val();
4364 if (!Visited.insert(V).second)
4365 continue;
4366
4367 // Avoid walking large instruction graphs.
4368 if (Visited.size() > 16)
4369 return false;
4370
4371 // Either the value can't be poison, or the S would also be poison if it
4372 // is.
4373 if (PoisonVals.contains(V) || ::isGuaranteedNotToBePoison(V))
4374 continue;
4375
4376 auto *I = dyn_cast<Instruction>(V);
4377 if (!I)
4378 return false;
4379
4380 // Disjoint or instructions are interpreted as adds by SCEV. However, we
4381 // can't replace an arbitrary add with disjoint or, even if we drop the
4382 // flag. We would need to convert the or into an add.
4383 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
4384 if (PDI->isDisjoint())
4385 return false;
4386
4387 // FIXME: Ignore vscale, even though it technically could be poison. Do this
4388 // because SCEV currently assumes it can't be poison. Remove this special
4389 // case once we proper model when vscale can be poison.
4390 if (auto *II = dyn_cast<IntrinsicInst>(I);
4391 II && II->getIntrinsicID() == Intrinsic::vscale)
4392 continue;
4393
4394 if (canCreatePoison(cast<Operator>(I), /*ConsiderFlagsAndMetadata*/ false))
4395 return false;
4396
4397 // If the instruction can't create poison, we can recurse to its operands.
4398 if (I->hasPoisonGeneratingAnnotations())
4399 DropPoisonGeneratingInsts.push_back(I);
4400
4401 llvm::append_range(Worklist, I->operands());
4402 }
4403 return true;
4404}
4405
4406const SCEV *
4409 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
4410 "Not a SCEVSequentialMinMaxExpr!");
4411 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
4412 if (Ops.size() == 1)
4413 return Ops[0];
4414#ifndef NDEBUG
4415 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
4416 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4417 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
4418 "Operand types don't match!");
4419 assert(Ops[0]->getType()->isPointerTy() ==
4420 Ops[i]->getType()->isPointerTy() &&
4421 "min/max should be consistently pointerish");
4422 }
4423#endif
4424
4425 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
4426 // so we can *NOT* do any kind of sorting of the expressions!
4427
4428 // Check if we have created the same expression before.
4429 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
4430 return S;
4431
4432 // FIXME: there are *some* simplifications that we can do here.
4433
4434 // Keep only the first instance of an operand.
4435 {
4436 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
4437 bool Changed = Deduplicator.visit(Kind, Ops, Ops);
4438 if (Changed)
4439 return getSequentialMinMaxExpr(Kind, Ops);
4440 }
4441
4442 // Check to see if one of the operands is of the same kind. If so, expand its
4443 // operands onto our operand list, and recurse to simplify.
4444 {
4445 unsigned Idx = 0;
4446 bool DeletedAny = false;
4447 while (Idx < Ops.size()) {
4448 if (Ops[Idx]->getSCEVType() != Kind) {
4449 ++Idx;
4450 continue;
4451 }
4452 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
4453 Ops.erase(Ops.begin() + Idx);
4454 Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
4455 SMME->operands().end());
4456 DeletedAny = true;
4457 }
4458
4459 if (DeletedAny)
4460 return getSequentialMinMaxExpr(Kind, Ops);
4461 }
4462
4463 const SCEV *SaturationPoint;
4465 switch (Kind) {
4467 SaturationPoint = getZero(Ops[0]->getType());
4468 Pred = ICmpInst::ICMP_ULE;
4469 break;
4470 default:
4471 llvm_unreachable("Not a sequential min/max type.");
4472 }
4473
4474 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
4475 if (!isGuaranteedNotToCauseUB(Ops[i]))
4476 continue;
4477 // We can replace %x umin_seq %y with %x umin %y if either:
4478 // * %y being poison implies %x is also poison.
4479 // * %x cannot be the saturating value (e.g. zero for umin).
4480 if (::impliesPoison(Ops[i], Ops[i - 1]) ||
4481 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
4482 SaturationPoint)) {
4483 SmallVector<SCEVUse, 2> SeqOps = {Ops[i - 1], Ops[i]};
4484 Ops[i - 1] = getMinMaxExpr(
4486 SeqOps);
4487 Ops.erase(Ops.begin() + i);
4488 return getSequentialMinMaxExpr(Kind, Ops);
4489 }
4490 // Fold %x umin_seq %y to %x if %x ule %y.
4491 // TODO: We might be able to prove the predicate for a later operand.
4492 if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
4493 Ops.erase(Ops.begin() + i);
4494 return getSequentialMinMaxExpr(Kind, Ops);
4495 }
4496 }
4497
4498 // Okay, it looks like we really DO need an expr. Check to see if we
4499 // already have one, otherwise create a new one.
4501 ID.AddInteger(Kind);
4502 for (const SCEV *Op : Ops)
4503 ID.AddPointer(Op);
4504 void *IP = nullptr;
4505 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
4506 if (ExistingSCEV)
4507 return ExistingSCEV;
4508
4509 SCEVUse *O = SCEVAllocator.Allocate<SCEVUse>(Ops.size());
4511 SCEV *S = new (SCEVAllocator)
4512 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
4513
4514 UniqueSCEVs.InsertNode(S, IP);
4515 S->computeAndSetCanonical(*this);
4516 registerUser(S, Ops);
4517 return S;
4518}
4519
4524
4528
4533
4537
4542
4546
4548 bool Sequential) {
4549 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4550 return getUMinExpr(Ops, Sequential);
4551}
4552
4558
4559const SCEV *
4561 const SCEV *Res = getConstant(IntTy, Size.getKnownMinValue());
4562 if (Size.isScalable())
4563 Res = getMulExpr(Res, getVScale(IntTy));
4564 return Res;
4565}
4566
4568 return getSizeOfExpr(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
4569}
4570
4572 return getSizeOfExpr(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
4573}
4574
4576 StructType *STy,
4577 unsigned FieldNo) {
4578 // We can bypass creating a target-independent constant expression and then
4579 // folding it back into a ConstantInt. This is just a compile-time
4580 // optimization.
4581 const StructLayout *SL = getDataLayout().getStructLayout(STy);
4582 assert(!SL->getSizeInBits().isScalable() &&
4583 "Cannot get offset for structure containing scalable vector types");
4584 return getConstant(IntTy, SL->getElementOffset(FieldNo));
4585}
4586
4588 // Don't attempt to do anything other than create a SCEVUnknown object
4589 // here. createSCEV only calls getUnknown after checking for all other
4590 // interesting possibilities, and any other code that calls getUnknown
4591 // is doing so in order to hide a value from SCEV canonicalization.
4592
4594 ID.AddInteger(scUnknown);
4595 ID.AddPointer(V);
4596 void *IP = nullptr;
4597 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
4598 assert(cast<SCEVUnknown>(S)->getValue() == V &&
4599 "Stale SCEVUnknown in uniquing map!");
4600 return S;
4601 }
4602 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
4603 FirstUnknown);
4604 FirstUnknown = cast<SCEVUnknown>(S);
4605 UniqueSCEVs.InsertNode(S, IP);
4606 S->computeAndSetCanonical(*this);
4607 return S;
4608}
4609
4610//===----------------------------------------------------------------------===//
4611// Basic SCEV Analysis and PHI Idiom Recognition Code
4612//
4613
4614/// Test if values of the given type are analyzable within the SCEV
4615/// framework. This primarily includes integer types, and it can optionally
4616/// include pointer types if the ScalarEvolution class has access to
4617/// target-specific information.
4619 // Integers and pointers are always SCEVable.
4620 return Ty->isIntOrPtrTy();
4621}
4622
4623/// Return the size in bits of the specified type, for which isSCEVable must
4624/// return true.
4626 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4627 if (Ty->isPointerTy())
4629 return getDataLayout().getTypeSizeInBits(Ty);
4630}
4631
4632/// Return a type with the same bitwidth as the given type and which represents
4633/// how SCEV will treat the given type, for which isSCEVable must return
4634/// true. For pointer types, this is the pointer index sized integer type.
4636 assert(isSCEVable(Ty) && "Type is not SCEVable!");
4637
4638 if (Ty->isIntegerTy())
4639 return Ty;
4640
4641 // The only other support type is pointer.
4642 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
4643 return getDataLayout().getIndexType(Ty);
4644}
4645
4647 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
4648}
4649
4651 const SCEV *B) {
4652 /// For a valid use point to exist, the defining scope of one operand
4653 /// must dominate the other.
4654 bool PreciseA, PreciseB;
4655 auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
4656 auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
4657 if (!PreciseA || !PreciseB)
4658 // Can't tell.
4659 return false;
4660 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
4661 DT.dominates(ScopeB, ScopeA);
4662}
4663
4665 return CouldNotCompute.get();
4666}
4667
4668bool ScalarEvolution::checkValidity(const SCEV *S) const {
4669 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
4670 auto *SU = dyn_cast<SCEVUnknown>(S);
4671 return SU && SU->getValue() == nullptr;
4672 });
4673
4674 return !ContainsNulls;
4675}
4676
4678 HasRecMapType::iterator I = HasRecMap.find(S);
4679 if (I != HasRecMap.end())
4680 return I->second;
4681
4682 bool FoundAddRec =
4683 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
4684 HasRecMap.insert({S, FoundAddRec});
4685 return FoundAddRec;
4686}
4687
4688/// Return the ValueOffsetPair set for \p S. \p S can be represented
4689/// by the value and offset from any ValueOffsetPair in the set.
4690ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
4691 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
4692 if (SI == ExprValueMap.end())
4693 return {};
4694 return SI->second.getArrayRef();
4695}
4696
4697/// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
4698/// cannot be used separately. eraseValueFromMap should be used to remove
4699/// V from ValueExprMap and ExprValueMap at the same time.
4700void ScalarEvolution::eraseValueFromMap(Value *V) {
4701 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4702 if (I != ValueExprMap.end()) {
4703 auto EVIt = ExprValueMap.find(I->second);
4704 bool Removed = EVIt->second.remove(V);
4705 (void) Removed;
4706 assert(Removed && "Value not in ExprValueMap?");
4707 ValueExprMap.erase(I);
4708 }
4709}
4710
4711void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
4712 // A recursive query may have already computed the SCEV. It should be
4713 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
4714 // inferred nowrap flags.
4715 auto It = ValueExprMap.find_as(V);
4716 if (It == ValueExprMap.end()) {
4717 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
4718 ExprValueMap[S].insert(V);
4719 }
4720}
4721
4722/// Return an existing SCEV if it exists, otherwise analyze the expression and
4723/// create a new one.
4725 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4726
4727 if (const SCEV *S = getExistingSCEV(V))
4728 return S;
4729 return createSCEVIter(V);
4730}
4731
4733 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
4734
4735 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
4736 if (I != ValueExprMap.end()) {
4737 const SCEV *S = I->second;
4738 assert(checkValidity(S) &&
4739 "existing SCEV has not been properly invalidated");
4740 return S;
4741 }
4742 return nullptr;
4743}
4744
4745/// Return a SCEV corresponding to -V = -1*V
4747 SCEV::NoWrapFlags Flags) {
4748 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4749 return getConstant(
4750 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
4751
4752 Type *Ty = V->getType();
4753 Ty = getEffectiveSCEVType(Ty);
4754 return getMulExpr(V, getMinusOne(Ty), Flags);
4755}
4756
4757/// If Expr computes ~A, return A else return nullptr
4758static const SCEV *MatchNotExpr(const SCEV *Expr) {
4759 const SCEV *MulOp;
4760 if (match(Expr, m_scev_Add(m_scev_AllOnes(),
4761 m_scev_Mul(m_scev_AllOnes(), m_SCEV(MulOp)))))
4762 return MulOp;
4763 return nullptr;
4764}
4765
4766/// Return a SCEV corresponding to ~V = -1-V
4768 assert(!V->getType()->isPointerTy() && "Can't negate pointer");
4769
4770 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
4771 return getConstant(
4772 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
4773
4774 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
4775 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
4776 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
4777 SmallVector<SCEVUse, 2> MatchedOperands;
4778 for (const SCEV *Operand : MME->operands()) {
4779 const SCEV *Matched = MatchNotExpr(Operand);
4780 if (!Matched)
4781 return (const SCEV *)nullptr;
4782 MatchedOperands.push_back(Matched);
4783 }
4784 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
4785 MatchedOperands);
4786 };
4787 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
4788 return Replaced;
4789 }
4790
4791 Type *Ty = V->getType();
4792 Ty = getEffectiveSCEVType(Ty);
4793 return getMinusSCEV(getMinusOne(Ty), V);
4794}
4795
4797 assert(P->getType()->isPointerTy());
4798
4799 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
4800 // The base of an AddRec is the first operand.
4801 SmallVector<SCEVUse> Ops{AddRec->operands()};
4802 Ops[0] = removePointerBase(Ops[0]);
4803 // Don't try to transfer nowrap flags for now. We could in some cases
4804 // (for example, if pointer operand of the AddRec is a SCEVUnknown).
4805 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
4806 }
4807 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
4808 // The base of an Add is the pointer operand.
4809 SmallVector<SCEVUse> Ops{Add->operands()};
4810 SCEVUse *PtrOp = nullptr;
4811 for (SCEVUse &AddOp : Ops) {
4812 if (AddOp->getType()->isPointerTy()) {
4813 assert(!PtrOp && "Cannot have multiple pointer ops");
4814 PtrOp = &AddOp;
4815 }
4816 }
4817 *PtrOp = removePointerBase(*PtrOp);
4818 // Don't try to transfer nowrap flags for now. We could in some cases
4819 // (for example, if the pointer operand of the Add is a SCEVUnknown).
4820 return getAddExpr(Ops);
4821 }
4822 // Any other expression must be a pointer base.
4823 return getZero(P->getType());
4824}
4825
4827 SCEV::NoWrapFlags Flags,
4828 unsigned Depth) {
4829 // Fast path: X - X --> 0.
4830 if (LHS == RHS)
4831 return getZero(LHS->getType());
4832
4833 // If we subtract two pointers with different pointer bases, bail.
4834 // Eventually, we're going to add an assertion to getMulExpr that we
4835 // can't multiply by a pointer.
4836 if (RHS->getType()->isPointerTy()) {
4837 if (!LHS->getType()->isPointerTy() ||
4838 getPointerBase(LHS) != getPointerBase(RHS))
4839 return getCouldNotCompute();
4840 LHS = removePointerBase(LHS);
4841 RHS = removePointerBase(RHS);
4842 }
4843
4844 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4845 // makes it so that we cannot make much use of NUW.
4846 auto AddFlags = SCEV::FlagAnyWrap;
4847 const bool RHSIsNotMinSigned =
4849 if (hasFlags(Flags, SCEV::FlagNSW)) {
4850 // Let M be the minimum representable signed value. Then (-1)*RHS
4851 // signed-wraps if and only if RHS is M. That can happen even for
4852 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4853 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4854 // (-1)*RHS, we need to prove that RHS != M.
4855 //
4856 // If LHS is non-negative and we know that LHS - RHS does not
4857 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4858 // either by proving that RHS > M or that LHS >= 0.
4859 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4860 AddFlags = SCEV::FlagNSW;
4861 }
4862 }
4863
4864 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4865 // RHS is NSW and LHS >= 0.
4866 //
4867 // The difficulty here is that the NSW flag may have been proven
4868 // relative to a loop that is to be found in a recurrence in LHS and
4869 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4870 // larger scope than intended.
4871 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4872
4873 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4874}
4875
4877 unsigned Depth) {
4878 Type *SrcTy = V->getType();
4879 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4880 "Cannot truncate or zero extend with non-integer arguments!");
4881 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4882 return V; // No conversion
4883 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4884 return getTruncateExpr(V, Ty, Depth);
4885 return getZeroExtendExpr(V, Ty, Depth);
4886}
4887
4889 unsigned Depth) {
4890 Type *SrcTy = V->getType();
4891 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4892 "Cannot truncate or zero extend with non-integer arguments!");
4893 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4894 return V; // No conversion
4895 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4896 return getTruncateExpr(V, Ty, Depth);
4897 return getSignExtendExpr(V, Ty, Depth);
4898}
4899
4900const SCEV *
4902 Type *SrcTy = V->getType();
4903 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4904 "Cannot noop or zero extend with non-integer arguments!");
4906 "getNoopOrZeroExtend cannot truncate!");
4907 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4908 return V; // No conversion
4909 return getZeroExtendExpr(V, Ty);
4910}
4911
4912const SCEV *
4914 Type *SrcTy = V->getType();
4915 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4916 "Cannot noop or sign extend with non-integer arguments!");
4918 "getNoopOrSignExtend cannot truncate!");
4919 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4920 return V; // No conversion
4921 return getSignExtendExpr(V, Ty);
4922}
4923
4924const SCEV *
4926 Type *SrcTy = V->getType();
4927 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4928 "Cannot noop or any extend with non-integer arguments!");
4930 "getNoopOrAnyExtend cannot truncate!");
4931 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4932 return V; // No conversion
4933 return getAnyExtendExpr(V, Ty);
4934}
4935
4936const SCEV *
4938 Type *SrcTy = V->getType();
4939 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4940 "Cannot truncate or noop with non-integer arguments!");
4942 "getTruncateOrNoop cannot extend!");
4943 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4944 return V; // No conversion
4945 return getTruncateExpr(V, Ty);
4946}
4947
4949 const SCEV *RHS) {
4950 const SCEV *PromotedLHS = LHS;
4951 const SCEV *PromotedRHS = RHS;
4952
4953 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4954 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4955 else
4956 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4957
4958 return getUMaxExpr(PromotedLHS, PromotedRHS);
4959}
4960
4962 const SCEV *RHS,
4963 bool Sequential) {
4964 SmallVector<SCEVUse, 2> Ops = {LHS, RHS};
4965 return getUMinFromMismatchedTypes(Ops, Sequential);
4966}
4967
4968const SCEV *
4970 bool Sequential) {
4971 assert(!Ops.empty() && "At least one operand must be!");
4972 // Trivial case.
4973 if (Ops.size() == 1)
4974 return Ops[0];
4975
4976 // Find the max type first.
4977 Type *MaxType = nullptr;
4978 for (SCEVUse S : Ops)
4979 if (MaxType)
4980 MaxType = getWiderType(MaxType, S->getType());
4981 else
4982 MaxType = S->getType();
4983 assert(MaxType && "Failed to find maximum type!");
4984
4985 // Extend all ops to max type.
4986 SmallVector<SCEVUse, 2> PromotedOps;
4987 for (SCEVUse S : Ops)
4988 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4989
4990 // Generate umin.
4991 return getUMinExpr(PromotedOps, Sequential);
4992}
4993
4995 // A pointer operand may evaluate to a nonpointer expression, such as null.
4996 if (!V->getType()->isPointerTy())
4997 return V;
4998
4999 while (true) {
5000 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
5001 V = AddRec->getStart();
5002 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
5003 const SCEV *PtrOp = nullptr;
5004 for (const SCEV *AddOp : Add->operands()) {
5005 if (AddOp->getType()->isPointerTy()) {
5006 assert(!PtrOp && "Cannot have multiple pointer ops");
5007 PtrOp = AddOp;
5008 }
5009 }
5010 assert(PtrOp && "Must have pointer op");
5011 V = PtrOp;
5012 } else // Not something we can look further into.
5013 return V;
5014 }
5015}
5016
5017/// Push users of the given Instruction onto the given Worklist.
5021 // Push the def-use children onto the Worklist stack.
5022 for (User *U : I->users()) {
5023 auto *UserInsn = cast<Instruction>(U);
5024 if (Visited.insert(UserInsn).second)
5025 Worklist.push_back(UserInsn);
5026 }
5027}
5028
5029namespace {
5030
5031/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
5032/// expression in case its Loop is L. If it is not L then
5033/// if IgnoreOtherLoops is true then use AddRec itself
5034/// otherwise rewrite cannot be done.
5035/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5036class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
5037public:
5038 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
5039 bool IgnoreOtherLoops = true) {
5040 SCEVInitRewriter Rewriter(L, SE);
5041 const SCEV *Result = Rewriter.visit(S);
5042 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
5043 return SE.getCouldNotCompute();
5044 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
5045 ? SE.getCouldNotCompute()
5046 : Result;
5047 }
5048
5049 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5050 if (!SE.isLoopInvariant(Expr, L))
5051 SeenLoopVariantSCEVUnknown = true;
5052 return Expr;
5053 }
5054
5055 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5056 // Only re-write AddRecExprs for this loop.
5057 if (Expr->getLoop() == L)
5058 return Expr->getStart();
5059 SeenOtherLoops = true;
5060 return Expr;
5061 }
5062
5063 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5064
5065 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5066
5067private:
5068 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
5069 : SCEVRewriteVisitor(SE), L(L) {}
5070
5071 const Loop *L;
5072 bool SeenLoopVariantSCEVUnknown = false;
5073 bool SeenOtherLoops = false;
5074};
5075
5076/// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
5077/// increment expression in case its Loop is L. If it is not L then
5078/// use AddRec itself.
5079/// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
5080class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
5081public:
5082 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
5083 SCEVPostIncRewriter Rewriter(L, SE);
5084 const SCEV *Result = Rewriter.visit(S);
5085 return Rewriter.hasSeenLoopVariantSCEVUnknown()
5086 ? SE.getCouldNotCompute()
5087 : Result;
5088 }
5089
5090 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5091 if (!SE.isLoopInvariant(Expr, L))
5092 SeenLoopVariantSCEVUnknown = true;
5093 return Expr;
5094 }
5095
5096 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5097 // Only re-write AddRecExprs for this loop.
5098 if (Expr->getLoop() == L)
5099 return Expr->getPostIncExpr(SE);
5100 SeenOtherLoops = true;
5101 return Expr;
5102 }
5103
5104 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
5105
5106 bool hasSeenOtherLoops() { return SeenOtherLoops; }
5107
5108private:
5109 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
5110 : SCEVRewriteVisitor(SE), L(L) {}
5111
5112 const Loop *L;
5113 bool SeenLoopVariantSCEVUnknown = false;
5114 bool SeenOtherLoops = false;
5115};
5116
5117/// This class evaluates the compare condition by matching it against the
5118/// condition of loop latch. If there is a match we assume a true value
5119/// for the condition while building SCEV nodes.
5120class SCEVBackedgeConditionFolder
5121 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
5122public:
5123 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5124 ScalarEvolution &SE) {
5125 bool IsPosBECond = false;
5126 Value *BECond = nullptr;
5127 if (BasicBlock *Latch = L->getLoopLatch()) {
5128 if (CondBrInst *BI = dyn_cast<CondBrInst>(Latch->getTerminator())) {
5129 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
5130 "Both outgoing branches should not target same header!");
5131 BECond = BI->getCondition();
5132 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
5133 } else {
5134 return S;
5135 }
5136 }
5137 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
5138 return Rewriter.visit(S);
5139 }
5140
5141 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5142 const SCEV *Result = Expr;
5143 bool InvariantF = SE.isLoopInvariant(Expr, L);
5144
5145 if (!InvariantF) {
5147 switch (I->getOpcode()) {
5148 case Instruction::Select: {
5149 SelectInst *SI = cast<SelectInst>(I);
5150 std::optional<const SCEV *> Res =
5151 compareWithBackedgeCondition(SI->getCondition());
5152 if (Res) {
5153 bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
5154 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
5155 }
5156 break;
5157 }
5158 default: {
5159 std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
5160 if (Res)
5161 Result = *Res;
5162 break;
5163 }
5164 }
5165 }
5166 return Result;
5167 }
5168
5169private:
5170 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
5171 bool IsPosBECond, ScalarEvolution &SE)
5172 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
5173 IsPositiveBECond(IsPosBECond) {}
5174
5175 std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
5176
5177 const Loop *L;
5178 /// Loop back condition.
5179 Value *BackedgeCond = nullptr;
5180 /// Set to true if loop back is on positive branch condition.
5181 bool IsPositiveBECond;
5182};
5183
5184std::optional<const SCEV *>
5185SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
5186
5187 // If value matches the backedge condition for loop latch,
5188 // then return a constant evolution node based on loopback
5189 // branch taken.
5190 if (BackedgeCond == IC)
5191 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
5193 return std::nullopt;
5194}
5195
5196class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
5197public:
5198 static const SCEV *rewrite(const SCEV *S, const Loop *L,
5199 ScalarEvolution &SE) {
5200 SCEVShiftRewriter Rewriter(L, SE);
5201 const SCEV *Result = Rewriter.visit(S);
5202 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
5203 }
5204
5205 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
5206 // Only allow AddRecExprs for this loop.
5207 if (!SE.isLoopInvariant(Expr, L))
5208 Valid = false;
5209 return Expr;
5210 }
5211
5212 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
5213 if (Expr->getLoop() == L && Expr->isAffine())
5214 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
5215 Valid = false;
5216 return Expr;
5217 }
5218
5219 bool isValid() { return Valid; }
5220
5221private:
5222 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
5223 : SCEVRewriteVisitor(SE), L(L) {}
5224
5225 const Loop *L;
5226 bool Valid = true;
5227};
5228
5229} // end anonymous namespace
5230
5231void ScalarEvolution::inferNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
5232 if (!AR->isAffine())
5233 return;
5234
5235 // Force computation of ranges, which will also perform range-based flag
5236 // inference.
5237 if (!AR->hasNoSignedWrap())
5238 (void)getSignedRange(AR);
5239
5240 if (!AR->hasNoUnsignedWrap())
5241 (void)getUnsignedRange(AR);
5242
5243 if (!AR->hasNoSelfWrap()) {
5244 const SCEV *BECount = getConstantMaxBackedgeTakenCount(AR->getLoop());
5245 if (const SCEVConstant *BECountMax = dyn_cast<SCEVConstant>(BECount)) {
5246 ConstantRange StepCR = getSignedRange(AR->getStepRecurrence(*this));
5247 const APInt &BECountAP = BECountMax->getAPInt();
5248 unsigned NoOverflowBitWidth =
5249 BECountAP.getActiveBits() + StepCR.getMinSignedBits();
5250 if (NoOverflowBitWidth <= getTypeSizeInBits(AR->getType()))
5251 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
5252 }
5253 }
5254}
5255
5257ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5259
5260 if (AR->hasNoSignedWrap())
5261 return Result;
5262
5263 if (!AR->isAffine())
5264 return Result;
5265
5266 // This function can be expensive, only try to prove NSW once per AddRec.
5267 if (!SignedWrapViaInductionTried.insert(AR).second)
5268 return Result;
5269
5270 const SCEV *Step = AR->getStepRecurrence(*this);
5271 const Loop *L = AR->getLoop();
5272
5273 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5274 // Note that this serves two purposes: It filters out loops that are
5275 // simply not analyzable, and it covers the case where this code is
5276 // being called from within backedge-taken count analysis, such that
5277 // attempting to ask for the backedge-taken count would likely result
5278 // in infinite recursion. In the later case, the analysis code will
5279 // cope with a conservative value, and it will take care to purge
5280 // that value once it has finished.
5281 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5282
5283 // Normally, in the cases we can prove no-overflow via a
5284 // backedge guarding condition, we can also compute a backedge
5285 // taken count for the loop. The exceptions are assumptions and
5286 // guards present in the loop -- SCEV is not great at exploiting
5287 // these to compute max backedge taken counts, but can still use
5288 // these to prove lack of overflow. Use this fact to avoid
5289 // doing extra work that may not pay off.
5290
5291 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5292 AC.assumptions().empty())
5293 return Result;
5294
5295 // If the backedge is guarded by a comparison with the pre-inc value the
5296 // addrec is safe. Also, if the entry is guarded by a comparison with the
5297 // start value and the backedge is guarded by a comparison with the post-inc
5298 // value, the addrec is safe.
5300 const SCEV *OverflowLimit =
5301 getSignedOverflowLimitForStep(Step, &Pred, this);
5302 if (OverflowLimit &&
5303 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
5304 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
5305 Result = setFlags(Result, SCEV::FlagNSW);
5306 }
5307 return Result;
5308}
5310ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
5312
5313 if (AR->hasNoUnsignedWrap())
5314 return Result;
5315
5316 if (!AR->isAffine())
5317 return Result;
5318
5319 // This function can be expensive, only try to prove NUW once per AddRec.
5320 if (!UnsignedWrapViaInductionTried.insert(AR).second)
5321 return Result;
5322
5323 const SCEV *Step = AR->getStepRecurrence(*this);
5324 unsigned BitWidth = getTypeSizeInBits(AR->getType());
5325 const Loop *L = AR->getLoop();
5326
5327 // Check whether the backedge-taken count is SCEVCouldNotCompute.
5328 // Note that this serves two purposes: It filters out loops that are
5329 // simply not analyzable, and it covers the case where this code is
5330 // being called from within backedge-taken count analysis, such that
5331 // attempting to ask for the backedge-taken count would likely result
5332 // in infinite recursion. In the later case, the analysis code will
5333 // cope with a conservative value, and it will take care to purge
5334 // that value once it has finished.
5335 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
5336
5337 // Normally, in the cases we can prove no-overflow via a
5338 // backedge guarding condition, we can also compute a backedge
5339 // taken count for the loop. The exceptions are assumptions and
5340 // guards present in the loop -- SCEV is not great at exploiting
5341 // these to compute max backedge taken counts, but can still use
5342 // these to prove lack of overflow. Use this fact to avoid
5343 // doing extra work that may not pay off.
5344
5345 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards &&
5346 AC.assumptions().empty())
5347 return Result;
5348
5349 // If the backedge is guarded by a comparison with the pre-inc value the
5350 // addrec is safe. Also, if the entry is guarded by a comparison with the
5351 // start value and the backedge is guarded by a comparison with the post-inc
5352 // value, the addrec is safe.
5353 if (isKnownPositive(Step)) {
5354 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
5355 getUnsignedRangeMax(Step));
5358 Result = setFlags(Result, SCEV::FlagNUW);
5359 }
5360 }
5361
5362 return Result;
5363}
5364
5365namespace {
5366
5367/// Represents an abstract binary operation. This may exist as a
5368/// normal instruction or constant expression, or may have been
5369/// derived from an expression tree.
5370struct BinaryOp {
5371 unsigned Opcode;
5372 Value *LHS;
5373 Value *RHS;
5374 bool IsNSW = false;
5375 bool IsNUW = false;
5376
5377 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
5378 /// constant expression.
5379 Operator *Op = nullptr;
5380
5381 explicit BinaryOp(Operator *Op)
5382 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
5383 Op(Op) {
5384 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
5385 IsNSW = OBO->hasNoSignedWrap();
5386 IsNUW = OBO->hasNoUnsignedWrap();
5387 }
5388 }
5389
5390 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
5391 bool IsNUW = false)
5392 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
5393};
5394
5395} // end anonymous namespace
5396
5397/// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
5398static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
5399 AssumptionCache &AC,
5400 const DominatorTree &DT,
5401 const Instruction *CxtI) {
5402 auto *Op = dyn_cast<Operator>(V);
5403 if (!Op)
5404 return std::nullopt;
5405
5406 // Implementation detail: all the cleverness here should happen without
5407 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
5408 // SCEV expressions when possible, and we should not break that.
5409
5410 switch (Op->getOpcode()) {
5411 case Instruction::Add:
5412 case Instruction::Sub:
5413 case Instruction::Mul:
5414 case Instruction::UDiv:
5415 case Instruction::URem:
5416 case Instruction::And:
5417 case Instruction::AShr:
5418 case Instruction::Shl:
5419 return BinaryOp(Op);
5420
5421 case Instruction::Or: {
5422 // Convert or disjoint into add nuw nsw.
5423 if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) {
5424 BinaryOp BinOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
5425 /*IsNSW=*/true, /*IsNUW=*/true);
5426 // Keep the reference to the original instruction so that we can later
5427 // check whether it can produce poison value or not.
5428 BinOp.Op = Op;
5429 return BinOp;
5430 }
5431 return BinaryOp(Op);
5432 }
5433
5434 case Instruction::Xor:
5435 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
5436 // If the RHS of the xor is a signmask, then this is just an add.
5437 // Instcombine turns add of signmask into xor as a strength reduction step.
5438 if (RHSC->getValue().isSignMask())
5439 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5440 // Binary `xor` is a bit-wise `add`.
5441 if (V->getType()->isIntegerTy(1))
5442 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
5443 return BinaryOp(Op);
5444
5445 case Instruction::LShr:
5446 // Turn logical shift right of a constant into a unsigned divide.
5447 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
5448 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
5449
5450 // If the shift count is not less than the bitwidth, the result of
5451 // the shift is undefined. Don't try to analyze it, because the
5452 // resolution chosen here may differ from the resolution chosen in
5453 // other parts of the compiler.
5454 if (SA->getValue().ult(BitWidth)) {
5455 Constant *X =
5456 ConstantInt::get(SA->getContext(),
5457 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
5458 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
5459 }
5460 }
5461 return BinaryOp(Op);
5462
5463 case Instruction::ExtractValue: {
5464 auto *EVI = cast<ExtractValueInst>(Op);
5465 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
5466 break;
5467
5468 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
5469 if (!WO)
5470 break;
5471
5472 Instruction::BinaryOps BinOp = WO->getBinaryOp();
5473 bool Signed = WO->isSigned();
5474 // TODO: Should add nuw/nsw flags for mul as well.
5475 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
5476 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
5477
5478 // Now that we know that all uses of the arithmetic-result component of
5479 // CI are guarded by the overflow check, we can go ahead and pretend
5480 // that the arithmetic is non-overflowing.
5481 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
5482 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
5483 }
5484
5485 default:
5486 break;
5487 }
5488
5489 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
5490 // semantics as a Sub, return a binary sub expression.
5491 if (auto *II = dyn_cast<IntrinsicInst>(V))
5492 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
5493 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
5494
5495 return std::nullopt;
5496}
5497
5498/// Helper function to createAddRecFromPHIWithCasts. We have a phi
5499/// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
5500/// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
5501/// way. This function checks if \p Op, an operand of this SCEVAddExpr,
5502/// follows one of the following patterns:
5503/// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5504/// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
5505/// If the SCEV expression of \p Op conforms with one of the expected patterns
5506/// we return the type of the truncation operation, and indicate whether the
5507/// truncated type should be treated as signed/unsigned by setting
5508/// \p Signed to true/false, respectively.
5509static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
5510 bool &Signed, ScalarEvolution &SE) {
5511 // The case where Op == SymbolicPHI (that is, with no type conversions on
5512 // the way) is handled by the regular add recurrence creating logic and
5513 // would have already been triggered in createAddRecForPHI. Reaching it here
5514 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
5515 // because one of the other operands of the SCEVAddExpr updating this PHI is
5516 // not invariant).
5517 //
5518 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
5519 // this case predicates that allow us to prove that Op == SymbolicPHI will
5520 // be added.
5521 if (Op == SymbolicPHI)
5522 return nullptr;
5523
5524 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
5525 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
5526 if (SourceBits != NewBits)
5527 return nullptr;
5528
5529 if (match(Op, m_scev_SExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5530 Signed = true;
5531 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5532 }
5533 if (match(Op, m_scev_ZExt(m_scev_Trunc(m_scev_Specific(SymbolicPHI))))) {
5534 Signed = false;
5535 return cast<SCEVCastExpr>(Op)->getOperand()->getType();
5536 }
5537 return nullptr;
5538}
5539
5540static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
5541 if (!PN->getType()->isIntegerTy())
5542 return nullptr;
5543 const Loop *L = LI.getLoopFor(PN->getParent());
5544 if (!L || L->getHeader() != PN->getParent())
5545 return nullptr;
5546 return L;
5547}
5548
5549// Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
5550// computation that updates the phi follows the following pattern:
5551// (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
5552// which correspond to a phi->trunc->sext/zext->add->phi update chain.
5553// If so, try to see if it can be rewritten as an AddRecExpr under some
5554// Predicates. If successful, return them as a pair. Also cache the results
5555// of the analysis.
5556//
5557// Example usage scenario:
5558// Say the Rewriter is called for the following SCEV:
5559// 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5560// where:
5561// %X = phi i64 (%Start, %BEValue)
5562// It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
5563// and call this function with %SymbolicPHI = %X.
5564//
5565// The analysis will find that the value coming around the backedge has
5566// the following SCEV:
5567// BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
5568// Upon concluding that this matches the desired pattern, the function
5569// will return the pair {NewAddRec, SmallPredsVec} where:
5570// NewAddRec = {%Start,+,%Step}
5571// SmallPredsVec = {P1, P2, P3} as follows:
5572// P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
5573// P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
5574// P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
5575// The returned pair means that SymbolicPHI can be rewritten into NewAddRec
5576// under the predicates {P1,P2,P3}.
5577// This predicated rewrite will be cached in PredicatedSCEVRewrites:
5578// PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
5579//
5580// TODO's:
5581//
5582// 1) Extend the Induction descriptor to also support inductions that involve
5583// casts: When needed (namely, when we are called in the context of the
5584// vectorizer induction analysis), a Set of cast instructions will be
5585// populated by this method, and provided back to isInductionPHI. This is
5586// needed to allow the vectorizer to properly record them to be ignored by
5587// the cost model and to avoid vectorizing them (otherwise these casts,
5588// which are redundant under the runtime overflow checks, will be
5589// vectorized, which can be costly).
5590//
5591// 2) Support additional induction/PHISCEV patterns: We also want to support
5592// inductions where the sext-trunc / zext-trunc operations (partly) occur
5593// after the induction update operation (the induction increment):
5594//
5595// (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
5596// which correspond to a phi->add->trunc->sext/zext->phi update chain.
5597//
5598// (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
5599// which correspond to a phi->trunc->add->sext/zext->phi update chain.
5600//
5601// 3) Outline common code with createAddRecFromPHI to avoid duplication.
5602std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5603ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
5605
5606 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
5607 // return an AddRec expression under some predicate.
5608
5609 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5610 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5611 assert(L && "Expecting an integer loop header phi");
5612
5613 // The loop may have multiple entrances or multiple exits; we can analyze
5614 // this phi as an addrec if it has a unique entry value and a unique
5615 // backedge value.
5616 Value *BEValueV = nullptr, *StartValueV = nullptr;
5617 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5618 Value *V = PN->getIncomingValue(i);
5619 if (L->contains(PN->getIncomingBlock(i))) {
5620 if (!BEValueV) {
5621 BEValueV = V;
5622 } else if (BEValueV != V) {
5623 BEValueV = nullptr;
5624 break;
5625 }
5626 } else if (!StartValueV) {
5627 StartValueV = V;
5628 } else if (StartValueV != V) {
5629 StartValueV = nullptr;
5630 break;
5631 }
5632 }
5633 if (!BEValueV || !StartValueV)
5634 return std::nullopt;
5635
5636 const SCEV *BEValue = getSCEV(BEValueV);
5637
5638 // If the value coming around the backedge is an add with the symbolic
5639 // value we just inserted, possibly with casts that we can ignore under
5640 // an appropriate runtime guard, then we found a simple induction variable!
5641 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
5642 if (!Add)
5643 return std::nullopt;
5644
5645 // If there is a single occurrence of the symbolic value, possibly
5646 // casted, replace it with a recurrence.
5647 unsigned FoundIndex = Add->getNumOperands();
5648 Type *TruncTy = nullptr;
5649 bool Signed;
5650 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5651 if ((TruncTy =
5652 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
5653 if (FoundIndex == e) {
5654 FoundIndex = i;
5655 break;
5656 }
5657
5658 if (FoundIndex == Add->getNumOperands())
5659 return std::nullopt;
5660
5661 // Create an add with everything but the specified operand.
5663 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5664 if (i != FoundIndex)
5665 Ops.push_back(Add->getOperand(i));
5666 const SCEV *Accum = getAddExpr(Ops);
5667
5668 // The runtime checks will not be valid if the step amount is
5669 // varying inside the loop.
5670 if (!isLoopInvariant(Accum, L))
5671 return std::nullopt;
5672
5673 // *** Part2: Create the predicates
5674
5675 // Analysis was successful: we have a phi-with-cast pattern for which we
5676 // can return an AddRec expression under the following predicates:
5677 //
5678 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
5679 // fits within the truncated type (does not overflow) for i = 0 to n-1.
5680 // P2: An Equal predicate that guarantees that
5681 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
5682 // P3: An Equal predicate that guarantees that
5683 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
5684 //
5685 // As we next prove, the above predicates guarantee that:
5686 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
5687 //
5688 //
5689 // More formally, we want to prove that:
5690 // Expr(i+1) = Start + (i+1) * Accum
5691 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5692 //
5693 // Given that:
5694 // 1) Expr(0) = Start
5695 // 2) Expr(1) = Start + Accum
5696 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
5697 // 3) Induction hypothesis (step i):
5698 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
5699 //
5700 // Proof:
5701 // Expr(i+1) =
5702 // = Start + (i+1)*Accum
5703 // = (Start + i*Accum) + Accum
5704 // = Expr(i) + Accum
5705 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
5706 // :: from step i
5707 //
5708 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
5709 //
5710 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
5711 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
5712 // + Accum :: from P3
5713 //
5714 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
5715 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
5716 //
5717 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
5718 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
5719 //
5720 // By induction, the same applies to all iterations 1<=i<n:
5721 //
5722
5723 // Create a truncated addrec for which we will add a no overflow check (P1).
5724 const SCEV *StartVal = getSCEV(StartValueV);
5725 const SCEV *PHISCEV =
5726 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
5727 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
5728
5729 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
5730 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
5731 // will be constant.
5732 //
5733 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
5734 // add P1.
5735 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
5739 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
5740 Predicates.push_back(AddRecPred);
5741 }
5742
5743 // Create the Equal Predicates P2,P3:
5744
5745 // It is possible that the predicates P2 and/or P3 are computable at
5746 // compile time due to StartVal and/or Accum being constants.
5747 // If either one is, then we can check that now and escape if either P2
5748 // or P3 is false.
5749
5750 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
5751 // for each of StartVal and Accum
5752 auto getExtendedExpr = [&](const SCEV *Expr,
5753 bool CreateSignExtend) -> const SCEV * {
5754 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
5755 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
5756 const SCEV *ExtendedExpr =
5757 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
5758 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
5759 return ExtendedExpr;
5760 };
5761
5762 // Given:
5763 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
5764 // = getExtendedExpr(Expr)
5765 // Determine whether the predicate P: Expr == ExtendedExpr
5766 // is known to be false at compile time
5767 auto PredIsKnownFalse = [&](const SCEV *Expr,
5768 const SCEV *ExtendedExpr) -> bool {
5769 return Expr != ExtendedExpr &&
5770 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
5771 };
5772
5773 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
5774 if (PredIsKnownFalse(StartVal, StartExtended)) {
5775 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
5776 return std::nullopt;
5777 }
5778
5779 // The Step is always Signed (because the overflow checks are either
5780 // NSSW or NUSW)
5781 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
5782 if (PredIsKnownFalse(Accum, AccumExtended)) {
5783 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
5784 return std::nullopt;
5785 }
5786
5787 auto AppendPredicate = [&](const SCEV *Expr,
5788 const SCEV *ExtendedExpr) -> void {
5789 if (Expr != ExtendedExpr &&
5790 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
5791 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
5792 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
5793 Predicates.push_back(Pred);
5794 }
5795 };
5796
5797 AppendPredicate(StartVal, StartExtended);
5798 AppendPredicate(Accum, AccumExtended);
5799
5800 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
5801 // which the casts had been folded away. The caller can rewrite SymbolicPHI
5802 // into NewAR if it will also add the runtime overflow checks specified in
5803 // Predicates.
5804 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
5805
5806 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
5807 std::make_pair(NewAR, Predicates);
5808 // Remember the result of the analysis for this SCEV at this locayyytion.
5809 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
5810 return PredRewrite;
5811}
5812
5813std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5815 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
5816 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
5817 if (!L)
5818 return std::nullopt;
5819
5820 // Check to see if we already analyzed this PHI.
5821 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
5822 if (I != PredicatedSCEVRewrites.end()) {
5823 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
5824 I->second;
5825 // Analysis was done before and failed to create an AddRec:
5826 if (Rewrite.first == SymbolicPHI)
5827 return std::nullopt;
5828 // Analysis was done before and succeeded to create an AddRec under
5829 // a predicate:
5830 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
5831 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
5832 return Rewrite;
5833 }
5834
5835 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
5836 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
5837
5838 // Record in the cache that the analysis failed
5839 if (!Rewrite) {
5841 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
5842 return std::nullopt;
5843 }
5844
5845 return Rewrite;
5846}
5847
5848// FIXME: This utility is currently required because the Rewriter currently
5849// does not rewrite this expression:
5850// {0, +, (sext ix (trunc iy to ix) to iy)}
5851// into {0, +, %step},
5852// even when the following Equal predicate exists:
5853// "%step == (sext ix (trunc iy to ix) to iy)".
5855 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2,
5856 ArrayRef<const SCEVPredicate *> NoWrapPreds) const {
5857 if (AR1 == AR2)
5858 return true;
5859
5860 SCEVUnionPredicate NoWrapUnionPred(NoWrapPreds, SE);
5861 SCEVUnionPredicate AllPreds = Preds->getUnionWith(&NoWrapUnionPred, SE);
5862 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
5863 if (Expr1 != Expr2 &&
5864 !AllPreds.implies(SE.getEqualPredicate(Expr1, Expr2), SE) &&
5865 !AllPreds.implies(SE.getEqualPredicate(Expr2, Expr1), SE))
5866 return false;
5867 return true;
5868 };
5869
5870 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
5871 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
5872 return false;
5873 return true;
5874}
5875
5876/// A helper function for createAddRecFromPHI to handle simple cases.
5877///
5878/// This function tries to find an AddRec expression for the simplest (yet most
5879/// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
5880/// If it fails, createAddRecFromPHI will use a more general, but slow,
5881/// technique for finding the AddRec expression.
5882const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
5883 Value *BEValueV,
5884 Value *StartValueV) {
5885 const Loop *L = LI.getLoopFor(PN->getParent());
5886 assert(L && L->getHeader() == PN->getParent());
5887 assert(BEValueV && StartValueV);
5888
5889 auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
5890 if (!BO)
5891 return nullptr;
5892
5893 if (BO->Opcode != Instruction::Add)
5894 return nullptr;
5895
5896 const SCEV *Accum = nullptr;
5897 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
5898 Accum = getSCEV(BO->RHS);
5899 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
5900 Accum = getSCEV(BO->LHS);
5901
5902 if (!Accum)
5903 return nullptr;
5904
5906 if (BO->IsNUW)
5907 Flags = setFlags(Flags, SCEV::FlagNUW);
5908 if (BO->IsNSW)
5909 Flags = setFlags(Flags, SCEV::FlagNSW);
5910
5911 const SCEV *StartVal = getSCEV(StartValueV);
5912 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5913 insertValueToMap(PN, PHISCEV);
5914
5915 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
5916 inferNoWrapViaConstantRanges(AR);
5917
5918 // We can add Flags to the post-inc expression only if we
5919 // know that it is *undefined behavior* for BEValueV to
5920 // overflow.
5921 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
5922 assert(isLoopInvariant(Accum, L) &&
5923 "Accum is defined outside L, but is not invariant?");
5924 if (isAddRecNeverPoison(BEInst, L))
5925 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5926 }
5927
5928 return PHISCEV;
5929}
5930
5931const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5932 const Loop *L = LI.getLoopFor(PN->getParent());
5933 if (!L || L->getHeader() != PN->getParent())
5934 return nullptr;
5935
5936 // The loop may have multiple entrances or multiple exits; we can analyze
5937 // this phi as an addrec if it has a unique entry value and a unique
5938 // backedge value.
5939 Value *BEValueV = nullptr, *StartValueV = nullptr;
5940 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5941 Value *V = PN->getIncomingValue(i);
5942 if (L->contains(PN->getIncomingBlock(i))) {
5943 if (!BEValueV) {
5944 BEValueV = V;
5945 } else if (BEValueV != V) {
5946 BEValueV = nullptr;
5947 break;
5948 }
5949 } else if (!StartValueV) {
5950 StartValueV = V;
5951 } else if (StartValueV != V) {
5952 StartValueV = nullptr;
5953 break;
5954 }
5955 }
5956 if (!BEValueV || !StartValueV)
5957 return nullptr;
5958
5959 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5960 "PHI node already processed?");
5961
5962 // First, try to find AddRec expression without creating a fictituos symbolic
5963 // value for PN.
5964 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5965 return S;
5966
5967 // Handle PHI node value symbolically.
5968 const SCEV *SymbolicName = getUnknown(PN);
5969 insertValueToMap(PN, SymbolicName);
5970
5971 // Using this symbolic name for the PHI, analyze the value coming around
5972 // the back-edge.
5973 const SCEV *BEValue = getSCEV(BEValueV);
5974
5975 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5976 // has a special value for the first iteration of the loop.
5977
5978 // If the value coming around the backedge is an add with the symbolic
5979 // value we just inserted, then we found a simple induction variable!
5980 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5981 // If there is a single occurrence of the symbolic value, replace it
5982 // with a recurrence.
5983 unsigned FoundIndex = Add->getNumOperands();
5984 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5985 if (Add->getOperand(i) == SymbolicName)
5986 if (FoundIndex == e) {
5987 FoundIndex = i;
5988 break;
5989 }
5990
5991 if (FoundIndex != Add->getNumOperands()) {
5992 // Create an add with everything but the specified operand.
5994 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5995 if (i != FoundIndex)
5996 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5997 L, *this));
5998 const SCEV *Accum = getAddExpr(Ops);
5999
6000 // This is not a valid addrec if the step amount is varying each
6001 // loop iteration, but is not itself an addrec in this loop.
6002 if (isLoopInvariant(Accum, L) ||
6003 (isa<SCEVAddRecExpr>(Accum) &&
6004 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
6006
6007 if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
6008 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
6009 if (BO->IsNUW)
6010 Flags = setFlags(Flags, SCEV::FlagNUW);
6011 if (BO->IsNSW)
6012 Flags = setFlags(Flags, SCEV::FlagNSW);
6013 }
6014 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
6015 if (GEP->getOperand(0) == PN) {
6016 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
6017 // If the increment has any nowrap flags, then we know the address
6018 // space cannot be wrapped around.
6019 if (NW != GEPNoWrapFlags::none())
6020 Flags = setFlags(Flags, SCEV::FlagNW);
6021 // If the GEP is nuw or nusw with non-negative offset, we know that
6022 // no unsigned wrap occurs. We cannot set the nsw flag as only the
6023 // offset is treated as signed, while the base is unsigned.
6024 if (NW.hasNoUnsignedWrap() ||
6026 Flags = setFlags(Flags, SCEV::FlagNUW);
6027 }
6028
6029 // We cannot transfer nuw and nsw flags from subtraction
6030 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
6031 // for instance.
6032 }
6033
6034 const SCEV *StartVal = getSCEV(StartValueV);
6035 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
6036
6037 // Okay, for the entire analysis of this edge we assumed the PHI
6038 // to be symbolic. We now need to go back and purge all of the
6039 // entries for the scalars that use the symbolic expression.
6040 forgetMemoizedResults({SymbolicName});
6041 insertValueToMap(PN, PHISCEV);
6042
6043 if (auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV))
6044 inferNoWrapViaConstantRanges(AR);
6045
6046 // We can add Flags to the post-inc expression only if we
6047 // know that it is *undefined behavior* for BEValueV to
6048 // overflow.
6049 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
6050 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
6051 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
6052
6053 return PHISCEV;
6054 }
6055 }
6056 } else {
6057 // Otherwise, this could be a loop like this:
6058 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
6059 // In this case, j = {1,+,1} and BEValue is j.
6060 // Because the other in-value of i (0) fits the evolution of BEValue
6061 // i really is an addrec evolution.
6062 //
6063 // We can generalize this saying that i is the shifted value of BEValue
6064 // by one iteration:
6065 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
6066
6067 // Do not allow refinement in rewriting of BEValue.
6068 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
6069 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
6070 if (Shifted != getCouldNotCompute() && Start != getCouldNotCompute() &&
6071 isGuaranteedNotToCauseUB(Shifted) && ::impliesPoison(Shifted, Start)) {
6072 const SCEV *StartVal = getSCEV(StartValueV);
6073 if (Start == StartVal) {
6074 // Okay, for the entire analysis of this edge we assumed the PHI
6075 // to be symbolic. We now need to go back and purge all of the
6076 // entries for the scalars that use the symbolic expression.
6077 forgetMemoizedResults({SymbolicName});
6078 insertValueToMap(PN, Shifted);
6079 return Shifted;
6080 }
6081 }
6082 }
6083
6084 // Remove the temporary PHI node SCEV that has been inserted while intending
6085 // to create an AddRecExpr for this PHI node. We can not keep this temporary
6086 // as it will prevent later (possibly simpler) SCEV expressions to be added
6087 // to the ValueExprMap.
6088 eraseValueFromMap(PN);
6089
6090 return nullptr;
6091}
6092
6093// Try to match a control flow sequence that branches out at BI and merges back
6094// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
6095// match.
6097 Value *&C, Value *&LHS, Value *&RHS) {
6098 C = BI->getCondition();
6099
6100 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
6101 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
6102
6103 Use &LeftUse = Merge->getOperandUse(0);
6104 Use &RightUse = Merge->getOperandUse(1);
6105
6106 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
6107 LHS = LeftUse;
6108 RHS = RightUse;
6109 return true;
6110 }
6111
6112 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
6113 LHS = RightUse;
6114 RHS = LeftUse;
6115 return true;
6116 }
6117
6118 return false;
6119}
6120
6122 Value *&Cond, Value *&LHS,
6123 Value *&RHS) {
6124 auto IsReachable =
6125 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
6126 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
6127 // Try to match
6128 //
6129 // br %cond, label %left, label %right
6130 // left:
6131 // br label %merge
6132 // right:
6133 // br label %merge
6134 // merge:
6135 // V = phi [ %x, %left ], [ %y, %right ]
6136 //
6137 // as "select %cond, %x, %y"
6138
6139 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
6140 assert(IDom && "At least the entry block should dominate PN");
6141
6142 auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator());
6143 return BI && BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS);
6144 }
6145 return false;
6146}
6147
6148const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
6149 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6150 if (getOperandsForSelectLikePHI(DT, PN, Cond, LHS, RHS) &&
6153 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
6154
6155 return nullptr;
6156}
6157
6159 BinaryOperator *CommonInst = nullptr;
6160 // Check if instructions are identical.
6161 for (Value *Incoming : PN->incoming_values()) {
6162 auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
6163 if (!IncomingInst)
6164 return nullptr;
6165 if (CommonInst) {
6166 if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
6167 return nullptr; // Not identical, give up
6168 } else {
6169 // Remember binary operator
6170 CommonInst = IncomingInst;
6171 }
6172 }
6173 return CommonInst;
6174}
6175
6176/// Returns SCEV for the first operand of a phi if all phi operands have
6177/// identical opcodes and operands
6178/// eg.
6179/// a: %add = %a + %b
6180/// br %c
6181/// b: %add1 = %a + %b
6182/// br %c
6183/// c: %phi = phi [%add, a], [%add1, b]
6184/// scev(%phi) => scev(%add)
6185const SCEV *
6186ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
6187 BinaryOperator *CommonInst = getCommonInstForPHI(PN);
6188 if (!CommonInst)
6189 return nullptr;
6190
6191 // Check if SCEV exprs for instructions are identical.
6192 const SCEV *CommonSCEV = getSCEV(CommonInst);
6193 bool SCEVExprsIdentical =
6195 [this, CommonSCEV](Value *V) { return CommonSCEV == getSCEV(V); });
6196 return SCEVExprsIdentical ? CommonSCEV : nullptr;
6197}
6198
6199const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
6200 if (const SCEV *S = createAddRecFromPHI(PN))
6201 return S;
6202
6203 // We do not allow simplifying phi (undef, X) to X here, to avoid reusing the
6204 // phi node for X.
6205 if (Value *V = simplifyInstruction(
6206 PN, {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
6207 /*UseInstrInfo=*/true, /*CanUseUndef=*/false}))
6208 return getSCEV(V);
6209
6210 if (const SCEV *S = createNodeForPHIWithIdenticalOperands(PN))
6211 return S;
6212
6213 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
6214 return S;
6215
6216 // If it's not a loop phi, we can't handle it yet.
6217 return getUnknown(PN);
6218}
6219
6220bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
6221 SCEVTypes RootKind) {
6222 struct FindClosure {
6223 const SCEV *OperandToFind;
6224 const SCEVTypes RootKind; // Must be a sequential min/max expression.
6225 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
6226
6227 bool Found = false;
6228
6229 bool canRecurseInto(SCEVTypes Kind) const {
6230 // We can only recurse into the SCEV expression of the same effective type
6231 // as the type of our root SCEV expression, and into zero-extensions.
6232 return RootKind == Kind || NonSequentialRootKind == Kind ||
6233 scZeroExtend == Kind;
6234 };
6235
6236 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
6237 : OperandToFind(OperandToFind), RootKind(RootKind),
6238 NonSequentialRootKind(
6240 RootKind)) {}
6241
6242 bool follow(const SCEV *S) {
6243 Found = S == OperandToFind;
6244
6245 return !isDone() && canRecurseInto(S->getSCEVType());
6246 }
6247
6248 bool isDone() const { return Found; }
6249 };
6250
6251 FindClosure FC(OperandToFind, RootKind);
6252 visitAll(Root, FC);
6253 return FC.Found;
6254}
6255
6256std::optional<const SCEV *>
6257ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
6258 ICmpInst *Cond,
6259 Value *TrueVal,
6260 Value *FalseVal) {
6261 // Try to match some simple smax or umax patterns.
6262 auto *ICI = Cond;
6263
6264 Value *LHS = ICI->getOperand(0);
6265 Value *RHS = ICI->getOperand(1);
6266
6267 switch (ICI->getPredicate()) {
6268 case ICmpInst::ICMP_SLT:
6269 case ICmpInst::ICMP_SLE:
6270 case ICmpInst::ICMP_ULT:
6271 case ICmpInst::ICMP_ULE:
6272 std::swap(LHS, RHS);
6273 [[fallthrough]];
6274 case ICmpInst::ICMP_SGT:
6275 case ICmpInst::ICMP_SGE:
6276 case ICmpInst::ICMP_UGT:
6277 case ICmpInst::ICMP_UGE:
6278 // a > b ? a+x : b+x -> max(a, b)+x
6279 // a > b ? b+x : a+x -> min(a, b)+x
6281 bool Signed = ICI->isSigned();
6282 const SCEV *LA = getSCEV(TrueVal);
6283 const SCEV *RA = getSCEV(FalseVal);
6284 const SCEV *LS = getSCEV(LHS);
6285 const SCEV *RS = getSCEV(RHS);
6286 if (LA->getType()->isPointerTy()) {
6287 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
6288 // Need to make sure we can't produce weird expressions involving
6289 // negated pointers.
6290 if (LA == LS && RA == RS)
6291 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
6292 if (LA == RS && RA == LS)
6293 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
6294 }
6295 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
6296 if (Op->getType()->isPointerTy()) {
6299 return Op;
6300 }
6301 if (Signed)
6302 Op = getNoopOrSignExtend(Op, Ty);
6303 else
6304 Op = getNoopOrZeroExtend(Op, Ty);
6305 return Op;
6306 };
6307 LS = CoerceOperand(LS);
6308 RS = CoerceOperand(RS);
6310 break;
6311 const SCEV *LDiff = getMinusSCEV(LA, LS);
6312 const SCEV *RDiff = getMinusSCEV(RA, RS);
6313 if (LDiff == RDiff)
6314 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
6315 LDiff);
6316 LDiff = getMinusSCEV(LA, RS);
6317 RDiff = getMinusSCEV(RA, LS);
6318 if (LDiff == RDiff)
6319 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
6320 LDiff);
6321 }
6322 break;
6323 case ICmpInst::ICMP_NE:
6324 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
6325 std::swap(TrueVal, FalseVal);
6326 [[fallthrough]];
6327 case ICmpInst::ICMP_EQ:
6328 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
6331 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
6332 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
6333 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
6334 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
6335 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
6336 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
6337 return getAddExpr(getUMaxExpr(X, C), Y);
6338 }
6339 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
6340 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
6341 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
6342 // -> umin_seq(x, umin (..., umin_seq(...), ...))
6344 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
6345 const SCEV *X = getSCEV(LHS);
6346 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
6347 X = ZExt->getOperand();
6348 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
6349 const SCEV *FalseValExpr = getSCEV(FalseVal);
6350 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
6351 return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
6352 /*Sequential=*/true);
6353 }
6354 }
6355 break;
6356 default:
6357 break;
6358 }
6359
6360 return std::nullopt;
6361}
6362
6363static std::optional<const SCEV *>
6365 const SCEV *TrueExpr, const SCEV *FalseExpr) {
6366 assert(CondExpr->getType()->isIntegerTy(1) &&
6367 TrueExpr->getType() == FalseExpr->getType() &&
6368 TrueExpr->getType()->isIntegerTy(1) &&
6369 "Unexpected operands of a select.");
6370
6371 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
6372 // --> C + (umin_seq cond, x - C)
6373 //
6374 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
6375 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
6376 // --> C + (umin_seq ~cond, x - C)
6377
6378 // FIXME: while we can't legally model the case where both of the hands
6379 // are fully variable, we only require that the *difference* is constant.
6380 if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
6381 return std::nullopt;
6382
6383 const SCEV *X, *C;
6384 if (isa<SCEVConstant>(TrueExpr)) {
6385 CondExpr = SE->getNotSCEV(CondExpr);
6386 X = FalseExpr;
6387 C = TrueExpr;
6388 } else {
6389 X = TrueExpr;
6390 C = FalseExpr;
6391 }
6392 return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
6393 /*Sequential=*/true));
6394}
6395
6396static std::optional<const SCEV *>
6398 Value *FalseVal) {
6399 if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
6400 return std::nullopt;
6401
6402 const auto *SECond = SE->getSCEV(Cond);
6403 const auto *SETrue = SE->getSCEV(TrueVal);
6404 const auto *SEFalse = SE->getSCEV(FalseVal);
6405 return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
6406}
6407
6408const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
6409 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
6410 assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
6411 assert(TrueVal->getType() == FalseVal->getType() &&
6412 V->getType() == TrueVal->getType() &&
6413 "Types of select hands and of the result must match.");
6414
6415 // For now, only deal with i1-typed `select`s.
6416 if (!V->getType()->isIntegerTy(1))
6417 return getUnknown(V);
6418
6419 if (std::optional<const SCEV *> S =
6420 createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
6421 return *S;
6422
6423 return getUnknown(V);
6424}
6425
6426const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
6427 Value *TrueVal,
6428 Value *FalseVal) {
6429 // Handle "constant" branch or select. This can occur for instance when a
6430 // loop pass transforms an inner loop and moves on to process the outer loop.
6431 if (auto *CI = dyn_cast<ConstantInt>(Cond))
6432 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
6433
6434 if (auto *I = dyn_cast<Instruction>(V)) {
6435 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
6436 if (std::optional<const SCEV *> S =
6437 createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
6438 TrueVal, FalseVal))
6439 return *S;
6440 }
6441 }
6442
6443 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
6444}
6445
6446/// Expand GEP instructions into add and multiply operations. This allows them
6447/// to be analyzed by regular SCEV code.
6448const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
6449 assert(GEP->getSourceElementType()->isSized() &&
6450 "GEP source element type must be sized");
6451
6452 SmallVector<SCEVUse, 4> IndexExprs;
6453 for (Value *Index : GEP->indices())
6454 IndexExprs.push_back(getSCEV(Index));
6455 return getGEPExpr(GEP, IndexExprs);
6456}
6457
6458APInt ScalarEvolution::getConstantMultipleImpl(const SCEV *S,
6459 const Instruction *CtxI) {
6460 uint64_t BitWidth = getTypeSizeInBits(S->getType());
6461 auto GetShiftedByZeros = [BitWidth](uint32_t TrailingZeros) {
6462 return TrailingZeros >= BitWidth
6464 : APInt::getOneBitSet(BitWidth, TrailingZeros);
6465 };
6466 auto GetGCDMultiple = [this, CtxI](const SCEVNAryExpr *N) {
6467 // The result is GCD of all operands results.
6468 APInt Res = getConstantMultiple(N->getOperand(0), CtxI);
6469 for (unsigned I = 1, E = N->getNumOperands(); I < E && Res != 1; ++I)
6471 Res, getConstantMultiple(N->getOperand(I), CtxI));
6472 return Res;
6473 };
6474
6475 switch (S->getSCEVType()) {
6476 case scConstant:
6477 return cast<SCEVConstant>(S)->getAPInt();
6478 case scPtrToAddr:
6479 case scPtrToInt:
6480 return getConstantMultiple(cast<SCEVCastExpr>(S)->getOperand());
6481 case scUDivExpr:
6482 case scVScale:
6483 return APInt(BitWidth, 1);
6484 case scTruncate: {
6485 // Only multiples that are a power of 2 will hold after truncation.
6486 const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
6487 uint32_t TZ = getMinTrailingZeros(T->getOperand(), CtxI);
6488 return GetShiftedByZeros(TZ);
6489 }
6490 case scZeroExtend: {
6491 const SCEVZeroExtendExpr *Z = cast<SCEVZeroExtendExpr>(S);
6492 return getConstantMultiple(Z->getOperand(), CtxI).zext(BitWidth);
6493 }
6494 case scSignExtend: {
6495 // Only multiples that are a power of 2 will hold after sext.
6496 const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
6497 uint32_t TZ = getMinTrailingZeros(E->getOperand(), CtxI);
6498 return GetShiftedByZeros(TZ);
6499 }
6500 case scMulExpr: {
6501 const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
6502 if (M->hasNoUnsignedWrap()) {
6503 // The result is the product of all operand results.
6504 APInt Res = getConstantMultiple(M->getOperand(0), CtxI);
6505 for (const SCEV *Operand : M->operands().drop_front())
6506 Res = Res * getConstantMultiple(Operand, CtxI);
6507 return Res;
6508 }
6509
6510 // If there are no wrap guarentees, find the trailing zeros, which is the
6511 // sum of trailing zeros for all its operands.
6512 uint32_t TZ = 0;
6513 for (const SCEV *Operand : M->operands())
6514 TZ += getMinTrailingZeros(Operand, CtxI);
6515 return GetShiftedByZeros(TZ);
6516 }
6517 case scAddExpr:
6518 case scAddRecExpr: {
6519 const SCEVNAryExpr *N = cast<SCEVNAryExpr>(S);
6520 if (N->hasNoUnsignedWrap())
6521 return GetGCDMultiple(N);
6522 // Find the trailing bits, which is the minimum of its operands.
6523 uint32_t TZ = getMinTrailingZeros(N->getOperand(0), CtxI);
6524 for (const SCEV *Operand : N->operands().drop_front())
6525 TZ = std::min(TZ, getMinTrailingZeros(Operand, CtxI));
6526 return GetShiftedByZeros(TZ);
6527 }
6528 case scUMaxExpr:
6529 case scSMaxExpr:
6530 case scUMinExpr:
6531 case scSMinExpr:
6533 return GetGCDMultiple(cast<SCEVNAryExpr>(S));
6534 case scUnknown: {
6535 // Ask ValueTracking for known bits. SCEVUnknown only become available at
6536 // the point their underlying IR instruction has been defined. If CtxI was
6537 // not provided, use:
6538 // * the first instruction in the entry block if it is an argument
6539 // * the instruction itself otherwise.
6540 const SCEVUnknown *U = cast<SCEVUnknown>(S);
6541 if (!CtxI) {
6542 if (isa<Argument>(U->getValue()))
6543 CtxI = &*F.getEntryBlock().begin();
6544 else if (auto *I = dyn_cast<Instruction>(U->getValue()))
6545 CtxI = I;
6546 }
6547 unsigned Known =
6548 computeKnownBits(U->getValue(),
6549 SimplifyQuery(getDataLayout(), &DT, &AC, CtxI)
6550 .allowEphemerals(true))
6551 .countMinTrailingZeros();
6552 return GetShiftedByZeros(Known);
6553 }
6554 case scCouldNotCompute:
6555 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6556 }
6557 llvm_unreachable("Unknown SCEV kind!");
6558}
6559
6561 const Instruction *CtxI) {
6562 // Skip looking up and updating the cache if there is a context instruction,
6563 // as the result will only be valid in the specified context.
6564 if (CtxI)
6565 return getConstantMultipleImpl(S, CtxI);
6566
6567 auto I = ConstantMultipleCache.find(S);
6568 if (I != ConstantMultipleCache.end())
6569 return I->second;
6570
6571 APInt Result = getConstantMultipleImpl(S, CtxI);
6572 auto InsertPair = ConstantMultipleCache.insert({S, Result});
6573 assert(InsertPair.second && "Should insert a new key");
6574 return InsertPair.first->second;
6575}
6576
6578 APInt Multiple = getConstantMultiple(S);
6579 return Multiple == 0 ? APInt(Multiple.getBitWidth(), 1) : Multiple;
6580}
6581
6583 const Instruction *CtxI) {
6584 return std::min(getConstantMultiple(S, CtxI).countTrailingZeros(),
6585 (unsigned)getTypeSizeInBits(S->getType()));
6586}
6587
6588/// Helper method to assign a range to V from metadata present in the IR.
6589static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
6591 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
6592 return getConstantRangeFromMetadata(*MD);
6593 if (const auto *CB = dyn_cast<CallBase>(V))
6594 if (std::optional<ConstantRange> Range = CB->getRange())
6595 return Range;
6596 }
6597 if (auto *A = dyn_cast<Argument>(V))
6598 if (std::optional<ConstantRange> Range = A->getRange())
6599 return Range;
6600
6601 return std::nullopt;
6602}
6603
6605 SCEV::NoWrapFlags Flags) {
6606 if (AddRec->getNoWrapFlags(Flags) != Flags) {
6607 AddRec->setNoWrapFlags(Flags);
6608 UnsignedRanges.erase(AddRec);
6609 SignedRanges.erase(AddRec);
6610 ConstantMultipleCache.erase(AddRec);
6611 }
6612}
6613
6614ConstantRange ScalarEvolution::
6615getRangeForUnknownRecurrence(const SCEVUnknown *U) {
6616 const DataLayout &DL = getDataLayout();
6617
6618 unsigned BitWidth = getTypeSizeInBits(U->getType());
6619 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
6620
6621 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
6622 // use information about the trip count to improve our available range. Note
6623 // that the trip count independent cases are already handled by known bits.
6624 // WARNING: The definition of recurrence used here is subtly different than
6625 // the one used by AddRec (and thus most of this file). Step is allowed to
6626 // be arbitrarily loop varying here, where AddRec allows only loop invariant
6627 // and other addrecs in the same loop (for non-affine addrecs). The code
6628 // below intentionally handles the case where step is not loop invariant.
6629 auto *P = dyn_cast<PHINode>(U->getValue());
6630 if (!P)
6631 return FullSet;
6632
6633 // Make sure that no Phi input comes from an unreachable block. Otherwise,
6634 // even the values that are not available in these blocks may come from them,
6635 // and this leads to false-positive recurrence test.
6636 for (auto *Pred : predecessors(P->getParent()))
6637 if (!DT.isReachableFromEntry(Pred))
6638 return FullSet;
6639
6640 BinaryOperator *BO;
6641 Value *Start, *Step;
6642 if (!matchSimpleRecurrence(P, BO, Start, Step))
6643 return FullSet;
6644
6645 // If we found a recurrence in reachable code, we must be in a loop. Note
6646 // that BO might be in some subloop of L, and that's completely okay.
6647 auto *L = LI.getLoopFor(P->getParent());
6648 assert(L && L->getHeader() == P->getParent());
6649 if (!L->contains(BO->getParent()))
6650 // NOTE: This bailout should be an assert instead. However, asserting
6651 // the condition here exposes a case where LoopFusion is querying SCEV
6652 // with malformed loop information during the midst of the transform.
6653 // There doesn't appear to be an obvious fix, so for the moment bailout
6654 // until the caller issue can be fixed. PR49566 tracks the bug.
6655 return FullSet;
6656
6657 // TODO: Extend to other opcodes such as mul, and div
6658 switch (BO->getOpcode()) {
6659 default:
6660 return FullSet;
6661 case Instruction::AShr:
6662 case Instruction::LShr:
6663 case Instruction::Shl:
6664 break;
6665 };
6666
6667 if (BO->getOperand(0) != P)
6668 // TODO: Handle the power function forms some day.
6669 return FullSet;
6670
6671 unsigned TC = getSmallConstantMaxTripCount(L);
6672 if (!TC || TC >= BitWidth)
6673 return FullSet;
6674
6675 auto KnownStart = computeKnownBits(Start, DL, &AC, nullptr, &DT);
6676 auto KnownStep = computeKnownBits(Step, DL, &AC, nullptr, &DT);
6677 assert(KnownStart.getBitWidth() == BitWidth &&
6678 KnownStep.getBitWidth() == BitWidth);
6679
6680 // Compute total shift amount, being careful of overflow and bitwidths.
6681 auto MaxShiftAmt = KnownStep.getMaxValue();
6682 APInt TCAP(BitWidth, TC-1);
6683 bool Overflow = false;
6684 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
6685 if (Overflow)
6686 return FullSet;
6687
6688 switch (BO->getOpcode()) {
6689 default:
6690 llvm_unreachable("filtered out above");
6691 case Instruction::AShr: {
6692 // For each ashr, three cases:
6693 // shift = 0 => unchanged value
6694 // saturation => 0 or -1
6695 // other => a value closer to zero (of the same sign)
6696 // Thus, the end value is closer to zero than the start.
6697 auto KnownEnd = KnownBits::ashr(KnownStart,
6698 KnownBits::makeConstant(TotalShift));
6699 if (KnownStart.isNonNegative())
6700 // Analogous to lshr (simply not yet canonicalized)
6701 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6702 KnownStart.getMaxValue() + 1);
6703 if (KnownStart.isNegative())
6704 // End >=u Start && End <=s Start
6705 return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
6706 KnownEnd.getMaxValue() + 1);
6707 break;
6708 }
6709 case Instruction::LShr: {
6710 // For each lshr, three cases:
6711 // shift = 0 => unchanged value
6712 // saturation => 0
6713 // other => a smaller positive number
6714 // Thus, the low end of the unsigned range is the last value produced.
6715 auto KnownEnd = KnownBits::lshr(KnownStart,
6716 KnownBits::makeConstant(TotalShift));
6717 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
6718 KnownStart.getMaxValue() + 1);
6719 }
6720 case Instruction::Shl: {
6721 // Iff no bits are shifted out, value increases on every shift.
6722 auto KnownEnd = KnownBits::shl(KnownStart,
6723 KnownBits::makeConstant(TotalShift));
6724 if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
6725 return ConstantRange(KnownStart.getMinValue(),
6726 KnownEnd.getMaxValue() + 1);
6727 break;
6728 }
6729 };
6730 return FullSet;
6731}
6732
6733// The goal of this function is to check if recursively visiting the operands
6734// of this PHI might lead to an infinite loop. If we do see such a loop,
6735// there's no good way to break it, so we avoid analyzing such cases.
6736//
6737// getRangeRef previously used a visited set to avoid infinite loops, but this
6738// caused other issues: the result was dependent on the order of getRangeRef
6739// calls, and the interaction with createSCEVIter could cause a stack overflow
6740// in some cases (see issue #148253).
6741//
6742// FIXME: The way this is implemented is overly conservative; this checks
6743// for a few obviously safe patterns, but anything that doesn't lead to
6744// recursion is fine.
6746 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
6748 return true;
6749
6750 if (all_of(PHI->operands(),
6751 [&](Value *Operand) { return DT.dominates(Operand, PHI); }))
6752 return true;
6753
6754 return false;
6755}
6756
6757const ConstantRange &
6758ScalarEvolution::getRangeRefIter(const SCEV *S,
6759 ScalarEvolution::RangeSignHint SignHint) {
6760 DenseMap<const SCEV *, ConstantRange> &Cache =
6761 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6762 : SignedRanges;
6763 SmallVector<SCEVUse> WorkList;
6764 SmallPtrSet<const SCEV *, 8> Seen;
6765
6766 // Add Expr to the worklist, if Expr is either an N-ary expression or a
6767 // SCEVUnknown PHI node.
6768 auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
6769 if (!Seen.insert(Expr).second)
6770 return;
6771 if (Cache.contains(Expr))
6772 return;
6773 switch (Expr->getSCEVType()) {
6774 case scUnknown:
6776 break;
6777 [[fallthrough]];
6778 case scConstant:
6779 case scVScale:
6780 case scTruncate:
6781 case scZeroExtend:
6782 case scSignExtend:
6783 case scPtrToAddr:
6784 case scPtrToInt:
6785 case scAddExpr:
6786 case scMulExpr:
6787 case scUDivExpr:
6788 case scAddRecExpr:
6789 case scUMaxExpr:
6790 case scSMaxExpr:
6791 case scUMinExpr:
6792 case scSMinExpr:
6794 WorkList.push_back(Expr);
6795 break;
6796 case scCouldNotCompute:
6797 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
6798 }
6799 };
6800 AddToWorklist(S);
6801
6802 // Build worklist by queuing operands of N-ary expressions and phi nodes.
6803 for (unsigned I = 0; I != WorkList.size(); ++I) {
6804 const SCEV *P = WorkList[I];
6805 auto *UnknownS = dyn_cast<SCEVUnknown>(P);
6806 // If it is not a `SCEVUnknown`, just recurse into operands.
6807 if (!UnknownS) {
6808 for (const SCEV *Op : P->operands())
6809 AddToWorklist(Op);
6810 continue;
6811 }
6812 // `SCEVUnknown`'s require special treatment.
6813 if (PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
6814 if (!RangeRefPHIAllowedOperands(DT, P))
6815 continue;
6816 for (auto &Op : reverse(P->operands()))
6817 AddToWorklist(getSCEV(Op));
6818 }
6819 }
6820
6821 if (!WorkList.empty()) {
6822 // Use getRangeRef to compute ranges for items in the worklist in reverse
6823 // order. This will force ranges for earlier operands to be computed before
6824 // their users in most cases.
6825 for (const SCEV *P : reverse(drop_begin(WorkList))) {
6826 getRangeRef(P, SignHint);
6827 }
6828 }
6829
6830 return getRangeRef(S, SignHint, 0);
6831}
6832
6833/// Determine the range for a particular SCEV. If SignHint is
6834/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
6835/// with a "cleaner" unsigned (resp. signed) representation.
6836const ConstantRange &ScalarEvolution::getRangeRef(
6837 const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
6838 DenseMap<const SCEV *, ConstantRange> &Cache =
6839 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
6840 : SignedRanges;
6842 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
6844
6845 // See if we've computed this range already.
6846 auto I = Cache.find(S);
6847 if (I != Cache.end())
6848 return I->second;
6849
6850 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
6851 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
6852
6853 // Switch to iteratively computing the range for S, if it is part of a deeply
6854 // nested expression.
6856 return getRangeRefIter(S, SignHint);
6857
6858 unsigned BitWidth = getTypeSizeInBits(S->getType());
6859 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
6860 using OBO = OverflowingBinaryOperator;
6861
6862 // If the value has known zeros, the maximum value will have those known zeros
6863 // as well.
6864 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
6865 APInt Multiple = getNonZeroConstantMultiple(S);
6866 APInt Remainder = APInt::getMaxValue(BitWidth).urem(Multiple);
6867 if (!Remainder.isZero())
6868 ConservativeResult =
6869 ConstantRange(APInt::getMinValue(BitWidth),
6870 APInt::getMaxValue(BitWidth) - Remainder + 1);
6871 }
6872 else {
6873 uint32_t TZ = getMinTrailingZeros(S);
6874 if (TZ != 0) {
6875 ConservativeResult = ConstantRange(
6877 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
6878 }
6879 }
6880
6881 switch (S->getSCEVType()) {
6882 case scConstant:
6883 llvm_unreachable("Already handled above.");
6884 case scVScale:
6885 return setRange(S, SignHint, getVScaleRange(&F, BitWidth));
6886 case scTruncate: {
6887 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
6888 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
6889 return setRange(
6890 Trunc, SignHint,
6891 ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
6892 }
6893 case scZeroExtend: {
6894 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
6895 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
6896 return setRange(
6897 ZExt, SignHint,
6898 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
6899 }
6900 case scSignExtend: {
6901 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
6902 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
6903 return setRange(
6904 SExt, SignHint,
6905 ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
6906 }
6907 case scPtrToAddr:
6908 case scPtrToInt: {
6909 const SCEVCastExpr *Cast = cast<SCEVCastExpr>(S);
6910 ConstantRange X = getRangeRef(Cast->getOperand(), SignHint, Depth + 1);
6911 return setRange(Cast, SignHint, X);
6912 }
6913 case scAddExpr: {
6914 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
6915 // Check if this is a URem pattern: A - (A / B) * B, which is always < B.
6916 const SCEV *URemLHS = nullptr, *URemRHS = nullptr;
6917 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED &&
6918 match(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), *this))) {
6919 ConstantRange LHSRange = getRangeRef(URemLHS, SignHint, Depth + 1);
6920 ConstantRange RHSRange = getRangeRef(URemRHS, SignHint, Depth + 1);
6921 ConservativeResult =
6922 ConservativeResult.intersectWith(LHSRange.urem(RHSRange), RangeType);
6923 }
6924 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
6925 unsigned WrapType = OBO::AnyWrap;
6926 if (Add->hasNoSignedWrap())
6927 WrapType |= OBO::NoSignedWrap;
6928 if (Add->hasNoUnsignedWrap())
6929 WrapType |= OBO::NoUnsignedWrap;
6930 for (const SCEV *Op : drop_begin(Add->operands()))
6931 X = X.addWithNoWrap(getRangeRef(Op, SignHint, Depth + 1), WrapType,
6932 RangeType);
6933 return setRange(Add, SignHint,
6934 ConservativeResult.intersectWith(X, RangeType));
6935 }
6936 case scMulExpr: {
6937 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
6938 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
6939 for (const SCEV *Op : drop_begin(Mul->operands()))
6940 X = X.multiply(getRangeRef(Op, SignHint, Depth + 1));
6941 return setRange(Mul, SignHint,
6942 ConservativeResult.intersectWith(X, RangeType));
6943 }
6944 case scUDivExpr: {
6945 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
6946 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
6947 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
6948 return setRange(UDiv, SignHint,
6949 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
6950 }
6951 case scAddRecExpr: {
6952 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
6953 // If there's no unsigned wrap, the value will never be less than its
6954 // initial value.
6955 if (AddRec->hasNoUnsignedWrap()) {
6956 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
6957 if (!UnsignedMinValue.isZero())
6958 ConservativeResult = ConservativeResult.intersectWith(
6959 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
6960 }
6961
6962 // If there's no signed wrap, and all the operands except initial value have
6963 // the same sign or zero, the value won't ever be:
6964 // 1: smaller than initial value if operands are non negative,
6965 // 2: bigger than initial value if operands are non positive.
6966 // For both cases, value can not cross signed min/max boundary.
6967 if (AddRec->hasNoSignedWrap()) {
6968 bool AllNonNeg = true;
6969 bool AllNonPos = true;
6970 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
6971 if (!isKnownNonNegative(AddRec->getOperand(i)))
6972 AllNonNeg = false;
6973 if (!isKnownNonPositive(AddRec->getOperand(i)))
6974 AllNonPos = false;
6975 }
6976 if (AllNonNeg)
6977 ConservativeResult = ConservativeResult.intersectWith(
6980 RangeType);
6981 else if (AllNonPos)
6982 ConservativeResult = ConservativeResult.intersectWith(
6984 getSignedRangeMax(AddRec->getStart()) +
6985 1),
6986 RangeType);
6987 }
6988
6989 // TODO: non-affine addrec
6990 if (AddRec->isAffine()) {
6991 const SCEV *MaxBEScev =
6993 if (!isa<SCEVCouldNotCompute>(MaxBEScev)) {
6994 APInt MaxBECount = cast<SCEVConstant>(MaxBEScev)->getAPInt();
6995
6996 // Adjust MaxBECount to the same bitwidth as AddRec. We can truncate if
6997 // MaxBECount's active bits are all <= AddRec's bit width.
6998 if (MaxBECount.getBitWidth() > BitWidth &&
6999 MaxBECount.getActiveBits() <= BitWidth)
7000 MaxBECount = MaxBECount.trunc(BitWidth);
7001 else if (MaxBECount.getBitWidth() < BitWidth)
7002 MaxBECount = MaxBECount.zext(BitWidth);
7003
7004 if (MaxBECount.getBitWidth() == BitWidth) {
7005 auto [RangeFromAffine, Flags] = getRangeForAffineAR(
7006 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7007 ConservativeResult =
7008 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
7009 const_cast<SCEVAddRecExpr *>(AddRec)->setNoWrapFlags(Flags);
7010
7011 auto RangeFromFactoring = getRangeViaFactoring(
7012 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount);
7013 ConservativeResult =
7014 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
7015 }
7016 }
7017
7018 // Now try symbolic BE count and more powerful methods.
7020 const SCEV *SymbolicMaxBECount =
7022 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
7023 getTypeSizeInBits(MaxBEScev->getType()) <= BitWidth &&
7024 AddRec->hasNoSelfWrap()) {
7025 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
7026 AddRec, SymbolicMaxBECount, BitWidth, SignHint);
7027 ConservativeResult =
7028 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
7029 }
7030 }
7031 }
7032
7033 return setRange(AddRec, SignHint, std::move(ConservativeResult));
7034 }
7035 case scUMaxExpr:
7036 case scSMaxExpr:
7037 case scUMinExpr:
7038 case scSMinExpr:
7039 case scSequentialUMinExpr: {
7041 switch (S->getSCEVType()) {
7042 case scUMaxExpr:
7043 ID = Intrinsic::umax;
7044 break;
7045 case scSMaxExpr:
7046 ID = Intrinsic::smax;
7047 break;
7048 case scUMinExpr:
7050 ID = Intrinsic::umin;
7051 break;
7052 case scSMinExpr:
7053 ID = Intrinsic::smin;
7054 break;
7055 default:
7056 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
7057 }
7058
7059 const auto *NAry = cast<SCEVNAryExpr>(S);
7060 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
7061 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
7062 X = X.intrinsic(
7063 ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
7064 return setRange(S, SignHint,
7065 ConservativeResult.intersectWith(X, RangeType));
7066 }
7067 case scUnknown: {
7068 const SCEVUnknown *U = cast<SCEVUnknown>(S);
7069 Value *V = U->getValue();
7070
7071 // Check if the IR explicitly contains !range metadata.
7072 std::optional<ConstantRange> MDRange = GetRangeFromMetadata(V);
7073 if (MDRange)
7074 ConservativeResult =
7075 ConservativeResult.intersectWith(*MDRange, RangeType);
7076
7077 // Use facts about recurrences in the underlying IR. Note that add
7078 // recurrences are AddRecExprs and thus don't hit this path. This
7079 // primarily handles shift recurrences.
7080 auto CR = getRangeForUnknownRecurrence(U);
7081 ConservativeResult = ConservativeResult.intersectWith(CR);
7082
7083 // See if ValueTracking can give us a useful range.
7084 const DataLayout &DL = getDataLayout();
7085 KnownBits Known = computeKnownBits(V, DL, &AC, nullptr, &DT);
7086 if (Known.getBitWidth() != BitWidth)
7087 Known = Known.zextOrTrunc(BitWidth);
7088
7089 // ValueTracking may be able to compute a tighter result for the number of
7090 // sign bits than for the value of those sign bits.
7091 unsigned NS = ComputeNumSignBits(V, DL, &AC, nullptr, &DT);
7092 if (U->getType()->isPointerTy()) {
7093 // If the pointer size is larger than the index size type, this can cause
7094 // NS to be larger than BitWidth. So compensate for this.
7095 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
7096 int ptrIdxDiff = ptrSize - BitWidth;
7097 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
7098 NS -= ptrIdxDiff;
7099 }
7100
7101 if (NS > 1) {
7102 // If we know any of the sign bits, we know all of the sign bits.
7103 if (!Known.Zero.getHiBits(NS).isZero())
7104 Known.Zero.setHighBits(NS);
7105 if (!Known.One.getHiBits(NS).isZero())
7106 Known.One.setHighBits(NS);
7107 }
7108
7109 if (Known.getMinValue() != Known.getMaxValue() + 1)
7110 ConservativeResult = ConservativeResult.intersectWith(
7111 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
7112 RangeType);
7113 if (NS > 1)
7114 ConservativeResult = ConservativeResult.intersectWith(
7115 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
7116 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
7117 RangeType);
7118
7119 if (U->getType()->isPointerTy() && SignHint == HINT_RANGE_UNSIGNED) {
7120 // Strengthen the range if the underlying IR value is a
7121 // global/alloca/heap allocation using the size of the object.
7122 bool CanBeNull;
7123 uint64_t DerefBytes = V->getPointerDereferenceableBytes(
7124 DL, CanBeNull, /*CanBeFreed=*/nullptr);
7125 if (DerefBytes > 1 && isUIntN(BitWidth, DerefBytes)) {
7126 // The highest address the object can start is DerefBytes bytes before
7127 // the end (unsigned max value). If this value is not a multiple of the
7128 // alignment, the last possible start value is the next lowest multiple
7129 // of the alignment. Note: The computations below cannot overflow,
7130 // because if they would there's no possible start address for the
7131 // object.
7132 APInt MaxVal =
7133 APInt::getMaxValue(BitWidth) - APInt(BitWidth, DerefBytes);
7134 uint64_t Align = U->getValue()->getPointerAlignment(DL).value();
7135 uint64_t Rem = MaxVal.urem(Align);
7136 MaxVal -= APInt(BitWidth, Rem);
7137 APInt MinVal = APInt::getZero(BitWidth);
7138 if (llvm::isKnownNonZero(V, DL))
7139 MinVal = Align;
7140 ConservativeResult = ConservativeResult.intersectWith(
7141 ConstantRange::getNonEmpty(MinVal, MaxVal + 1), RangeType);
7142 }
7143 }
7144
7145 // A range of Phi is a subset of union of all ranges of its input.
7146 if (PHINode *Phi = dyn_cast<PHINode>(V)) {
7147 // SCEVExpander sometimes creates SCEVUnknowns that are secretly
7148 // AddRecs; return the range for the corresponding AddRec.
7149 if (auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V)))
7150 return getRangeRef(AR, SignHint, Depth + 1);
7151
7152 // Make sure that we do not run over cycled Phis.
7153 if (RangeRefPHIAllowedOperands(DT, Phi)) {
7154 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
7155
7156 for (const auto &Op : Phi->operands()) {
7157 auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
7158 RangeFromOps = RangeFromOps.unionWith(OpRange);
7159 // No point to continue if we already have a full set.
7160 if (RangeFromOps.isFullSet())
7161 break;
7162 }
7163 ConservativeResult =
7164 ConservativeResult.intersectWith(RangeFromOps, RangeType);
7165 }
7166 }
7167
7168 // vscale can't be equal to zero
7169 if (const auto *II = dyn_cast<IntrinsicInst>(V))
7170 if (II->getIntrinsicID() == Intrinsic::vscale) {
7171 ConstantRange Disallowed = APInt::getZero(BitWidth);
7172 ConservativeResult = ConservativeResult.difference(Disallowed);
7173 }
7174
7175 return setRange(U, SignHint, std::move(ConservativeResult));
7176 }
7177 case scCouldNotCompute:
7178 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
7179 }
7180
7181 return setRange(S, SignHint, std::move(ConservativeResult));
7182}
7183
7184// Given a StartRange, Step and MaxBECount for an expression compute a range of
7185// values that the expression can take. Initially, the expression has a value
7186// from StartRange and then is changed by Step up to MaxBECount times. Signed
7187// argument defines if we treat Step as signed or unsigned. The second return
7188// value indicates that no wrapping occurred.
7189static std::pair<ConstantRange, bool>
7191 const APInt &MaxBECount, bool Signed) {
7192 unsigned BitWidth = Step.getBitWidth();
7193 assert(BitWidth == StartRange.getBitWidth() &&
7194 BitWidth == MaxBECount.getBitWidth() && "mismatched bit widths");
7195 // If either Step or MaxBECount is 0, then the expression won't change, and we
7196 // just need to return the initial range.
7197 if (Step == 0 || MaxBECount == 0)
7198 return {StartRange, true};
7199
7200 // If we don't know anything about the initial value (i.e. StartRange is
7201 // FullRange), then we don't know anything about the final range either.
7202 // Return FullRange.
7203 if (StartRange.isFullSet())
7204 return {ConstantRange::getFull(BitWidth), false};
7205
7206 // If Step is signed and negative, then we use its absolute value, but we also
7207 // note that we're moving in the opposite direction.
7208 bool Descending = Signed && Step.isNegative();
7209
7210 if (Signed)
7211 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
7212 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
7213 // This equations hold true due to the well-defined wrap-around behavior of
7214 // APInt.
7215 Step = Step.abs();
7216
7217 // Check if Offset is more than full span of BitWidth. If it is, the
7218 // expression is guaranteed to overflow.
7219 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
7220 return {ConstantRange::getFull(BitWidth), false};
7221
7222 // Offset is by how much the expression can change. Checks above guarantee no
7223 // overflow here.
7224 APInt Offset = Step * MaxBECount;
7225
7226 // Minimum value of the final range will match the minimal value of StartRange
7227 // if the expression is increasing and will be decreased by Offset otherwise.
7228 // Maximum value of the final range will match the maximal value of StartRange
7229 // if the expression is decreasing and will be increased by Offset otherwise.
7230 APInt StartLower = StartRange.getLower();
7231 APInt StartUpper = StartRange.getUpper() - 1;
7232 bool Overflow;
7233 APInt MovedBoundary;
7234 if (Signed) {
7235 // This does not use sadd_ov, as we want to check overflow for a signed
7236 // start with an unsigned offset.
7237 if (Descending) {
7238 MovedBoundary = StartLower - std::move(Offset);
7239 Overflow = MovedBoundary.sgt(StartLower) || StartRange.isSignWrappedSet();
7240 } else {
7241 MovedBoundary = StartUpper + std::move(Offset);
7242 Overflow = MovedBoundary.slt(StartUpper) || StartRange.isSignWrappedSet();
7243 }
7244 } else {
7245 MovedBoundary = StartUpper.uadd_ov(std::move(Offset), Overflow);
7246 Overflow |= StartRange.isWrappedSet();
7247 }
7248
7249 // It's possible that the new minimum/maximum value will fall into the initial
7250 // range (due to wrap around). This means that the expression can take any
7251 // value in this bitwidth, and we have to return full range.
7252 if (StartRange.contains(MovedBoundary))
7253 return {ConstantRange::getFull(BitWidth), false};
7254
7255 APInt NewLower =
7256 Descending ? std::move(MovedBoundary) : std::move(StartLower);
7257 APInt NewUpper =
7258 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
7259 NewUpper += 1;
7260
7261 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
7262 return {ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)),
7263 !Overflow};
7264}
7265
7266std::pair<ConstantRange, SCEV::NoWrapFlags>
7267ScalarEvolution::getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
7268 const APInt &MaxBECount) {
7269 assert(getTypeSizeInBits(Start->getType()) ==
7270 getTypeSizeInBits(Step->getType()) &&
7271 getTypeSizeInBits(Start->getType()) == MaxBECount.getBitWidth() &&
7272 "mismatched bit widths");
7273
7274 // First, consider step signed.
7275 ConstantRange StartSRange = getSignedRange(Start);
7276 ConstantRange StepSRange = getSignedRange(Step);
7277
7278 // If Step can be both positive and negative, we need to find ranges for the
7279 // maximum absolute step values in both directions and union them.
7280 auto [SR1, NSW1] = getRangeForAffineARHelper(
7281 StepSRange.getSignedMin(), StartSRange, MaxBECount, /*Signed=*/true);
7282 auto [SR2, NSW2] = getRangeForAffineARHelper(StepSRange.getSignedMax(),
7283 StartSRange, MaxBECount,
7284 /*Signed=*/true);
7285 ConstantRange SR = SR1.unionWith(SR2);
7286
7287 // Next, consider step unsigned.
7288 auto [UR, NUW] = getRangeForAffineARHelper(
7289 getUnsignedRangeMax(Step), getUnsignedRange(Start), MaxBECount,
7290 /*Signed=*/false);
7291
7293 if (NUW)
7295 if (NSW1 && NSW2)
7297
7298 // Finally, intersect signed and unsigned ranges.
7300}
7301
7302ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
7303 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
7304 ScalarEvolution::RangeSignHint SignHint) {
7305 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
7306 assert(AddRec->hasNoSelfWrap() &&
7307 "This only works for non-self-wrapping AddRecs!");
7308 const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
7309 const SCEV *Step = AddRec->getStepRecurrence(*this);
7310 // Only deal with constant step to save compile time.
7311 if (!isa<SCEVConstant>(Step))
7312 return ConstantRange::getFull(BitWidth);
7313 // Let's make sure that we can prove that we do not self-wrap during
7314 // MaxBECount iterations. We need this because MaxBECount is a maximum
7315 // iteration count estimate, and we might infer nw from some exit for which we
7316 // do not know max exit count (or any other side reasoning).
7317 // TODO: Turn into assert at some point.
7318 if (getTypeSizeInBits(MaxBECount->getType()) >
7319 getTypeSizeInBits(AddRec->getType()))
7320 return ConstantRange::getFull(BitWidth);
7321 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
7322 const SCEV *RangeWidth = getMinusOne(AddRec->getType());
7323 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
7324 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
7325 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
7326 MaxItersWithoutWrap))
7327 return ConstantRange::getFull(BitWidth);
7328
7329 ICmpInst::Predicate LEPred =
7331 ICmpInst::Predicate GEPred =
7333 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
7334
7335 // We know that there is no self-wrap. Let's take Start and End values and
7336 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
7337 // the iteration. They either lie inside the range [Min(Start, End),
7338 // Max(Start, End)] or outside it:
7339 //
7340 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
7341 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
7342 //
7343 // No self wrap flag guarantees that the intermediate values cannot be BOTH
7344 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
7345 // knowledge, let's try to prove that we are dealing with Case 1. It is so if
7346 // Start <= End and step is positive, or Start >= End and step is negative.
7347 const SCEV *Start = applyLoopGuards(AddRec->getStart(), AddRec->getLoop());
7348 ConstantRange StartRange = getRangeRef(Start, SignHint);
7349 ConstantRange EndRange = getRangeRef(End, SignHint);
7350 ConstantRange RangeBetween = StartRange.unionWith(EndRange);
7351 // If they already cover full iteration space, we will know nothing useful
7352 // even if we prove what we want to prove.
7353 if (RangeBetween.isFullSet())
7354 return RangeBetween;
7355 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
7356 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
7357 : RangeBetween.isWrappedSet();
7358 if (IsWrappedSet)
7359 return ConstantRange::getFull(BitWidth);
7360
7361 if (isKnownPositive(Step) &&
7362 isKnownPredicateViaConstantRanges(LEPred, Start, End))
7363 return RangeBetween;
7364 if (isKnownNegative(Step) &&
7365 isKnownPredicateViaConstantRanges(GEPred, Start, End))
7366 return RangeBetween;
7367 return ConstantRange::getFull(BitWidth);
7368}
7369
7370ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
7371 const SCEV *Step,
7372 const APInt &MaxBECount) {
7373 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
7374 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
7375
7376 unsigned BitWidth = MaxBECount.getBitWidth();
7377 assert(getTypeSizeInBits(Start->getType()) == BitWidth &&
7378 getTypeSizeInBits(Step->getType()) == BitWidth &&
7379 "mismatched bit widths");
7380
7381 struct SelectPattern {
7382 Value *Condition = nullptr;
7383 APInt TrueValue;
7384 APInt FalseValue;
7385
7386 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
7387 const SCEV *S) {
7388 std::optional<unsigned> CastOp;
7389 APInt Offset(BitWidth, 0);
7390
7392 "Should be!");
7393
7394 // Peel off a constant offset. In the future we could consider being
7395 // smarter here and handle {Start+Step,+,Step} too.
7396 const APInt *Off;
7397 if (match(S, m_scev_Add(m_scev_APInt(Off), m_SCEV(S))))
7398 Offset = *Off;
7399
7400 // Peel off a cast operation
7401 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
7402 CastOp = SCast->getSCEVType();
7403 S = SCast->getOperand();
7404 }
7405
7406 using namespace llvm::PatternMatch;
7407
7408 auto *SU = dyn_cast<SCEVUnknown>(S);
7409 const APInt *TrueVal, *FalseVal;
7410 if (!SU ||
7411 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
7412 m_APInt(FalseVal)))) {
7413 Condition = nullptr;
7414 return;
7415 }
7416
7417 TrueValue = *TrueVal;
7418 FalseValue = *FalseVal;
7419
7420 // Re-apply the cast we peeled off earlier
7421 if (CastOp)
7422 switch (*CastOp) {
7423 default:
7424 llvm_unreachable("Unknown SCEV cast type!");
7425
7426 case scTruncate:
7427 TrueValue = TrueValue.trunc(BitWidth);
7428 FalseValue = FalseValue.trunc(BitWidth);
7429 break;
7430 case scZeroExtend:
7431 TrueValue = TrueValue.zext(BitWidth);
7432 FalseValue = FalseValue.zext(BitWidth);
7433 break;
7434 case scSignExtend:
7435 TrueValue = TrueValue.sext(BitWidth);
7436 FalseValue = FalseValue.sext(BitWidth);
7437 break;
7438 }
7439
7440 // Re-apply the constant offset we peeled off earlier
7441 TrueValue += Offset;
7442 FalseValue += Offset;
7443 }
7444
7445 bool isRecognized() { return Condition != nullptr; }
7446 };
7447
7448 SelectPattern StartPattern(*this, BitWidth, Start);
7449 if (!StartPattern.isRecognized())
7450 return ConstantRange::getFull(BitWidth);
7451
7452 SelectPattern StepPattern(*this, BitWidth, Step);
7453 if (!StepPattern.isRecognized())
7454 return ConstantRange::getFull(BitWidth);
7455
7456 if (StartPattern.Condition != StepPattern.Condition) {
7457 // We don't handle this case today; but we could, by considering four
7458 // possibilities below instead of two. I'm not sure if there are cases where
7459 // that will help over what getRange already does, though.
7460 return ConstantRange::getFull(BitWidth);
7461 }
7462
7463 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
7464 // construct arbitrary general SCEV expressions here. This function is called
7465 // from deep in the call stack, and calling getSCEV (on a sext instruction,
7466 // say) can end up caching a suboptimal value.
7467
7468 // FIXME: without the explicit `this` receiver below, MSVC errors out with
7469 // C2352 and C2512 (otherwise it isn't needed).
7470
7471 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
7472 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
7473 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
7474 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
7475
7476 ConstantRange TrueRange =
7477 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount).first;
7478 ConstantRange FalseRange =
7479 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount).first;
7480
7481 return TrueRange.unionWith(FalseRange);
7482}
7483
7484SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
7485 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
7486 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
7487
7488 // Return early if there are no flags to propagate to the SCEV.
7490 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(BinOp);
7491 PDI && PDI->isDisjoint()) {
7493 } else {
7494 if (BinOp->hasNoUnsignedWrap())
7496 if (BinOp->hasNoSignedWrap())
7498 }
7499 if (Flags == SCEV::FlagAnyWrap)
7500 return SCEV::FlagAnyWrap;
7501
7502 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
7503}
7504
7505const Instruction *
7506ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
7507 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
7508 return &*AddRec->getLoop()->getHeader()->begin();
7509 if (auto *U = dyn_cast<SCEVUnknown>(S))
7510 if (auto *I = dyn_cast<Instruction>(U->getValue()))
7511 return I;
7512 return nullptr;
7513}
7514
7515const Instruction *ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
7516 bool &Precise) {
7517 Precise = true;
7518 // Do a bounded search of the def relation of the requested SCEVs.
7519 SmallPtrSet<const SCEV *, 16> Visited;
7520 SmallVector<SCEVUse> Worklist;
7521 auto pushOp = [&](const SCEV *S) {
7522 if (!Visited.insert(S).second)
7523 return;
7524 // Threshold of 30 here is arbitrary.
7525 if (Visited.size() > 30) {
7526 Precise = false;
7527 return;
7528 }
7529 Worklist.push_back(S);
7530 };
7531
7532 for (SCEVUse S : Ops)
7533 pushOp(S);
7534
7535 const Instruction *Bound = nullptr;
7536 while (!Worklist.empty()) {
7537 SCEVUse S = Worklist.pop_back_val();
7538 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
7539 if (!Bound || DT.dominates(Bound, DefI))
7540 Bound = DefI;
7541 } else {
7542 for (SCEVUse Op : S->operands())
7543 pushOp(Op);
7544 }
7545 }
7546 return Bound ? Bound : &*F.getEntryBlock().begin();
7547}
7548
7549const Instruction *
7550ScalarEvolution::getDefiningScopeBound(ArrayRef<SCEVUse> Ops) {
7551 bool Discard;
7552 return getDefiningScopeBound(Ops, Discard);
7553}
7554
7555bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
7556 const Instruction *B) {
7557 if (A->getParent() == B->getParent() &&
7559 B->getIterator()))
7560 return true;
7561
7562 auto *BLoop = LI.getLoopFor(B->getParent());
7563 if (BLoop && BLoop->getHeader() == B->getParent() &&
7564 BLoop->getLoopPreheader() == A->getParent() &&
7566 A->getParent()->end()) &&
7567 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
7568 B->getIterator()))
7569 return true;
7570 return false;
7571}
7572
7574 SCEVPoisonCollector PC(/* LookThroughMaybePoisonBlocking */ true);
7575 visitAll(Op, PC);
7576 return PC.MaybePoison.empty();
7577}
7578
7579bool ScalarEvolution::isGuaranteedNotToCauseUB(const SCEV *Op) {
7580 return !SCEVExprContains(Op, [this](const SCEV *S) {
7581 const SCEV *Op1;
7582 bool M = match(S, m_scev_UDiv(m_SCEV(), m_SCEV(Op1)));
7583 // The UDiv may be UB if the divisor is poison or zero. Unless the divisor
7584 // is a non-zero constant, we have to assume the UDiv may be UB.
7585 return M && (!isKnownNonZero(Op1) || !isGuaranteedNotToBePoison(Op1));
7586 });
7587}
7588
7589bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
7590 // Only proceed if we can prove that I does not yield poison.
7592 return false;
7593
7594 // At this point we know that if I is executed, then it does not wrap
7595 // according to at least one of NSW or NUW. If I is not executed, then we do
7596 // not know if the calculation that I represents would wrap. Multiple
7597 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
7598 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
7599 // derived from other instructions that map to the same SCEV. We cannot make
7600 // that guarantee for cases where I is not executed. So we need to find a
7601 // upper bound on the defining scope for the SCEV, and prove that I is
7602 // executed every time we enter that scope. When the bounding scope is a
7603 // loop (the common case), this is equivalent to proving I executes on every
7604 // iteration of that loop.
7605 SmallVector<SCEVUse> SCEVOps;
7606 for (const Use &Op : I->operands()) {
7607 // I could be an extractvalue from a call to an overflow intrinsic.
7608 // TODO: We can do better here in some cases.
7609 if (isSCEVable(Op->getType()))
7610 SCEVOps.push_back(getSCEV(Op));
7611 }
7612 auto *DefI = getDefiningScopeBound(SCEVOps);
7613 return isGuaranteedToTransferExecutionTo(DefI, I);
7614}
7615
7616bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
7617 // If we know that \c I can never be poison period, then that's enough.
7618 if (isSCEVExprNeverPoison(I))
7619 return true;
7620
7621 // If the loop only has one exit, then we know that, if the loop is entered,
7622 // any instruction dominating that exit will be executed. If any such
7623 // instruction would result in UB, the addrec cannot be poison.
7624 //
7625 // This is basically the same reasoning as in isSCEVExprNeverPoison(), but
7626 // also handles uses outside the loop header (they just need to dominate the
7627 // single exit).
7628
7629 auto *ExitingBB = L->getExitingBlock();
7630 if (!ExitingBB || !loopHasNoAbnormalExits(L))
7631 return false;
7632
7633 SmallPtrSet<const Value *, 16> KnownPoison;
7635
7636 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
7637 // things that are known to be poison under that assumption go on the
7638 // Worklist.
7639 KnownPoison.insert(I);
7640 Worklist.push_back(I);
7641
7642 while (!Worklist.empty()) {
7643 const Instruction *Poison = Worklist.pop_back_val();
7644
7645 for (const Use &U : Poison->uses()) {
7646 const Instruction *PoisonUser = cast<Instruction>(U.getUser());
7647 if (mustTriggerUB(PoisonUser, KnownPoison) &&
7648 DT.dominates(PoisonUser->getParent(), ExitingBB))
7649 return true;
7650
7651 if (propagatesPoison(U) && L->contains(PoisonUser))
7652 if (KnownPoison.insert(PoisonUser).second)
7653 Worklist.push_back(PoisonUser);
7654 }
7655 }
7656
7657 return false;
7658}
7659
7660ScalarEvolution::LoopProperties
7661ScalarEvolution::getLoopProperties(const Loop *L) {
7662 using LoopProperties = ScalarEvolution::LoopProperties;
7663
7664 auto Itr = LoopPropertiesCache.find(L);
7665 if (Itr == LoopPropertiesCache.end()) {
7666 auto HasSideEffects = [](Instruction *I) {
7667 if (auto *SI = dyn_cast<StoreInst>(I))
7668 return !SI->isSimple();
7669
7670 if (I->mayThrow())
7671 return true;
7672
7673 // Non-volatile memset / memcpy do not count as side-effect for forward
7674 // progress.
7675 if (isa<MemIntrinsic>(I) && !I->isVolatile())
7676 return false;
7677
7678 return I->mayWriteToMemory();
7679 };
7680
7681 LoopProperties LP = {/* HasNoAbnormalExits */ true,
7682 /*HasNoSideEffects*/ true};
7683
7684 for (auto *BB : L->getBlocks())
7685 for (auto &I : *BB) {
7687 LP.HasNoAbnormalExits = false;
7688 if (HasSideEffects(&I))
7689 LP.HasNoSideEffects = false;
7690 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
7691 break; // We're already as pessimistic as we can get.
7692 }
7693
7694 auto InsertPair = LoopPropertiesCache.insert({L, LP});
7695 assert(InsertPair.second && "We just checked!");
7696 Itr = InsertPair.first;
7697 }
7698
7699 return Itr->second;
7700}
7701
7703 // A mustprogress loop without side effects must be finite.
7704 // TODO: The check used here is very conservative. It's only *specific*
7705 // side effects which are well defined in infinite loops.
7706 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
7707}
7708
7709const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
7710 // Worklist item with a Value and a bool indicating whether all operands have
7711 // been visited already.
7714
7715 Stack.emplace_back(V, false);
7716 while (!Stack.empty()) {
7717 auto E = Stack.back();
7718 Value *CurV = E.getPointer();
7719
7720 if (getExistingSCEV(CurV)) {
7721 Stack.pop_back();
7722 continue;
7723 }
7724
7726 const SCEV *CreatedSCEV = nullptr;
7727 // If all operands have been visited already, create the SCEV.
7728 if (E.getInt()) {
7729 CreatedSCEV = createSCEV(CurV);
7730 } else {
7731 // Otherwise get the operands we need to create SCEV's for before creating
7732 // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
7733 // just use it.
7734 CreatedSCEV = getOperandsToCreate(CurV, Ops);
7735 }
7736
7737 if (CreatedSCEV) {
7738 insertValueToMap(CurV, CreatedSCEV);
7739 Stack.pop_back();
7740 } else {
7741 Stack.back().setInt(true);
7742 // Queue its operands which need to be constructed.
7743 for (Value *Op : Ops)
7744 Stack.emplace_back(Op, false);
7745 }
7746 }
7747
7748 return getExistingSCEV(V);
7749}
7750
7751const SCEV *
7752ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
7753 if (!isSCEVable(V->getType()))
7754 return getUnknown(V);
7755
7756 if (Instruction *I = dyn_cast<Instruction>(V)) {
7757 // Don't attempt to analyze instructions in blocks that aren't
7758 // reachable. Such instructions don't matter, and they aren't required
7759 // to obey basic rules for definitions dominating uses which this
7760 // analysis depends on.
7761 if (!DT.isReachableFromEntry(I->getParent()))
7762 return getUnknown(PoisonValue::get(V->getType()));
7763 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7764 return getConstant(CI);
7765 else if (isa<GlobalAlias>(V))
7766 return getUnknown(V);
7767 else if (!isa<ConstantExpr>(V))
7768 return getUnknown(V);
7769
7771 if (auto BO =
7773 bool IsConstArg = isa<ConstantInt>(BO->RHS);
7774 switch (BO->Opcode) {
7775 case Instruction::Add:
7776 case Instruction::Mul: {
7777 // For additions and multiplications, traverse add/mul chains for which we
7778 // can potentially create a single SCEV, to reduce the number of
7779 // get{Add,Mul}Expr calls.
7780 do {
7781 if (BO->Op) {
7782 if (BO->Op != V && getExistingSCEV(BO->Op)) {
7783 Ops.push_back(BO->Op);
7784 break;
7785 }
7786 }
7787 Ops.push_back(BO->RHS);
7788 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
7790 if (!NewBO ||
7791 (BO->Opcode == Instruction::Add &&
7792 (NewBO->Opcode != Instruction::Add &&
7793 NewBO->Opcode != Instruction::Sub)) ||
7794 (BO->Opcode == Instruction::Mul &&
7795 NewBO->Opcode != Instruction::Mul)) {
7796 Ops.push_back(BO->LHS);
7797 break;
7798 }
7799 // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
7800 // requires a SCEV for the LHS.
7801 if (BO->Op && (BO->IsNSW || BO->IsNUW)) {
7802 auto *I = dyn_cast<Instruction>(BO->Op);
7803 if (I && programUndefinedIfPoison(I)) {
7804 Ops.push_back(BO->LHS);
7805 break;
7806 }
7807 }
7808 BO = NewBO;
7809 } while (true);
7810 return nullptr;
7811 }
7812 case Instruction::Sub:
7813 case Instruction::UDiv:
7814 case Instruction::URem:
7815 break;
7816 case Instruction::AShr:
7817 case Instruction::Shl:
7818 case Instruction::Xor:
7819 if (!IsConstArg)
7820 return nullptr;
7821 break;
7822 case Instruction::And:
7823 case Instruction::Or:
7824 if (!IsConstArg && !BO->LHS->getType()->isIntegerTy(1))
7825 return nullptr;
7826 break;
7827 case Instruction::LShr:
7828 return getUnknown(V);
7829 default:
7830 llvm_unreachable("Unhandled binop");
7831 break;
7832 }
7833
7834 Ops.push_back(BO->LHS);
7835 Ops.push_back(BO->RHS);
7836 return nullptr;
7837 }
7838
7839 switch (U->getOpcode()) {
7840 case Instruction::Trunc:
7841 case Instruction::ZExt:
7842 case Instruction::SExt:
7843 case Instruction::PtrToAddr:
7844 case Instruction::PtrToInt:
7845 Ops.push_back(U->getOperand(0));
7846 return nullptr;
7847
7848 case Instruction::BitCast:
7849 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
7850 Ops.push_back(U->getOperand(0));
7851 return nullptr;
7852 }
7853 return getUnknown(V);
7854
7855 case Instruction::SDiv:
7856 case Instruction::SRem:
7857 Ops.push_back(U->getOperand(0));
7858 Ops.push_back(U->getOperand(1));
7859 return nullptr;
7860
7861 case Instruction::GetElementPtr:
7862 assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
7863 "GEP source element type must be sized");
7864 llvm::append_range(Ops, U->operands());
7865 return nullptr;
7866
7867 case Instruction::IntToPtr:
7868 return getUnknown(V);
7869
7870 case Instruction::PHI:
7871 // getNodeForPHI has four ways to turn a PHI into a SCEV; retrieve the
7872 // relevant nodes for each of them.
7873 //
7874 // The first is just to call simplifyInstruction, and get something back
7875 // that isn't a PHI.
7876 if (Value *V = simplifyInstruction(
7877 cast<PHINode>(U),
7878 {getDataLayout(), &TLI, &DT, &AC, /*CtxI=*/nullptr,
7879 /*UseInstrInfo=*/true, /*CanUseUndef=*/false})) {
7880 assert(V);
7881 Ops.push_back(V);
7882 return nullptr;
7883 }
7884 // The second is createNodeForPHIWithIdenticalOperands: this looks for
7885 // operands which all perform the same operation, but haven't been
7886 // CSE'ed for whatever reason.
7887 if (BinaryOperator *BO = getCommonInstForPHI(cast<PHINode>(U))) {
7888 assert(BO);
7889 Ops.push_back(BO);
7890 return nullptr;
7891 }
7892 // The third is createNodeFromSelectLikePHI; this takes a PHI which
7893 // is equivalent to a select, and analyzes it like a select.
7894 {
7895 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
7897 assert(Cond);
7898 assert(LHS);
7899 assert(RHS);
7900 if (auto *CondICmp = dyn_cast<ICmpInst>(Cond)) {
7901 Ops.push_back(CondICmp->getOperand(0));
7902 Ops.push_back(CondICmp->getOperand(1));
7903 }
7904 Ops.push_back(Cond);
7905 Ops.push_back(LHS);
7906 Ops.push_back(RHS);
7907 return nullptr;
7908 }
7909 }
7910 // The fourth way is createAddRecFromPHI. It's complicated to handle here,
7911 // so just construct it recursively.
7912 //
7913 // In addition to getNodeForPHI, also construct nodes which might be needed
7914 // by getRangeRef.
7916 for (Value *V : cast<PHINode>(U)->operands())
7917 Ops.push_back(V);
7918 return nullptr;
7919 }
7920 return nullptr;
7921
7922 case Instruction::Select: {
7923 // Check if U is a select that can be simplified to a SCEVUnknown.
7924 auto CanSimplifyToUnknown = [this, U]() {
7925 if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
7926 return false;
7927
7928 auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
7929 if (!ICI)
7930 return false;
7931 Value *LHS = ICI->getOperand(0);
7932 Value *RHS = ICI->getOperand(1);
7933 if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
7934 ICI->getPredicate() == CmpInst::ICMP_NE) {
7936 return true;
7937 } else if (getTypeSizeInBits(LHS->getType()) >
7938 getTypeSizeInBits(U->getType()))
7939 return true;
7940 return false;
7941 };
7942 if (CanSimplifyToUnknown())
7943 return getUnknown(U);
7944
7945 llvm::append_range(Ops, U->operands());
7946 return nullptr;
7947 break;
7948 }
7949 case Instruction::Call:
7950 case Instruction::Invoke:
7951 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
7952 Ops.push_back(RV);
7953 return nullptr;
7954 }
7955
7956 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
7957 switch (II->getIntrinsicID()) {
7958 case Intrinsic::abs:
7959 Ops.push_back(II->getArgOperand(0));
7960 return nullptr;
7961 case Intrinsic::umax:
7962 case Intrinsic::umin:
7963 case Intrinsic::smax:
7964 case Intrinsic::smin:
7965 case Intrinsic::usub_sat:
7966 case Intrinsic::uadd_sat:
7967 Ops.push_back(II->getArgOperand(0));
7968 Ops.push_back(II->getArgOperand(1));
7969 return nullptr;
7970 case Intrinsic::start_loop_iterations:
7971 case Intrinsic::annotation:
7972 case Intrinsic::ptr_annotation:
7973 Ops.push_back(II->getArgOperand(0));
7974 return nullptr;
7975 default:
7976 break;
7977 }
7978 }
7979 break;
7980 }
7981
7982 return nullptr;
7983}
7984
7985const SCEV *ScalarEvolution::createSCEV(Value *V) {
7986 if (!isSCEVable(V->getType()))
7987 return getUnknown(V);
7988
7989 if (Instruction *I = dyn_cast<Instruction>(V)) {
7990 // Don't attempt to analyze instructions in blocks that aren't
7991 // reachable. Such instructions don't matter, and they aren't required
7992 // to obey basic rules for definitions dominating uses which this
7993 // analysis depends on.
7994 if (!DT.isReachableFromEntry(I->getParent()))
7995 return getUnknown(PoisonValue::get(V->getType()));
7996 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
7997 return getConstant(CI);
7998 else if (isa<GlobalAlias>(V))
7999 return getUnknown(V);
8000 else if (!isa<ConstantExpr>(V))
8001 return getUnknown(V);
8002
8003 const SCEV *LHS;
8004 const SCEV *RHS;
8005
8007 if (auto BO =
8009 switch (BO->Opcode) {
8010 case Instruction::Add: {
8011 // The simple thing to do would be to just call getSCEV on both operands
8012 // and call getAddExpr with the result. However if we're looking at a
8013 // bunch of things all added together, this can be quite inefficient,
8014 // because it leads to N-1 getAddExpr calls for N ultimate operands.
8015 // Instead, gather up all the operands and make a single getAddExpr call.
8016 // LLVM IR canonical form means we need only traverse the left operands.
8018 do {
8019 if (BO->Op) {
8020 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8021 AddOps.push_back(OpSCEV);
8022 break;
8023 }
8024
8025 // If a NUW or NSW flag can be applied to the SCEV for this
8026 // addition, then compute the SCEV for this addition by itself
8027 // with a separate call to getAddExpr. We need to do that
8028 // instead of pushing the operands of the addition onto AddOps,
8029 // since the flags are only known to apply to this particular
8030 // addition - they may not apply to other additions that can be
8031 // formed with operands from AddOps.
8032 const SCEV *RHS = getSCEV(BO->RHS);
8033 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8034 if (Flags != SCEV::FlagAnyWrap) {
8035 const SCEV *LHS = getSCEV(BO->LHS);
8036 if (BO->Opcode == Instruction::Sub)
8037 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
8038 else
8039 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
8040 break;
8041 }
8042 }
8043
8044 if (BO->Opcode == Instruction::Sub)
8045 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
8046 else
8047 AddOps.push_back(getSCEV(BO->RHS));
8048
8049 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8051 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
8052 NewBO->Opcode != Instruction::Sub)) {
8053 AddOps.push_back(getSCEV(BO->LHS));
8054 break;
8055 }
8056 BO = NewBO;
8057 } while (true);
8058
8059 return getAddExpr(AddOps);
8060 }
8061
8062 case Instruction::Mul: {
8064 do {
8065 if (BO->Op) {
8066 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
8067 MulOps.push_back(OpSCEV);
8068 break;
8069 }
8070
8071 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
8072 if (Flags != SCEV::FlagAnyWrap) {
8073 LHS = getSCEV(BO->LHS);
8074 RHS = getSCEV(BO->RHS);
8075 MulOps.push_back(getMulExpr(LHS, RHS, Flags));
8076 break;
8077 }
8078 }
8079
8080 MulOps.push_back(getSCEV(BO->RHS));
8081 auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
8083 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
8084 MulOps.push_back(getSCEV(BO->LHS));
8085 break;
8086 }
8087 BO = NewBO;
8088 } while (true);
8089
8090 return getMulExpr(MulOps);
8091 }
8092 case Instruction::UDiv:
8093 LHS = getSCEV(BO->LHS);
8094 RHS = getSCEV(BO->RHS);
8095 return getUDivExpr(LHS, RHS);
8096 case Instruction::URem:
8097 LHS = getSCEV(BO->LHS);
8098 RHS = getSCEV(BO->RHS);
8099 return getURemExpr(LHS, RHS);
8100 case Instruction::Sub: {
8102 if (BO->Op)
8103 Flags = getNoWrapFlagsFromUB(BO->Op);
8104
8105 // Try to use ptrtoaddr for subtracts with at least one ptrtoint
8106 // operand. While we don't model ptrtoint directly in SCEV, the
8107 // difference between two pointer addresses is well-defined.
8108 Value *PtrLHS = nullptr, *PtrRHS = nullptr;
8109 bool HasPtrLHS = match(BO->LHS, m_PtrToInt(m_Value(PtrLHS)));
8110 bool HasPtrRHS = match(BO->RHS, m_PtrToInt(m_Value(PtrRHS)));
8111 if (HasPtrLHS || HasPtrRHS) {
8112 // Convert a ptrtoint operand (OrigOp) to ptrtoaddr of its pointer
8113 // PtrOp. When only one side is ptrtoint (BothPtr is false), skip
8114 // SCEVUnknown pointers since wrapping them in ptrtoaddr adds no
8115 // useful structure.
8116 auto GetOp = [&](bool HasPtr, Value *PtrOp, Value *OrigOp,
8117 bool BothPtr) -> const SCEV * {
8118 if (!HasPtr)
8119 return getSCEV(OrigOp);
8120 const SCEV *PtrSCEV = getSCEV(PtrOp);
8121 if (BothPtr || !isa<SCEVUnknown>(PtrSCEV)) {
8122 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8123 if (!isa<SCEVCouldNotCompute>(Addr) &&
8124 getTypeSizeInBits(OrigOp->getType()) <=
8125 getTypeSizeInBits(Addr->getType()))
8126 return getTruncateOrNoop(Addr, OrigOp->getType());
8127 }
8128 return getSCEV(OrigOp);
8129 };
8130 const SCEV *L = GetOp(HasPtrLHS, PtrLHS, BO->LHS, HasPtrRHS);
8131 const SCEV *R = GetOp(HasPtrRHS, PtrRHS, BO->RHS, HasPtrLHS);
8132 return getMinusSCEV(L, R, Flags);
8133 }
8134
8135 LHS = getSCEV(BO->LHS);
8136 RHS = getSCEV(BO->RHS);
8137 return getMinusSCEV(LHS, RHS, Flags);
8138 }
8139 case Instruction::And:
8140 // For an expression like x&255 that merely masks off the high bits,
8141 // use zext(trunc(x)) as the SCEV expression.
8142 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8143 if (CI->isZero())
8144 return getSCEV(BO->RHS);
8145 if (CI->isMinusOne())
8146 return getSCEV(BO->LHS);
8147 const APInt &A = CI->getValue();
8148
8149 // Instcombine's ShrinkDemandedConstant may strip bits out of
8150 // constants, obscuring what would otherwise be a low-bits mask.
8151 // Use computeKnownBits to compute what ShrinkDemandedConstant
8152 // knew about to reconstruct a low-bits mask value.
8153 unsigned LZ = A.countl_zero();
8154 unsigned TZ = A.countr_zero();
8155 unsigned BitWidth = A.getBitWidth();
8156 KnownBits Known(BitWidth);
8157 computeKnownBits(BO->LHS, Known, getDataLayout(), &AC, nullptr, &DT);
8158
8159 APInt EffectiveMask =
8160 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
8161 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
8162 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
8163 const SCEV *LHS = getSCEV(BO->LHS);
8164 const SCEV *ShiftedLHS = nullptr;
8165 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
8166 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
8167 // For an expression like (x * 8) & 8, simplify the multiply.
8168 unsigned MulZeros = OpC->getAPInt().countr_zero();
8169 unsigned GCD = std::min(MulZeros, TZ);
8170 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
8172 MulOps.push_back(getConstant(OpC->getAPInt().ashr(GCD)));
8173 append_range(MulOps, LHSMul->operands().drop_front());
8174 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
8175 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
8176 }
8177 }
8178 if (!ShiftedLHS)
8179 ShiftedLHS = getUDivExpr(LHS, MulCount);
8180 return getMulExpr(
8182 getTruncateExpr(ShiftedLHS,
8183 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
8184 BO->LHS->getType()),
8185 MulCount);
8186 }
8187 }
8188 // Binary `and` is a bit-wise `umin`.
8189 if (BO->LHS->getType()->isIntegerTy(1)) {
8190 LHS = getSCEV(BO->LHS);
8191 RHS = getSCEV(BO->RHS);
8192 return getUMinExpr(LHS, RHS);
8193 }
8194 break;
8195
8196 case Instruction::Or:
8197 // Binary `or` is a bit-wise `umax`.
8198 if (BO->LHS->getType()->isIntegerTy(1)) {
8199 LHS = getSCEV(BO->LHS);
8200 RHS = getSCEV(BO->RHS);
8201 return getUMaxExpr(LHS, RHS);
8202 }
8203 break;
8204
8205 case Instruction::Xor:
8206 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
8207 // If the RHS of xor is -1, then this is a not operation.
8208 if (CI->isMinusOne())
8209 return getNotSCEV(getSCEV(BO->LHS));
8210
8211 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
8212 // This is a variant of the check for xor with -1, and it handles
8213 // the case where instcombine has trimmed non-demanded bits out
8214 // of an xor with -1.
8215 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
8216 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
8217 if (LBO->getOpcode() == Instruction::And &&
8218 LCI->getValue() == CI->getValue())
8219 if (const SCEVZeroExtendExpr *Z =
8221 Type *UTy = BO->LHS->getType();
8222 const SCEV *Z0 = Z->getOperand();
8223 Type *Z0Ty = Z0->getType();
8224 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
8225
8226 // If C is a low-bits mask, the zero extend is serving to
8227 // mask off the high bits. Complement the operand and
8228 // re-apply the zext.
8229 if (CI->getValue().isMask(Z0TySize))
8230 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
8231
8232 // If C is a single bit, it may be in the sign-bit position
8233 // before the zero-extend. In this case, represent the xor
8234 // using an add, which is equivalent, and re-apply the zext.
8235 APInt Trunc = CI->getValue().trunc(Z0TySize);
8236 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
8237 Trunc.isSignMask())
8238 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
8239 UTy);
8240 }
8241 }
8242 break;
8243
8244 case Instruction::Shl:
8245 // Turn shift left of a constant amount into a multiply.
8246 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
8247 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
8248
8249 // If the shift count is not less than the bitwidth, the result of
8250 // the shift is undefined. Don't try to analyze it, because the
8251 // resolution chosen here may differ from the resolution chosen in
8252 // other parts of the compiler.
8253 if (SA->getValue().uge(BitWidth))
8254 break;
8255
8256 // We can safely preserve the nuw flag in all cases. It's also safe to
8257 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
8258 // requires special handling. It can be preserved as long as we're not
8259 // left shifting by bitwidth - 1.
8260 auto Flags = SCEV::FlagAnyWrap;
8261 if (BO->Op) {
8262 auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
8263 if (any(MulFlags & SCEV::FlagNSW) &&
8264 (any(MulFlags & SCEV::FlagNUW) ||
8265 SA->getValue().ult(BitWidth - 1)))
8267 if (any(MulFlags & SCEV::FlagNUW))
8269 }
8270
8271 ConstantInt *X = ConstantInt::get(
8272 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
8273 return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
8274 }
8275 break;
8276
8277 case Instruction::AShr:
8278 // AShr X, C, where C is a constant.
8279 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
8280 if (!CI)
8281 break;
8282
8283 Type *OuterTy = BO->LHS->getType();
8284 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
8285 // If the shift count is not less than the bitwidth, the result of
8286 // the shift is undefined. Don't try to analyze it, because the
8287 // resolution chosen here may differ from the resolution chosen in
8288 // other parts of the compiler.
8289 if (CI->getValue().uge(BitWidth))
8290 break;
8291
8292 if (CI->isZero())
8293 return getSCEV(BO->LHS); // shift by zero --> noop
8294
8295 uint64_t AShrAmt = CI->getZExtValue();
8296 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
8297
8298 Operator *L = dyn_cast<Operator>(BO->LHS);
8299 const SCEV *AddTruncateExpr = nullptr;
8300 ConstantInt *ShlAmtCI = nullptr;
8301 const SCEV *AddConstant = nullptr;
8302
8303 if (L && L->getOpcode() == Instruction::Add) {
8304 // X = Shl A, n
8305 // Y = Add X, c
8306 // Z = AShr Y, m
8307 // n, c and m are constants.
8308
8309 Operator *LShift = dyn_cast<Operator>(L->getOperand(0));
8310 ConstantInt *AddOperandCI = dyn_cast<ConstantInt>(L->getOperand(1));
8311 if (LShift && LShift->getOpcode() == Instruction::Shl) {
8312 if (AddOperandCI) {
8313 const SCEV *ShlOp0SCEV = getSCEV(LShift->getOperand(0));
8314 ShlAmtCI = dyn_cast<ConstantInt>(LShift->getOperand(1));
8315 // since we truncate to TruncTy, the AddConstant should be of the
8316 // same type, so create a new Constant with type same as TruncTy.
8317 // Also, the Add constant should be shifted right by AShr amount.
8318 APInt AddOperand = AddOperandCI->getValue().ashr(AShrAmt);
8319 AddConstant = getConstant(AddOperand.trunc(BitWidth - AShrAmt));
8320 // we model the expression as sext(add(trunc(A), c << n)), since the
8321 // sext(trunc) part is already handled below, we create a
8322 // AddExpr(TruncExp) which will be used later.
8323 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8324 }
8325 }
8326 } else if (L && L->getOpcode() == Instruction::Shl) {
8327 // X = Shl A, n
8328 // Y = AShr X, m
8329 // Both n and m are constant.
8330
8331 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
8332 ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
8333 AddTruncateExpr = getTruncateExpr(ShlOp0SCEV, TruncTy);
8334 }
8335
8336 if (AddTruncateExpr && ShlAmtCI) {
8337 // We can merge the two given cases into a single SCEV statement,
8338 // incase n = m, the mul expression will be 2^0, so it gets resolved to
8339 // a simpler case. The following code handles the two cases:
8340 //
8341 // 1) For a two-shift sext-inreg, i.e. n = m,
8342 // use sext(trunc(x)) as the SCEV expression.
8343 //
8344 // 2) When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
8345 // expression. We already checked that ShlAmt < BitWidth, so
8346 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
8347 // ShlAmt - AShrAmt < Amt.
8348 const APInt &ShlAmt = ShlAmtCI->getValue();
8349 if (ShlAmt.ult(BitWidth) && ShlAmt.uge(AShrAmt)) {
8350 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
8351 ShlAmtCI->getZExtValue() - AShrAmt);
8352 const SCEV *CompositeExpr =
8353 getMulExpr(AddTruncateExpr, getConstant(Mul));
8354 if (L->getOpcode() != Instruction::Shl)
8355 CompositeExpr = getAddExpr(CompositeExpr, AddConstant);
8356
8357 return getSignExtendExpr(CompositeExpr, OuterTy);
8358 }
8359 }
8360 break;
8361 }
8362 }
8363
8364 switch (U->getOpcode()) {
8365 case Instruction::Trunc:
8366 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
8367
8368 case Instruction::ZExt:
8369 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8370
8371 case Instruction::SExt:
8372 if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
8374 // The NSW flag of a subtract does not always survive the conversion to
8375 // A + (-1)*B. By pushing sign extension onto its operands we are much
8376 // more likely to preserve NSW and allow later AddRec optimisations.
8377 //
8378 // NOTE: This is effectively duplicating this logic from getSignExtend:
8379 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
8380 // but by that point the NSW information has potentially been lost.
8381 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
8382 Type *Ty = U->getType();
8383 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
8384 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
8385 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
8386 }
8387 }
8388 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
8389
8390 case Instruction::BitCast:
8391 // BitCasts are no-op casts so we just eliminate the cast.
8392 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
8393 return getSCEV(U->getOperand(0));
8394 break;
8395
8396 case Instruction::PtrToAddr: {
8397 const SCEV *IntOp = getPtrToAddrExpr(getSCEV(U->getOperand(0)));
8398 if (isa<SCEVCouldNotCompute>(IntOp))
8399 return getUnknown(V);
8400 return IntOp;
8401 }
8402
8403 case Instruction::PtrToInt: {
8404 // Keep ptrtoint as SCEVUnknown, except when the pointer operand has SCEV
8405 // structure (e.g. a pointer add-rec or an offset from a known base). In
8406 // that case model it via ptrtoaddr to preserve the integer structure
8407 // (induction, constant folding). A bare SCEVUnknown pointer gains no
8408 // structure from wrapping it in ptrtoaddr, so leave it opaque.
8409 const SCEV *PtrSCEV = getSCEV(U->getOperand(0));
8410 if (!isa<SCEVUnknown>(PtrSCEV)) {
8411 const SCEV *Addr = getPtrToAddrExpr(PtrSCEV);
8412 if (!isa<SCEVCouldNotCompute>(Addr) &&
8413 getTypeSizeInBits(V->getType()) <= getTypeSizeInBits(Addr->getType()))
8414 return getTruncateOrNoop(Addr, V->getType());
8415 }
8416 return getUnknown(V);
8417 }
8418 case Instruction::IntToPtr:
8419 // Just don't deal with inttoptr casts.
8420 return getUnknown(V);
8421
8422 case Instruction::SDiv:
8423 // If both operands are non-negative, this is just an udiv.
8424 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8425 isKnownNonNegative(getSCEV(U->getOperand(1))))
8426 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8427 break;
8428
8429 case Instruction::SRem:
8430 // If both operands are non-negative, this is just an urem.
8431 if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
8432 isKnownNonNegative(getSCEV(U->getOperand(1))))
8433 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
8434 break;
8435
8436 case Instruction::GetElementPtr:
8437 return createNodeForGEP(cast<GEPOperator>(U));
8438
8439 case Instruction::PHI:
8440 return createNodeForPHI(cast<PHINode>(U));
8441
8442 case Instruction::Select:
8443 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
8444 U->getOperand(2));
8445
8446 case Instruction::Call:
8447 case Instruction::Invoke:
8448 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
8449 return getSCEV(RV);
8450
8451 if (auto *II = dyn_cast<IntrinsicInst>(U)) {
8452 switch (II->getIntrinsicID()) {
8453 case Intrinsic::abs:
8454 return getAbsExpr(
8455 getSCEV(II->getArgOperand(0)),
8456 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
8457 case Intrinsic::umax:
8458 LHS = getSCEV(II->getArgOperand(0));
8459 RHS = getSCEV(II->getArgOperand(1));
8460 return getUMaxExpr(LHS, RHS);
8461 case Intrinsic::umin:
8462 LHS = getSCEV(II->getArgOperand(0));
8463 RHS = getSCEV(II->getArgOperand(1));
8464 return getUMinExpr(LHS, RHS);
8465 case Intrinsic::smax:
8466 LHS = getSCEV(II->getArgOperand(0));
8467 RHS = getSCEV(II->getArgOperand(1));
8468 return getSMaxExpr(LHS, RHS);
8469 case Intrinsic::smin:
8470 LHS = getSCEV(II->getArgOperand(0));
8471 RHS = getSCEV(II->getArgOperand(1));
8472 return getSMinExpr(LHS, RHS);
8473 case Intrinsic::usub_sat: {
8474 const SCEV *X = getSCEV(II->getArgOperand(0));
8475 const SCEV *Y = getSCEV(II->getArgOperand(1));
8476 const SCEV *ClampedY = getUMinExpr(X, Y);
8477 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
8478 }
8479 case Intrinsic::uadd_sat: {
8480 const SCEV *X = getSCEV(II->getArgOperand(0));
8481 const SCEV *Y = getSCEV(II->getArgOperand(1));
8482 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
8483 return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
8484 }
8485 case Intrinsic::start_loop_iterations:
8486 case Intrinsic::annotation:
8487 case Intrinsic::ptr_annotation:
8488 // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
8489 // just eqivalent to the first operand for SCEV purposes.
8490 return getSCEV(II->getArgOperand(0));
8491 case Intrinsic::vscale:
8492 return getVScale(II->getType());
8493 default:
8494 break;
8495 }
8496 }
8497 break;
8498 }
8499
8500 return getUnknown(V);
8501}
8502
8503//===----------------------------------------------------------------------===//
8504// Iteration Count Computation Code
8505//
8506
8508 if (isa<SCEVCouldNotCompute>(ExitCount))
8509 return getCouldNotCompute();
8510
8511 auto *ExitCountType = ExitCount->getType();
8512 assert(ExitCountType->isIntegerTy());
8513 auto *EvalTy = Type::getIntNTy(ExitCountType->getContext(),
8514 1 + ExitCountType->getScalarSizeInBits());
8515 return getTripCountFromExitCount(ExitCount, EvalTy, nullptr);
8516}
8517
8519 Type *EvalTy,
8520 const Loop *L) {
8521 if (isa<SCEVCouldNotCompute>(ExitCount))
8522 return getCouldNotCompute();
8523
8524 unsigned ExitCountSize = getTypeSizeInBits(ExitCount->getType());
8525 unsigned EvalSize = EvalTy->getPrimitiveSizeInBits();
8526
8527 auto CanAddOneWithoutOverflow = [&]() {
8528 ConstantRange ExitCountRange =
8529 getRangeRef(ExitCount, RangeSignHint::HINT_RANGE_UNSIGNED);
8530 if (!ExitCountRange.contains(APInt::getMaxValue(ExitCountSize)))
8531 return true;
8532
8533 return L && isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
8534 getMinusOne(ExitCount->getType()));
8535 };
8536
8537 // If we need to zero extend the backedge count, check if we can add one to
8538 // it prior to zero extending without overflow. Provided this is safe, it
8539 // allows better simplification of the +1.
8540 if (EvalSize > ExitCountSize && CanAddOneWithoutOverflow())
8541 return getZeroExtendExpr(
8542 getAddExpr(ExitCount, getOne(ExitCount->getType())), EvalTy);
8543
8544 // Get the total trip count from the count by adding 1. This may wrap.
8545 return getAddExpr(getTruncateOrZeroExtend(ExitCount, EvalTy), getOne(EvalTy));
8546}
8547
8548static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
8549 if (!ExitCount)
8550 return 0;
8551
8552 ConstantInt *ExitConst = ExitCount->getValue();
8553
8554 // Guard against huge trip counts.
8555 if (ExitConst->getValue().getActiveBits() > 32)
8556 return 0;
8557
8558 // In case of integer overflow, this returns 0, which is correct.
8559 return ((unsigned)ExitConst->getZExtValue()) + 1;
8560}
8561
8563 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
8564 return getConstantTripCount(ExitCount);
8565}
8566
8567unsigned
8569 const BasicBlock *ExitingBlock) {
8570 assert(ExitingBlock && "Must pass a non-null exiting block!");
8571 assert(L->isLoopExiting(ExitingBlock) &&
8572 "Exiting block must actually branch out of the loop!");
8573 const SCEVConstant *ExitCount =
8574 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
8575 return getConstantTripCount(ExitCount);
8576}
8577
8579 const Loop *L, SmallVectorImpl<const SCEVPredicate *> *Predicates) {
8580
8581 const auto *MaxExitCount =
8582 Predicates ? getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
8584 return getConstantTripCount(dyn_cast<SCEVConstant>(MaxExitCount));
8585}
8586
8588 SmallVector<BasicBlock *, 8> ExitingBlocks;
8589 L->getExitingBlocks(ExitingBlocks);
8590
8591 std::optional<unsigned> Res;
8592 for (auto *ExitingBB : ExitingBlocks) {
8593 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
8594 if (!Res)
8595 Res = Multiple;
8596 Res = std::gcd(*Res, Multiple);
8597 }
8598 return Res.value_or(1);
8599}
8600
8602 const SCEV *ExitCount) {
8603 if (isa<SCEVCouldNotCompute>(ExitCount))
8604 return 1;
8605
8606 // Get the trip count
8607 const SCEV *TCExpr = getTripCountFromExitCount(applyLoopGuards(ExitCount, L));
8608
8609 APInt Multiple = getNonZeroConstantMultiple(TCExpr);
8610 // If a trip multiple is huge (>=2^32), the trip count is still divisible by
8611 // the greatest power of 2 divisor less than 2^32.
8612 return Multiple.getActiveBits() > 32
8613 ? 1U << std::min(31U, Multiple.countTrailingZeros())
8614 : (unsigned)Multiple.getZExtValue();
8615}
8616
8617/// Returns the largest constant divisor of the trip count of this loop as a
8618/// normal unsigned value, if possible. This means that the actual trip count is
8619/// always a multiple of the returned value (don't forget the trip count could
8620/// very well be zero as well!).
8621///
8622/// Returns 1 if the trip count is unknown or not guaranteed to be the
8623/// multiple of a constant (which is also the case if the trip count is simply
8624/// constant, use getSmallConstantTripCount for that case), Will also return 1
8625/// if the trip count is very large (>= 2^32).
8626///
8627/// As explained in the comments for getSmallConstantTripCount, this assumes
8628/// that control exits the loop via ExitingBlock.
8629unsigned
8631 const BasicBlock *ExitingBlock) {
8632 assert(ExitingBlock && "Must pass a non-null exiting block!");
8633 assert(L->isLoopExiting(ExitingBlock) &&
8634 "Exiting block must actually branch out of the loop!");
8635 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
8636 return getSmallConstantTripMultiple(L, ExitCount);
8637}
8638
8640 const BasicBlock *ExitingBlock,
8641 ExitCountKind Kind) {
8642 switch (Kind) {
8643 case Exact:
8644 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
8645 case SymbolicMaximum:
8646 return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
8647 case ConstantMaximum:
8648 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
8649 };
8650 llvm_unreachable("Invalid ExitCountKind!");
8651}
8652
8654 const Loop *L, const BasicBlock *ExitingBlock,
8656 switch (Kind) {
8657 case Exact:
8658 return getPredicatedBackedgeTakenInfo(L).getExact(ExitingBlock, this,
8659 Predicates);
8660 case SymbolicMaximum:
8661 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this,
8662 Predicates);
8663 case ConstantMaximum:
8664 return getPredicatedBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this,
8665 Predicates);
8666 };
8667 llvm_unreachable("Invalid ExitCountKind!");
8668}
8669
8672 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
8673}
8674
8676 ExitCountKind Kind) {
8677 switch (Kind) {
8678 case Exact:
8679 return getBackedgeTakenInfo(L).getExact(L, this);
8680 case ConstantMaximum:
8681 return getBackedgeTakenInfo(L).getConstantMax(this);
8682 case SymbolicMaximum:
8683 return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
8684 };
8685 llvm_unreachable("Invalid ExitCountKind!");
8686}
8687
8690 return getPredicatedBackedgeTakenInfo(L).getSymbolicMax(L, this, &Preds);
8691}
8692
8695 return getPredicatedBackedgeTakenInfo(L).getConstantMax(this, &Preds);
8696}
8697
8699 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
8700}
8701
8702ScalarEvolution::BackedgeTakenInfo &
8703ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
8704 auto &BTI = getBackedgeTakenInfo(L);
8705 if (BTI.hasFullInfo())
8706 return BTI;
8707
8708 auto Pair = PredicatedBackedgeTakenCounts.try_emplace(L);
8709
8710 if (!Pair.second)
8711 return Pair.first->second;
8712
8713 BackedgeTakenInfo Result =
8714 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
8715
8716 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
8717}
8718
8719ScalarEvolution::BackedgeTakenInfo &
8720ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
8721 // Initially insert an invalid entry for this loop. If the insertion
8722 // succeeds, proceed to actually compute a backedge-taken count and
8723 // update the value. The temporary CouldNotCompute value tells SCEV
8724 // code elsewhere that it shouldn't attempt to request a new
8725 // backedge-taken count, which could result in infinite recursion.
8726 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
8727 BackedgeTakenCounts.try_emplace(L);
8728 if (!Pair.second)
8729 return Pair.first->second;
8730
8731 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
8732 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
8733 // must be cleared in this scope.
8734 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
8735
8736 // Now that we know more about the trip count for this loop, forget any
8737 // existing SCEV values for PHI nodes in this loop since they are only
8738 // conservative estimates made without the benefit of trip count
8739 // information. This invalidation is not necessary for correctness, and is
8740 // only done to produce more precise results.
8741 if (Result.hasAnyInfo()) {
8742 // Invalidate any expression using an addrec in this loop.
8743 SmallVector<SCEVUse, 8> ToForget;
8744 auto LoopUsersIt = LoopUsers.find(L);
8745 if (LoopUsersIt != LoopUsers.end())
8746 append_range(ToForget, LoopUsersIt->second);
8747 forgetMemoizedResults(ToForget);
8748
8749 // Invalidate constant-evolved loop header phis.
8750 for (PHINode &PN : L->getHeader()->phis())
8751 ConstantEvolutionLoopExitValue.erase(&PN);
8752 }
8753
8754 // Re-lookup the insert position, since the call to
8755 // computeBackedgeTakenCount above could result in a
8756 // recusive call to getBackedgeTakenInfo (on a different
8757 // loop), which would invalidate the iterator computed
8758 // earlier.
8759 return BackedgeTakenCounts.find(L)->second = std::move(Result);
8760}
8761
8763 // This method is intended to forget all info about loops. It should
8764 // invalidate caches as if the following happened:
8765 // - The trip counts of all loops have changed arbitrarily
8766 // - Every llvm::Value has been updated in place to produce a different
8767 // result.
8768 BackedgeTakenCounts.clear();
8769 PredicatedBackedgeTakenCounts.clear();
8770 BECountUsers.clear();
8771 LoopPropertiesCache.clear();
8772 ConstantEvolutionLoopExitValue.clear();
8773 ValueExprMap.clear();
8774 ValuesAtScopes.clear();
8775 ValuesAtScopesUsers.clear();
8776 LoopDispositions.clear();
8777 BlockDispositions.clear();
8778 UnsignedRanges.clear();
8779 SignedRanges.clear();
8780 ExprValueMap.clear();
8781 HasRecMap.clear();
8782 ConstantMultipleCache.clear();
8783 PredicatedSCEVRewrites.clear();
8784 FoldCache.clear();
8785 FoldCacheUser.clear();
8786}
8787void ScalarEvolution::visitAndClearUsers(
8790 SmallVectorImpl<SCEVUse> &ToForget) {
8791 while (!Worklist.empty()) {
8792 Instruction *I = Worklist.pop_back_val();
8793 if (!isSCEVable(I->getType()) && !isa<WithOverflowInst>(I))
8794 continue;
8795
8797 ValueExprMap.find_as(static_cast<Value *>(I));
8798 if (It != ValueExprMap.end()) {
8799 ToForget.push_back(It->second);
8800 eraseValueFromMap(It->first);
8801 if (PHINode *PN = dyn_cast<PHINode>(I))
8802 ConstantEvolutionLoopExitValue.erase(PN);
8803 }
8804
8805 PushDefUseChildren(I, Worklist, Visited);
8806 }
8807}
8808
8810 SmallVector<const Loop *, 16> LoopWorklist(1, L);
8811 SmallVector<SCEVUse, 16> ToForget;
8812
8813 // Iterate over all the loops and sub-loops to drop SCEV information.
8814 while (!LoopWorklist.empty()) {
8815 auto *CurrL = LoopWorklist.pop_back_val();
8816
8817 // Drop any stored trip count value.
8818 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
8819 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
8820
8821 // Drop information about predicated SCEV rewrites for this loop.
8822 PredicatedSCEVRewrites.remove_if(
8823 [&](const auto &Entry) { return Entry.first.second == CurrL; });
8824
8825 auto LoopUsersItr = LoopUsers.find(CurrL);
8826 if (LoopUsersItr != LoopUsers.end())
8827 llvm::append_range(ToForget, LoopUsersItr->second);
8828
8829 // Drop information about expressions based on loop-header PHIs.
8830 for (PHINode &PN : CurrL->getHeader()->phis()) {
8831 ConstantEvolutionLoopExitValue.erase(&PN);
8832 auto VIt = ValueExprMap.find_as(static_cast<Value *>(&PN));
8833 if (VIt != ValueExprMap.end())
8834 ToForget.push_back(VIt->second);
8835 }
8836
8837 LoopPropertiesCache.erase(CurrL);
8838 // Forget all contained loops too, to avoid dangling entries in the
8839 // ValuesAtScopes map.
8840 LoopWorklist.append(CurrL->begin(), CurrL->end());
8841 }
8842 forgetMemoizedResults(ToForget);
8843}
8844
8846 forgetLoop(L->getOutermostLoop());
8847}
8848
8851 if (!I) return;
8852
8853 // Drop information about expressions based on loop-header PHIs.
8856 SmallVector<SCEVUse, 8> ToForget;
8857 Worklist.push_back(I);
8858 Visited.insert(I);
8859 visitAndClearUsers(Worklist, Visited, ToForget);
8860
8861 forgetMemoizedResults(ToForget);
8862}
8863
8865 if (!isSCEVable(V->getType()))
8866 return;
8867
8868 // If SCEV looked through a trivial LCSSA phi node, we might have SCEV's
8869 // directly using a SCEVUnknown/SCEVAddRec defined in the loop. After an
8870 // extra predecessor is added, this is no longer valid. Find all Unknowns and
8871 // AddRecs defined in the loop and invalidate any SCEV's making use of them.
8872 if (const SCEV *S = getExistingSCEV(V)) {
8873 struct InvalidationRootCollector {
8874 Loop *L;
8876
8877 InvalidationRootCollector(Loop *L) : L(L) {}
8878
8879 bool follow(const SCEV *S) {
8880 if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
8881 if (auto *I = dyn_cast<Instruction>(SU->getValue()))
8882 if (L->contains(I))
8883 Roots.push_back(S);
8884 } else if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
8885 if (L->contains(AddRec->getLoop()))
8886 Roots.push_back(S);
8887 }
8888 return true;
8889 }
8890 bool isDone() const { return false; }
8891 };
8892
8893 InvalidationRootCollector C(L);
8894 visitAll(S, C);
8895 forgetMemoizedResults(C.Roots);
8896 }
8897
8898 // Also perform the normal invalidation.
8899 forgetValue(V);
8900}
8901
8902void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
8903
8905 // Unless a specific value is passed to invalidation, completely clear both
8906 // caches.
8907 if (!V) {
8908 BlockDispositions.clear();
8909 LoopDispositions.clear();
8910 return;
8911 }
8912
8913 if (!isSCEVable(V->getType()))
8914 return;
8915
8916 const SCEV *S = getExistingSCEV(V);
8917 if (!S)
8918 return;
8919
8920 // Invalidate the block and loop dispositions cached for S. Dispositions of
8921 // S's users may change if S's disposition changes (i.e. a user may change to
8922 // loop-invariant, if S changes to loop invariant), so also invalidate
8923 // dispositions of S's users recursively.
8924 SmallVector<SCEVUse, 8> Worklist = {S};
8926 while (!Worklist.empty()) {
8927 const SCEV *Curr = Worklist.pop_back_val();
8928 bool LoopDispoRemoved = LoopDispositions.erase(Curr);
8929 bool BlockDispoRemoved = BlockDispositions.erase(Curr);
8930 if (!LoopDispoRemoved && !BlockDispoRemoved)
8931 continue;
8932 auto Users = SCEVUsers.find(Curr);
8933 if (Users != SCEVUsers.end())
8934 for (const auto *User : Users->second)
8935 if (Seen.insert(User).second)
8936 Worklist.push_back(User);
8937 }
8938}
8939
8940/// Get the exact loop backedge taken count considering all loop exits. A
8941/// computable result can only be returned for loops with all exiting blocks
8942/// dominating the latch. howFarToZero assumes that the limit of each loop test
8943/// is never skipped. This is a valid assumption as long as the loop exits via
8944/// that test. For precise results, it is the caller's responsibility to specify
8945/// the relevant loop exiting block using getExact(ExitingBlock, SE).
8946const SCEV *ScalarEvolution::BackedgeTakenInfo::getExact(
8947 const Loop *L, ScalarEvolution *SE,
8949 // If any exits were not computable, the loop is not computable.
8950 if (!isComplete() || ExitNotTaken.empty())
8951 return SE->getCouldNotCompute();
8952
8953 const BasicBlock *Latch = L->getLoopLatch();
8954 // All exiting blocks we have collected must dominate the only backedge.
8955 if (!Latch)
8956 return SE->getCouldNotCompute();
8957
8958 // All exiting blocks we have gathered dominate loop's latch, so exact trip
8959 // count is simply a minimum out of all these calculated exit counts.
8961 for (const auto &ENT : ExitNotTaken) {
8962 const SCEV *BECount = ENT.ExactNotTaken;
8963 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
8964 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
8965 "We should only have known counts for exiting blocks that dominate "
8966 "latch!");
8967
8968 Ops.push_back(BECount);
8969
8970 if (Preds)
8971 append_range(*Preds, ENT.Predicates);
8972
8973 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
8974 "Predicate should be always true!");
8975 }
8976
8977 // If an earlier exit exits on the first iteration (exit count zero), then
8978 // a later poison exit count should not propagate into the result. This are
8979 // exactly the semantics provided by umin_seq.
8980 return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
8981}
8982
8983const ScalarEvolution::ExitNotTakenInfo *
8984ScalarEvolution::BackedgeTakenInfo::getExitNotTaken(
8985 const BasicBlock *ExitingBlock,
8986 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
8987 for (const auto &ENT : ExitNotTaken)
8988 if (ENT.ExitingBlock == ExitingBlock) {
8989 if (ENT.hasAlwaysTruePredicate())
8990 return &ENT;
8991 else if (Predicates) {
8992 append_range(*Predicates, ENT.Predicates);
8993 return &ENT;
8994 }
8995 }
8996
8997 return nullptr;
8998}
8999
9000/// getConstantMax - Get the constant max backedge taken count for the loop.
9001const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
9002 ScalarEvolution *SE,
9003 SmallVectorImpl<const SCEVPredicate *> *Predicates) const {
9004 if (!getConstantMax())
9005 return SE->getCouldNotCompute();
9006
9007 for (const auto &ENT : ExitNotTaken)
9008 if (!ENT.hasAlwaysTruePredicate()) {
9009 if (!Predicates)
9010 return SE->getCouldNotCompute();
9011 append_range(*Predicates, ENT.Predicates);
9012 }
9013
9014 assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
9015 isa<SCEVConstant>(getConstantMax())) &&
9016 "No point in having a non-constant max backedge taken count!");
9017 return getConstantMax();
9018}
9019
9020const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
9021 const Loop *L, ScalarEvolution *SE,
9022 SmallVectorImpl<const SCEVPredicate *> *Predicates) {
9023 if (!SymbolicMax) {
9024 // Form an expression for the maximum exit count possible for this loop. We
9025 // merge the max and exact information to approximate a version of
9026 // getConstantMaxBackedgeTakenCount which isn't restricted to just
9027 // constants.
9028 SmallVector<SCEVUse, 4> ExitCounts;
9029
9030 for (const auto &ENT : ExitNotTaken) {
9031 const SCEV *ExitCount = ENT.SymbolicMaxNotTaken;
9032 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
9033 assert(SE->DT.dominates(ENT.ExitingBlock, L->getLoopLatch()) &&
9034 "We should only have known counts for exiting blocks that "
9035 "dominate latch!");
9036 ExitCounts.push_back(ExitCount);
9037 if (Predicates)
9038 append_range(*Predicates, ENT.Predicates);
9039
9040 assert((Predicates || ENT.hasAlwaysTruePredicate()) &&
9041 "Predicate should be always true!");
9042 }
9043 }
9044 if (ExitCounts.empty())
9045 SymbolicMax = SE->getCouldNotCompute();
9046 else
9047 SymbolicMax =
9048 SE->getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
9049 }
9050 return SymbolicMax;
9051}
9052
9053bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
9054 ScalarEvolution *SE) const {
9055 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
9056 return !ENT.hasAlwaysTruePredicate();
9057 };
9058 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
9059}
9060
9063
9065 const SCEV *E, const SCEV *ConstantMaxNotTaken,
9066 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
9070 // If we prove the max count is zero, so is the symbolic bound. This happens
9071 // in practice due to differences in a) how context sensitive we've chosen
9072 // to be and b) how we reason about bounds implied by UB.
9073 if (ConstantMaxNotTaken->isZero()) {
9074 this->ExactNotTaken = E = ConstantMaxNotTaken;
9075 this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
9076 }
9077
9080 "Exact is not allowed to be less precise than Constant Max");
9083 "Exact is not allowed to be less precise than Symbolic Max");
9086 "Symbolic Max is not allowed to be less precise than Constant Max");
9089 "No point in having a non-constant max backedge taken count!");
9091 for (const auto PredList : PredLists)
9092 for (const auto *P : PredList) {
9093 if (SeenPreds.contains(P))
9094 continue;
9095 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
9096 SeenPreds.insert(P);
9097 Predicates.push_back(P);
9098 }
9099 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
9100 "Backedge count should be int");
9102 !ConstantMaxNotTaken->getType()->isPointerTy()) &&
9103 "Max backedge count should be int");
9104}
9105
9113
9114/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
9115/// computable exit into a persistent ExitNotTakenInfo array.
9116ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
9118 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
9119 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
9120 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9121
9122 ExitNotTaken.reserve(ExitCounts.size());
9123 std::transform(ExitCounts.begin(), ExitCounts.end(),
9124 std::back_inserter(ExitNotTaken),
9125 [&](const EdgeExitInfo &EEI) {
9126 BasicBlock *ExitBB = EEI.first;
9127 const ExitLimit &EL = EEI.second;
9128 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
9129 EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
9130 EL.Predicates);
9131 });
9132 assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
9133 isa<SCEVConstant>(ConstantMax)) &&
9134 "No point in having a non-constant max backedge taken count!");
9135}
9136
9137/// Compute the number of times the backedge of the specified loop will execute.
9138ScalarEvolution::BackedgeTakenInfo
9139ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
9140 bool AllowPredicates) {
9141 SmallVector<BasicBlock *, 8> ExitingBlocks;
9142 L->getExitingBlocks(ExitingBlocks);
9143
9144 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
9145
9147 bool CouldComputeBECount = true;
9148 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
9149 const SCEV *MustExitMaxBECount = nullptr;
9150 const SCEV *MayExitMaxBECount = nullptr;
9151 bool MustExitMaxOrZero = false;
9152 bool IsOnlyExit = ExitingBlocks.size() == 1;
9153
9154 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
9155 // and compute maxBECount.
9156 // Do a union of all the predicates here.
9157 for (BasicBlock *ExitBB : ExitingBlocks) {
9158 // We canonicalize untaken exits to br (constant), ignore them so that
9159 // proving an exit untaken doesn't negatively impact our ability to reason
9160 // about the loop as whole.
9161 if (auto *BI = dyn_cast<CondBrInst>(ExitBB->getTerminator()))
9162 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
9163 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9164 if (ExitIfTrue == CI->isZero())
9165 continue;
9166 }
9167
9168 ExitLimit EL = computeExitLimit(L, ExitBB, IsOnlyExit, AllowPredicates);
9169
9170 assert((AllowPredicates || EL.Predicates.empty()) &&
9171 "Predicated exit limit when predicates are not allowed!");
9172
9173 // 1. For each exit that can be computed, add an entry to ExitCounts.
9174 // CouldComputeBECount is true only if all exits can be computed.
9175 if (EL.ExactNotTaken != getCouldNotCompute())
9176 ++NumExitCountsComputed;
9177 else
9178 // We couldn't compute an exact value for this exit, so
9179 // we won't be able to compute an exact value for the loop.
9180 CouldComputeBECount = false;
9181 // Remember exit count if either exact or symbolic is known. Because
9182 // Exact always implies symbolic, only check symbolic.
9183 if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
9184 ExitCounts.emplace_back(ExitBB, EL);
9185 else {
9186 assert(EL.ExactNotTaken == getCouldNotCompute() &&
9187 "Exact is known but symbolic isn't?");
9188 ++NumExitCountsNotComputed;
9189 }
9190
9191 // 2. Derive the loop's MaxBECount from each exit's max number of
9192 // non-exiting iterations. Partition the loop exits into two kinds:
9193 // LoopMustExits and LoopMayExits.
9194 //
9195 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
9196 // is a LoopMayExit. If any computable LoopMustExit is found, then
9197 // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
9198 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
9199 // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
9200 // any
9201 // computable EL.ConstantMaxNotTaken.
9202 if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
9203 DT.dominates(ExitBB, Latch)) {
9204 if (!MustExitMaxBECount) {
9205 MustExitMaxBECount = EL.ConstantMaxNotTaken;
9206 MustExitMaxOrZero = EL.MaxOrZero;
9207 } else {
9208 MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
9209 EL.ConstantMaxNotTaken);
9210 }
9211 } else if (MayExitMaxBECount != getCouldNotCompute()) {
9212 if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
9213 MayExitMaxBECount = EL.ConstantMaxNotTaken;
9214 else {
9215 MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
9216 EL.ConstantMaxNotTaken);
9217 }
9218 }
9219 }
9220 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
9221 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
9222 // The loop backedge will be taken the maximum or zero times if there's
9223 // a single exit that must be taken the maximum or zero times.
9224 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
9225
9226 // Remember which SCEVs are used in exit limits for invalidation purposes.
9227 // We only care about non-constant SCEVs here, so we can ignore
9228 // EL.ConstantMaxNotTaken
9229 // and MaxBECount, which must be SCEVConstant.
9230 for (const auto &Pair : ExitCounts) {
9231 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
9232 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
9233 if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
9234 BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
9235 {L, AllowPredicates});
9236 }
9237 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
9238 MaxBECount, MaxOrZero);
9239}
9240
9241ScalarEvolution::ExitLimit
9242ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
9243 bool IsOnlyExit, bool AllowPredicates) {
9244 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
9245 // If our exiting block does not dominate the latch, then its connection with
9246 // loop's exit limit may be far from trivial.
9247 const BasicBlock *Latch = L->getLoopLatch();
9248 if (!Latch || !DT.dominates(ExitingBlock, Latch))
9249 return getCouldNotCompute();
9250
9251 Instruction *Term = ExitingBlock->getTerminator();
9252 if (CondBrInst *BI = dyn_cast<CondBrInst>(Term)) {
9253 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
9254 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
9255 "It should have one successor in loop and one exit block!");
9256 // Proceed to the next level to examine the exit condition expression.
9257 return computeExitLimitFromCond(L, BI->getCondition(), ExitIfTrue,
9258 /*ControlsOnlyExit=*/IsOnlyExit,
9259 AllowPredicates);
9260 }
9261
9262 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
9263 // For switch, make sure that there is a single exit from the loop.
9264 BasicBlock *Exit = nullptr;
9265 for (auto *SBB : successors(ExitingBlock))
9266 if (!L->contains(SBB)) {
9267 if (Exit) // Multiple exit successors.
9268 return getCouldNotCompute();
9269 Exit = SBB;
9270 }
9271 assert(Exit && "Exiting block must have at least one exit");
9272 return computeExitLimitFromSingleExitSwitch(
9273 L, SI, Exit, /*ControlsOnlyExit=*/IsOnlyExit);
9274 }
9275
9276 return getCouldNotCompute();
9277}
9278
9280 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9281 bool AllowPredicates) {
9282 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
9283 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
9284 ControlsOnlyExit, AllowPredicates);
9285}
9286
9287std::optional<ScalarEvolution::ExitLimit>
9288ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
9289 bool ExitIfTrue, bool ControlsOnlyExit,
9290 bool AllowPredicates) {
9291 (void)this->L;
9292 (void)this->ExitIfTrue;
9293 (void)this->AllowPredicates;
9294
9295 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9296 this->AllowPredicates == AllowPredicates &&
9297 "Variance in assumed invariant key components!");
9298 auto Itr = TripCountMap.find({ExitCond, ControlsOnlyExit});
9299 if (Itr == TripCountMap.end())
9300 return std::nullopt;
9301 return Itr->second;
9302}
9303
9304void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
9305 bool ExitIfTrue,
9306 bool ControlsOnlyExit,
9307 bool AllowPredicates,
9308 const ExitLimit &EL) {
9309 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
9310 this->AllowPredicates == AllowPredicates &&
9311 "Variance in assumed invariant key components!");
9312
9313 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsOnlyExit}, EL});
9314 assert(InsertResult.second && "Expected successful insertion!");
9315 (void)InsertResult;
9316 (void)ExitIfTrue;
9317}
9318
9319ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
9320 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9321 bool ControlsOnlyExit, bool AllowPredicates) {
9322
9323 if (auto MaybeEL = Cache.find(L, ExitCond, ExitIfTrue, ControlsOnlyExit,
9324 AllowPredicates))
9325 return *MaybeEL;
9326
9327 ExitLimit EL = computeExitLimitFromCondImpl(
9328 Cache, L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates);
9329 Cache.insert(L, ExitCond, ExitIfTrue, ControlsOnlyExit, AllowPredicates, EL);
9330 return EL;
9331}
9332
9333ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
9334 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
9335 bool ControlsOnlyExit, bool AllowPredicates) {
9336 // Handle BinOp conditions (And, Or).
9337 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
9338 Cache, L, ExitCond, ExitIfTrue, AllowPredicates))
9339 return *LimitFromBinOp;
9340
9341 // With an icmp, it may be feasible to compute an exact backedge-taken count.
9342 // Proceed to the next level to examine the icmp.
9343 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
9344 ExitLimit EL =
9345 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsOnlyExit);
9346 if (EL.hasFullInfo() || !AllowPredicates)
9347 return EL;
9348
9349 // Try again, but use SCEV predicates this time.
9350 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue,
9351 ControlsOnlyExit,
9352 /*AllowPredicates=*/true);
9353 }
9354
9355 // Check for a constant condition. These are normally stripped out by
9356 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
9357 // preserve the CFG and is temporarily leaving constant conditions
9358 // in place.
9359 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
9360 if (ExitIfTrue == !CI->getZExtValue())
9361 // The backedge is always taken.
9362 return getCouldNotCompute();
9363 // The backedge is never taken.
9364 return getZero(CI->getType());
9365 }
9366
9367 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
9368 // with a constant step, we can form an equivalent icmp predicate and figure
9369 // out how many iterations will be taken before we exit.
9370 const WithOverflowInst *WO;
9371 const APInt *C;
9372 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
9373 match(WO->getRHS(), m_APInt(C))) {
9374 ConstantRange NWR =
9376 WO->getNoWrapKind());
9377 CmpInst::Predicate Pred;
9378 APInt NewRHSC, Offset;
9379 NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
9380 if (!ExitIfTrue)
9381 Pred = ICmpInst::getInversePredicate(Pred);
9382 auto *LHS = getSCEV(WO->getLHS());
9383 if (Offset != 0)
9385 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
9386 ControlsOnlyExit, AllowPredicates);
9387 if (EL.hasAnyInfo())
9388 return EL;
9389 }
9390
9391 // If it's not an integer or pointer comparison then compute it the hard way.
9392 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9393}
9394
9395std::optional<ScalarEvolution::ExitLimit>
9396ScalarEvolution::computeExitLimitFromCondFromBinOp(ExitLimitCacheTy &Cache,
9397 const Loop *L,
9398 Value *ExitCond,
9399 bool ExitIfTrue,
9400 bool AllowPredicates) {
9401 // Check if the controlling expression for this loop is an And or Or.
9402 Value *Op0, *Op1;
9403 bool IsAnd;
9404 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
9405 IsAnd = true;
9406 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
9407 IsAnd = false;
9408 else
9409 return std::nullopt;
9410
9411 // A sub-condition of a non-trivial binop never solely controls the exit,
9412 // whether we exit always depends on both conditions.
9413 ExitLimit EL0 = computeExitLimitFromCondCached(
9414 Cache, L, Op0, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9415 ExitLimit EL1 = computeExitLimitFromCondCached(
9416 Cache, L, Op1, ExitIfTrue, /*ControlsOnlyExit=*/false, AllowPredicates);
9417
9418 // EitherMayExit is true in these two cases:
9419 // br (and Op0 Op1), loop, exit
9420 // br (or Op0 Op1), exit, loop
9421 bool EitherMayExit = IsAnd ^ ExitIfTrue;
9422
9423 const SCEV *BECount = getCouldNotCompute();
9424 const SCEV *ConstantMaxBECount = getCouldNotCompute();
9425 const SCEV *SymbolicMaxBECount = getCouldNotCompute();
9426 if (EitherMayExit) {
9427 bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
9428 // Both conditions must be same for the loop to continue executing.
9429 // Choose the less conservative count.
9430 if (EL0.ExactNotTaken != getCouldNotCompute() &&
9431 EL1.ExactNotTaken != getCouldNotCompute()) {
9432 BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
9433 UseSequentialUMin);
9434 }
9435 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
9436 ConstantMaxBECount = EL1.ConstantMaxNotTaken;
9437 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
9438 ConstantMaxBECount = EL0.ConstantMaxNotTaken;
9439 else
9440 ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
9441 EL1.ConstantMaxNotTaken);
9442 if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
9443 SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
9444 else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
9445 SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
9446 else
9447 SymbolicMaxBECount = getUMinFromMismatchedTypes(
9448 EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
9449 } else {
9450 // Both conditions must be same at the same time for the loop to exit.
9451 // For now, be conservative.
9452 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
9453 BECount = EL0.ExactNotTaken;
9454 }
9455
9456 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
9457 // to be more aggressive when computing BECount than when computing
9458 // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
9459 // and
9460 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
9461 // EL1.ConstantMaxNotTaken to not.
9462 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
9463 !isa<SCEVCouldNotCompute>(BECount))
9464 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
9465 if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
9466 SymbolicMaxBECount =
9467 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
9468 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
9469 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
9470}
9471
9472ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9473 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit,
9474 bool AllowPredicates) {
9475 // If the condition was exit on true, convert the condition to exit on false
9476 CmpPredicate Pred;
9477 if (!ExitIfTrue)
9478 Pred = ExitCond->getCmpPredicate();
9479 else
9480 Pred = ExitCond->getInverseCmpPredicate();
9481 const ICmpInst::Predicate OriginalPred = Pred;
9482
9483 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
9484 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
9485
9486 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsOnlyExit,
9487 AllowPredicates);
9488 if (EL.hasAnyInfo())
9489 return EL;
9490
9491 auto *ExhaustiveCount =
9492 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
9493
9494 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
9495 return ExhaustiveCount;
9496
9497 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
9498 ExitCond->getOperand(1), L, OriginalPred);
9499}
9500ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromICmp(
9501 const Loop *L, CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS,
9502 bool ControlsOnlyExit, bool AllowPredicates) {
9503
9504 // Try to evaluate any dependencies out of the loop.
9505 LHS = getSCEVAtScope(LHS, L);
9506 RHS = getSCEVAtScope(RHS, L);
9507
9508 // At this point, we would like to compute how many iterations of the
9509 // loop the predicate will return true for these inputs.
9510 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
9511 // If there is a loop-invariant, force it into the RHS.
9512 std::swap(LHS, RHS);
9514 }
9515
9516 bool ControllingFiniteLoop = ControlsOnlyExit && loopHasNoAbnormalExits(L) &&
9518 // Simplify the operands before analyzing them.
9519 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0);
9520
9521 // If we have a comparison of a chrec against a constant, try to use value
9522 // ranges to answer this query.
9523 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
9524 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
9525 if (AddRec->getLoop() == L) {
9526 // Form the constant range.
9527 ConstantRange CompRange =
9528 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
9529
9530 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
9531 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
9532 }
9533
9534 // If this loop must exit based on this condition (or execute undefined
9535 // behaviour), see if we can improve wrap flags. This is essentially
9536 // a must execute style proof.
9537 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
9538 // If we can prove the test sequence produced must repeat the same values
9539 // on self-wrap of the IV, then we can infer that IV doesn't self wrap
9540 // because if it did, we'd have an infinite (undefined) loop.
9541 // TODO: We can peel off any functions which are invertible *in L*. Loop
9542 // invariant terms are effectively constants for our purposes here.
9543 SCEVUse InnerLHS = LHS;
9544 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
9545 InnerLHS = ZExt->getOperand();
9546 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS);
9547 AR && !AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
9548 isKnownToBeAPowerOfTwo(AR->getStepRecurrence(*this), /*OrZero=*/true,
9549 /*OrNegative=*/true)) {
9550 auto Flags = AR->getNoWrapFlags();
9551 Flags = setFlags(Flags, SCEV::FlagNW);
9552 SmallVector<SCEVUse> Operands{AR->operands()};
9553 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9554 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9555 }
9556
9557 // For a slt/ult condition with a positive step, can we prove nsw/nuw?
9558 // From no-self-wrap, this follows trivially from the fact that every
9559 // (un)signed-wrapped, but not self-wrapped value must be LT than the
9560 // last value before (un)signed wrap. Since we know that last value
9561 // didn't exit, nor will any smaller one.
9562 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) {
9563 auto WrapType = Pred == ICmpInst::ICMP_SLT ? SCEV::FlagNSW : SCEV::FlagNUW;
9564 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS);
9565 AR && AR->getLoop() == L && AR->isAffine() &&
9566 !AR->getNoWrapFlags(WrapType) && AR->hasNoSelfWrap() &&
9567 isKnownPositive(AR->getStepRecurrence(*this))) {
9568 auto Flags = AR->getNoWrapFlags();
9569 Flags = setFlags(Flags, WrapType);
9570 SmallVector<SCEVUse> Operands{AR->operands()};
9571 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
9572 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
9573 }
9574 }
9575 }
9576
9577 switch (Pred) {
9578 case ICmpInst::ICMP_NE: { // while (X != Y)
9579 // Convert to: while (X-Y != 0)
9580 if (LHS->getType()->isPointerTy()) {
9583 return LHS;
9584 }
9585 if (RHS->getType()->isPointerTy()) {
9588 return RHS;
9589 }
9590 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit,
9591 AllowPredicates);
9592 if (EL.hasAnyInfo())
9593 return EL;
9594 break;
9595 }
9596 case ICmpInst::ICMP_EQ: { // while (X == Y)
9597 // Convert to: while (X-Y == 0)
9598 if (LHS->getType()->isPointerTy()) {
9601 return LHS;
9602 }
9603 if (RHS->getType()->isPointerTy()) {
9606 return RHS;
9607 }
9608 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
9609 if (EL.hasAnyInfo()) return EL;
9610 break;
9611 }
9612 case ICmpInst::ICMP_SLE:
9613 case ICmpInst::ICMP_ULE:
9614 // Since the loop is finite, an invariant RHS cannot include the boundary
9615 // value, otherwise it would loop forever.
9616 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9617 !isLoopInvariant(RHS, L)) {
9618 // Otherwise, perform the addition in a wider type, to avoid overflow.
9619 // If the LHS is an addrec with the appropriate nowrap flag, the
9620 // extension will be sunk into it and the exit count can be analyzed.
9621 auto *OldType = dyn_cast<IntegerType>(LHS->getType());
9622 if (!OldType)
9623 break;
9624 // Prefer doubling the bitwidth over adding a single bit to make it more
9625 // likely that we use a legal type.
9626 auto *NewType =
9627 Type::getIntNTy(OldType->getContext(), OldType->getBitWidth() * 2);
9628 if (ICmpInst::isSigned(Pred)) {
9629 LHS = getSignExtendExpr(LHS, NewType);
9630 RHS = getSignExtendExpr(RHS, NewType);
9631 } else {
9632 LHS = getZeroExtendExpr(LHS, NewType);
9633 RHS = getZeroExtendExpr(RHS, NewType);
9634 }
9635 }
9637 [[fallthrough]];
9638 case ICmpInst::ICMP_SLT:
9639 case ICmpInst::ICMP_ULT: { // while (X < Y)
9640 bool IsSigned = ICmpInst::isSigned(Pred);
9641 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9642 AllowPredicates);
9643 if (EL.hasAnyInfo())
9644 return EL;
9645 break;
9646 }
9647 case ICmpInst::ICMP_SGE:
9648 case ICmpInst::ICMP_UGE:
9649 // Since the loop is finite, an invariant RHS cannot include the boundary
9650 // value, otherwise it would loop forever.
9651 if (!EnableFiniteLoopControl || !ControllingFiniteLoop ||
9652 !isLoopInvariant(RHS, L))
9653 break;
9655 [[fallthrough]];
9656 case ICmpInst::ICMP_SGT:
9657 case ICmpInst::ICMP_UGT: { // while (X > Y)
9658 bool IsSigned = ICmpInst::isSigned(Pred);
9659 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsOnlyExit,
9660 AllowPredicates);
9661 if (EL.hasAnyInfo())
9662 return EL;
9663 break;
9664 }
9665 default:
9666 break;
9667 }
9668
9669 return getCouldNotCompute();
9670}
9671
9672ScalarEvolution::ExitLimit
9673ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
9674 SwitchInst *Switch,
9675 BasicBlock *ExitingBlock,
9676 bool ControlsOnlyExit) {
9677 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
9678
9679 // Give up if the exit is the default dest of a switch.
9680 if (Switch->getDefaultDest() == ExitingBlock)
9681 return getCouldNotCompute();
9682
9683 assert(L->contains(Switch->getDefaultDest()) &&
9684 "Default case must not exit the loop!");
9685 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
9686 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
9687
9688 // while (X != Y) --> while (X-Y != 0)
9689 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
9690 if (EL.hasAnyInfo())
9691 return EL;
9692
9693 return getCouldNotCompute();
9694}
9695
9696static ConstantInt *
9698 ScalarEvolution &SE) {
9699 const SCEV *InVal = SE.getConstant(C);
9700 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
9702 "Evaluation of SCEV at constant didn't fold correctly?");
9703 return cast<SCEVConstant>(Val)->getValue();
9704}
9705
9706ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
9707 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
9708 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
9709 if (!RHS)
9710 return getCouldNotCompute();
9711
9712 const BasicBlock *Latch = L->getLoopLatch();
9713 if (!Latch)
9714 return getCouldNotCompute();
9715
9716 const BasicBlock *Predecessor = L->getLoopPredecessor();
9717 if (!Predecessor)
9718 return getCouldNotCompute();
9719
9720 // Return true if V is of the form "LHS `shift_op` <positive constant>".
9721 // Return LHS in OutLHS, shift_op in OutOpCode, and the shift amount in
9722 // OutShiftAmt.
9723 auto MatchPositiveShift = [](Value *V, Value *&OutLHS,
9724 Instruction::BinaryOps &OutOpCode,
9725 unsigned &OutShiftAmt) {
9726 using namespace PatternMatch;
9727
9728 ConstantInt *ShiftAmt;
9729 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9730 OutOpCode = Instruction::LShr;
9731 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9732 OutOpCode = Instruction::AShr;
9733 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
9734 OutOpCode = Instruction::Shl;
9735 else
9736 return false;
9737
9738 uint64_t Amt = ShiftAmt->getValue().getLimitedValue();
9739 if (Amt == 0 || Amt >= OutLHS->getType()->getScalarSizeInBits())
9740 return false;
9741 OutShiftAmt = Amt;
9742 return true;
9743 };
9744
9745 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
9746 //
9747 // loop:
9748 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
9749 // %iv.shifted = lshr i32 %iv, <positive constant>
9750 //
9751 // Return true on a successful match. Return the corresponding PHI node (%iv
9752 // above) in PNOut, the opcode of the shift operation in OpCodeOut, and the
9753 // shift amount in ShiftAmtOut.
9754 auto MatchShiftRecurrence = [&](Value *V, PHINode *&PNOut,
9755 Instruction::BinaryOps &OpCodeOut,
9756 unsigned &ShiftAmtOut) {
9757 std::optional<Instruction::BinaryOps> PostShiftOpCode;
9758
9759 {
9761 Value *V;
9762 unsigned Amt;
9763
9764 // If we encounter a shift instruction, "peel off" the shift operation,
9765 // and remember that we did so. Later when we inspect %iv's backedge
9766 // value, we will make sure that the backedge value uses the same
9767 // operation.
9768 //
9769 // Note: the peeled shift operation does not have to be the same
9770 // instruction as the one feeding into the PHI's backedge value. We only
9771 // really care about it being the same *kind* of shift instruction --
9772 // that's all that is required for our later inferences to hold.
9773 if (MatchPositiveShift(LHS, V, OpC, Amt)) {
9774 PostShiftOpCode = OpC;
9775 LHS = V;
9776 }
9777 }
9778
9779 PNOut = dyn_cast<PHINode>(LHS);
9780 if (!PNOut || PNOut->getParent() != L->getHeader())
9781 return false;
9782
9783 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
9784 Value *OpLHS;
9785
9786 return
9787 // The backedge value for the PHI node must be a shift by a positive
9788 // amount
9789 MatchPositiveShift(BEValue, OpLHS, OpCodeOut, ShiftAmtOut) &&
9790
9791 // of the PHI node itself
9792 OpLHS == PNOut &&
9793
9794 // and the kind of shift should be match the kind of shift we peeled
9795 // off, if any.
9796 (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
9797 };
9798
9799 PHINode *PN;
9801 unsigned ShiftAmt;
9802 if (!MatchShiftRecurrence(LHS, PN, OpCode, ShiftAmt))
9803 return getCouldNotCompute();
9804
9805 const DataLayout &DL = getDataLayout();
9806
9807 // The key rationale for this optimization is that for some kinds of shift
9808 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
9809 // within a finite number of iterations. If the condition guarding the
9810 // backedge (in the sense that the backedge is taken if the condition is true)
9811 // is false for the value the shift recurrence stabilizes to, then we know
9812 // that the backedge is taken only a finite number of times.
9813
9814 ConstantInt *StableValue = nullptr;
9815 switch (OpCode) {
9816 default:
9817 llvm_unreachable("Impossible case!");
9818
9819 case Instruction::AShr: {
9820 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
9821 // bitwidth(K) iterations.
9822 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
9823 KnownBits Known = computeKnownBits(FirstValue, DL, &AC,
9824 Predecessor->getTerminator(), &DT);
9825 auto *Ty = cast<IntegerType>(RHS->getType());
9826 if (Known.isNonNegative())
9827 StableValue = ConstantInt::get(Ty, 0);
9828 else if (Known.isNegative())
9829 StableValue = ConstantInt::get(Ty, -1, true);
9830 else
9831 return getCouldNotCompute();
9832
9833 break;
9834 }
9835 case Instruction::LShr:
9836 case Instruction::Shl:
9837 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
9838 // stabilize to 0 in at most bitwidth(K) iterations.
9839 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
9840 break;
9841 }
9842
9843 auto *Result =
9844 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
9845 assert(Result->getType()->isIntegerTy(1) &&
9846 "Otherwise cannot be an operand to a branch instruction");
9847
9848 if (Result->isNullValue()) {
9849 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
9850 unsigned MaxBTC = BitWidth;
9851
9852 // For right-shift recurrences (lshr/ashr with non-negative start), we can
9853 // compute a tighter max backedge-taken count from the range of the start
9854 // value. After k shifts of ShiftAmt, value = start >> (k * ShiftAmt).
9855 // The value reaches 0 (the stable value) when k * ShiftAmt >=
9856 // activeBits(start), so max BTC = ceil(activeBits(maxStart) / ShiftAmt).
9857 if (OpCode == Instruction::LShr || OpCode == Instruction::AShr) {
9858 Value *StartValue = PN->getIncomingValueForBlock(Predecessor);
9859 const SCEV *StartSCEV = getSCEV(StartValue);
9860 APInt MaxStart = getUnsignedRangeMax(StartSCEV);
9861 if (MaxStart.isStrictlyPositive()) {
9862 unsigned ActiveBits = MaxStart.getActiveBits();
9863 unsigned RangeBTC = divideCeil(ActiveBits, ShiftAmt);
9864 MaxBTC = std::min(MaxBTC, RangeBTC);
9865 }
9866 }
9867
9868 const SCEV *UpperBound =
9870 return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
9871 }
9872
9873 return getCouldNotCompute();
9874}
9875
9876/// Return true if we can constant fold an instruction of the specified type,
9877/// assuming that all operands were constants.
9878static bool CanConstantFold(const Instruction *I) {
9882 return true;
9883
9884 if (const CallInst *CI = dyn_cast<CallInst>(I))
9885 if (const Function *F = CI->getCalledFunction())
9886 return canConstantFoldCallTo(CI, F);
9887 return false;
9888}
9889
9890/// Determine whether this instruction can constant evolve within this loop
9891/// assuming its operands can all constant evolve.
9892static bool canConstantEvolve(Instruction *I, const Loop *L) {
9893 // An instruction outside of the loop can't be derived from a loop PHI.
9894 if (!L->contains(I)) return false;
9895
9896 if (isa<PHINode>(I)) {
9897 // We don't currently keep track of the control flow needed to evaluate
9898 // PHIs, so we cannot handle PHIs inside of loops.
9899 return L->getHeader() == I->getParent();
9900 }
9901
9902 // If we won't be able to constant fold this expression even if the operands
9903 // are constants, bail early.
9904 return CanConstantFold(I);
9905}
9906
9907/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
9908/// recursing through each instruction operand until reaching a loop header phi.
9909static PHINode *
9912 unsigned Depth) {
9914 return nullptr;
9915
9916 // Otherwise, we can evaluate this instruction if all of its operands are
9917 // constant or derived from a PHI node themselves.
9918 PHINode *PHI = nullptr;
9919 for (Value *Op : UseInst->operands()) {
9920 if (isa<Constant>(Op)) continue;
9921
9923 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
9924
9925 PHINode *P = dyn_cast<PHINode>(OpInst);
9926 if (!P)
9927 // If this operand is already visited, reuse the prior result.
9928 // We may have P != PHI if this is the deepest point at which the
9929 // inconsistent paths meet.
9930 P = PHIMap.lookup(OpInst);
9931 if (!P) {
9932 // Recurse and memoize the results, whether a phi is found or not.
9933 // This recursive call invalidates pointers into PHIMap.
9934 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
9935 PHIMap[OpInst] = P;
9936 }
9937 if (!P)
9938 return nullptr; // Not evolving from PHI
9939 if (PHI && PHI != P)
9940 return nullptr; // Evolving from multiple different PHIs.
9941 PHI = P;
9942 }
9943 // This is a expression evolving from a constant PHI!
9944 return PHI;
9945}
9946
9947/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
9948/// in the loop that V is derived from. We allow arbitrary operations along the
9949/// way, but the operands of an operation must either be constants or a value
9950/// derived from a constant PHI. If this expression does not fit with these
9951/// constraints, return null.
9954 if (!I || !canConstantEvolve(I, L)) return nullptr;
9955
9956 if (PHINode *PN = dyn_cast<PHINode>(I))
9957 return PN;
9958
9959 // Record non-constant instructions contained by the loop.
9961 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
9962}
9963
9964/// EvaluateExpression - Given an expression that passes the
9965/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
9966/// in the loop has the value PHIVal. If we can't fold this expression for some
9967/// reason, return null.
9970 const DataLayout &DL,
9971 const TargetLibraryInfo *TLI) {
9972 // Convenient constant check, but redundant for recursive calls.
9973 if (Constant *C = dyn_cast<Constant>(V)) return C;
9975 if (!I) return nullptr;
9976
9977 if (Constant *C = Vals.lookup(I)) return C;
9978
9979 // An instruction inside the loop depends on a value outside the loop that we
9980 // weren't given a mapping for, or a value such as a call inside the loop.
9981 if (!canConstantEvolve(I, L)) return nullptr;
9982
9983 // An unmapped PHI can be due to a branch or another loop inside this loop,
9984 // or due to this not being the initial iteration through a loop where we
9985 // couldn't compute the evolution of this particular PHI last time.
9986 if (isa<PHINode>(I)) return nullptr;
9987
9988 std::vector<Constant*> Operands(I->getNumOperands());
9989
9990 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
9991 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
9992 if (!Operand) {
9993 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
9994 if (!Operands[i]) return nullptr;
9995 continue;
9996 }
9997 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
9998 Vals[Operand] = C;
9999 if (!C) return nullptr;
10000 Operands[i] = C;
10001 }
10002
10003 return ConstantFoldInstOperands(I, Operands, DL, TLI,
10004 /*AllowNonDeterministic=*/false);
10005}
10006
10007
10008// If every incoming value to PN except the one for BB is a specific Constant,
10009// return that, else return nullptr.
10011 Constant *IncomingVal = nullptr;
10012
10013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10014 if (PN->getIncomingBlock(i) == BB)
10015 continue;
10016
10017 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
10018 if (!CurrentVal)
10019 return nullptr;
10020
10021 if (IncomingVal != CurrentVal) {
10022 if (IncomingVal)
10023 return nullptr;
10024 IncomingVal = CurrentVal;
10025 }
10026 }
10027
10028 return IncomingVal;
10029}
10030
10031/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
10032/// in the header of its containing loop, we know the loop executes a
10033/// constant number of times, and the PHI node is just a recurrence
10034/// involving constants, fold it.
10035Constant *
10036ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
10037 const APInt &BEs,
10038 const Loop *L) {
10039 auto [I, Inserted] = ConstantEvolutionLoopExitValue.try_emplace(PN);
10040 if (!Inserted)
10041 return I->second;
10042
10044 return nullptr; // Not going to evaluate it.
10045
10046 Constant *&RetVal = I->second;
10047
10048 DenseMap<Instruction *, Constant *> CurrentIterVals;
10049 BasicBlock *Header = L->getHeader();
10050 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10051
10052 BasicBlock *Latch = L->getLoopLatch();
10053 if (!Latch)
10054 return nullptr;
10055
10056 for (PHINode &PHI : Header->phis()) {
10057 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10058 CurrentIterVals[&PHI] = StartCST;
10059 }
10060 if (!CurrentIterVals.count(PN))
10061 return RetVal = nullptr;
10062
10063 Value *BEValue = PN->getIncomingValueForBlock(Latch);
10064
10065 // Execute the loop symbolically to determine the exit value.
10066 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
10067 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
10068
10069 unsigned NumIterations = BEs.getZExtValue(); // must be in range
10070 unsigned IterationNum = 0;
10071 const DataLayout &DL = getDataLayout();
10072 for (; ; ++IterationNum) {
10073 if (IterationNum == NumIterations)
10074 return RetVal = CurrentIterVals[PN]; // Got exit value!
10075
10076 // Compute the value of the PHIs for the next iteration.
10077 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
10078 DenseMap<Instruction *, Constant *> NextIterVals;
10079 Constant *NextPHI =
10080 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10081 if (!NextPHI)
10082 return nullptr; // Couldn't evaluate!
10083 NextIterVals[PN] = NextPHI;
10084
10085 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
10086
10087 // Also evaluate the other PHI nodes. However, we don't get to stop if we
10088 // cease to be able to evaluate one of them or if they stop evolving,
10089 // because that doesn't necessarily prevent us from computing PN.
10091 for (const auto &I : CurrentIterVals) {
10092 PHINode *PHI = dyn_cast<PHINode>(I.first);
10093 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
10094 PHIsToCompute.emplace_back(PHI, I.second);
10095 }
10096 // We use two distinct loops because EvaluateExpression may invalidate any
10097 // iterators into CurrentIterVals.
10098 for (const auto &I : PHIsToCompute) {
10099 PHINode *PHI = I.first;
10100 Constant *&NextPHI = NextIterVals[PHI];
10101 if (!NextPHI) { // Not already computed.
10102 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10103 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10104 }
10105 if (NextPHI != I.second)
10106 StoppedEvolving = false;
10107 }
10108
10109 // If all entries in CurrentIterVals == NextIterVals then we can stop
10110 // iterating, the loop can't continue to change.
10111 if (StoppedEvolving)
10112 return RetVal = CurrentIterVals[PN];
10113
10114 CurrentIterVals.swap(NextIterVals);
10115 }
10116}
10117
10118const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
10119 Value *Cond,
10120 bool ExitWhen) {
10121 PHINode *PN = getConstantEvolvingPHI(Cond, L);
10122 if (!PN) return getCouldNotCompute();
10123
10124 // If the loop is canonicalized, the PHI will have exactly two entries.
10125 // That's the only form we support here.
10126 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
10127
10128 DenseMap<Instruction *, Constant *> CurrentIterVals;
10129 BasicBlock *Header = L->getHeader();
10130 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
10131
10132 BasicBlock *Latch = L->getLoopLatch();
10133 assert(Latch && "Should follow from NumIncomingValues == 2!");
10134
10135 for (PHINode &PHI : Header->phis()) {
10136 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
10137 CurrentIterVals[&PHI] = StartCST;
10138 }
10139 if (!CurrentIterVals.count(PN))
10140 return getCouldNotCompute();
10141
10142 // Okay, we find a PHI node that defines the trip count of this loop. Execute
10143 // the loop symbolically to determine when the condition gets a value of
10144 // "ExitWhen".
10145 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
10146 const DataLayout &DL = getDataLayout();
10147 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
10148 auto *CondVal = dyn_cast_or_null<ConstantInt>(
10149 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
10150
10151 // Couldn't symbolically evaluate.
10152 if (!CondVal) return getCouldNotCompute();
10153
10154 if (CondVal->getValue() == uint64_t(ExitWhen)) {
10155 ++NumBruteForceTripCountsComputed;
10156 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
10157 }
10158
10159 // Update all the PHI nodes for the next iteration.
10160 DenseMap<Instruction *, Constant *> NextIterVals;
10161
10162 // Create a list of which PHIs we need to compute. We want to do this before
10163 // calling EvaluateExpression on them because that may invalidate iterators
10164 // into CurrentIterVals.
10165 SmallVector<PHINode *, 8> PHIsToCompute;
10166 for (const auto &I : CurrentIterVals) {
10167 PHINode *PHI = dyn_cast<PHINode>(I.first);
10168 if (!PHI || PHI->getParent() != Header) continue;
10169 PHIsToCompute.push_back(PHI);
10170 }
10171 for (PHINode *PHI : PHIsToCompute) {
10172 Constant *&NextPHI = NextIterVals[PHI];
10173 if (NextPHI) continue; // Already computed!
10174
10175 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
10176 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
10177 }
10178 CurrentIterVals.swap(NextIterVals);
10179 }
10180
10181 // Too many iterations were needed to evaluate.
10182 return getCouldNotCompute();
10183}
10184
10185const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
10187 ValuesAtScopes[V];
10188 // Check to see if we've folded this expression at this loop before.
10189 for (auto &LS : Values)
10190 if (LS.first == L)
10191 return LS.second ? LS.second : V;
10192
10193 Values.emplace_back(L, nullptr);
10194
10195 // Otherwise compute it.
10196 const SCEV *C = computeSCEVAtScope(V, L);
10197 for (auto &LS : reverse(ValuesAtScopes[V]))
10198 if (LS.first == L) {
10199 LS.second = C;
10200 if (!isa<SCEVConstant>(C))
10201 ValuesAtScopesUsers[C].push_back({L, V});
10202 break;
10203 }
10204 return C;
10205}
10206
10207/// This builds up a Constant using the ConstantExpr interface. That way, we
10208/// will return Constants for objects which aren't represented by a
10209/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
10210/// Returns NULL if the SCEV isn't representable as a Constant.
10212 switch (V->getSCEVType()) {
10213 case scCouldNotCompute:
10214 case scAddRecExpr:
10215 case scVScale:
10216 return nullptr;
10217 case scConstant:
10218 return cast<SCEVConstant>(V)->getValue();
10219 case scUnknown:
10221 case scPtrToAddr: {
10223 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10224 return ConstantExpr::getPtrToAddr(CastOp, P2I->getType());
10225
10226 return nullptr;
10227 }
10228 case scPtrToInt: {
10230 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
10231 return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
10232
10233 return nullptr;
10234 }
10235 case scTruncate: {
10237 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
10238 return ConstantExpr::getTrunc(CastOp, ST->getType());
10239 return nullptr;
10240 }
10241 case scAddExpr: {
10242 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
10243 Constant *C = nullptr;
10244 for (const SCEV *Op : SA->operands()) {
10246 if (!OpC)
10247 return nullptr;
10248 if (!C) {
10249 C = OpC;
10250 continue;
10251 }
10252 assert(!C->getType()->isPointerTy() &&
10253 "Can only have one pointer, and it must be last");
10254 if (OpC->getType()->isPointerTy()) {
10255 // The offsets have been converted to bytes. We can add bytes using
10256 // an i8 GEP.
10257 C = ConstantExpr::getPtrAdd(OpC, C);
10258 } else {
10259 C = ConstantExpr::getAdd(C, OpC);
10260 }
10261 }
10262 return C;
10263 }
10264 case scMulExpr:
10265 case scSignExtend:
10266 case scZeroExtend:
10267 case scUDivExpr:
10268 case scSMaxExpr:
10269 case scUMaxExpr:
10270 case scSMinExpr:
10271 case scUMinExpr:
10273 return nullptr;
10274 }
10275 llvm_unreachable("Unknown SCEV kind!");
10276}
10277
10278const SCEV *ScalarEvolution::getWithOperands(const SCEV *S,
10279 SmallVectorImpl<SCEVUse> &NewOps) {
10280 switch (S->getSCEVType()) {
10281 case scTruncate:
10282 case scZeroExtend:
10283 case scSignExtend:
10284 case scPtrToAddr:
10285 case scPtrToInt:
10286 return getCastExpr(S->getSCEVType(), NewOps[0], S->getType());
10287 case scAddRecExpr: {
10288 auto *AddRec = cast<SCEVAddRecExpr>(S);
10289 return getAddRecExpr(NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags());
10290 }
10291 case scAddExpr:
10292 return getAddExpr(NewOps, cast<SCEVAddExpr>(S)->getNoWrapFlags());
10293 case scMulExpr:
10294 return getMulExpr(NewOps, cast<SCEVMulExpr>(S)->getNoWrapFlags());
10295 case scUDivExpr:
10296 return getUDivExpr(NewOps[0], NewOps[1]);
10297 case scUMaxExpr:
10298 case scSMaxExpr:
10299 case scUMinExpr:
10300 case scSMinExpr:
10301 return getMinMaxExpr(S->getSCEVType(), NewOps);
10303 return getSequentialMinMaxExpr(S->getSCEVType(), NewOps);
10304 case scConstant:
10305 case scVScale:
10306 case scUnknown:
10307 return S;
10308 case scCouldNotCompute:
10309 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10310 }
10311 llvm_unreachable("Unknown SCEV kind!");
10312}
10313
10314const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
10315 switch (V->getSCEVType()) {
10316 case scConstant:
10317 case scVScale:
10318 return V;
10319 case scAddRecExpr: {
10320 // If this is a loop recurrence for a loop that does not contain L, then we
10321 // are dealing with the final value computed by the loop.
10322 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
10323 // First, attempt to evaluate each operand.
10324 // Avoid performing the look-up in the common case where the specified
10325 // expression has no loop-variant portions.
10326 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
10327 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
10328 if (OpAtScope == AddRec->getOperand(i))
10329 continue;
10330
10331 // Okay, at least one of these operands is loop variant but might be
10332 // foldable. Build a new instance of the folded commutative expression.
10334 NewOps.reserve(AddRec->getNumOperands());
10335 append_range(NewOps, AddRec->operands().take_front(i));
10336 NewOps.push_back(OpAtScope);
10337 for (++i; i != e; ++i)
10338 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
10339
10340 const SCEV *FoldedRec = getAddRecExpr(
10341 NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
10342 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
10343 // The addrec may be folded to a nonrecurrence, for example, if the
10344 // induction variable is multiplied by zero after constant folding. Go
10345 // ahead and return the folded value.
10346 if (!AddRec)
10347 return FoldedRec;
10348 break;
10349 }
10350
10351 // If the scope is outside the addrec's loop, evaluate it by using the
10352 // loop exit value of the addrec.
10353 if (!AddRec->getLoop()->contains(L)) {
10354 // To evaluate this recurrence, we need to know how many times the AddRec
10355 // loop iterates. Compute this now.
10356 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
10357 if (BackedgeTakenCount == getCouldNotCompute())
10358 return AddRec;
10359
10360 // Then, evaluate the AddRec.
10361 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
10362 }
10363
10364 return AddRec;
10365 }
10366 case scTruncate:
10367 case scZeroExtend:
10368 case scSignExtend:
10369 case scPtrToAddr:
10370 case scPtrToInt:
10371 case scAddExpr:
10372 case scMulExpr:
10373 case scUDivExpr:
10374 case scUMaxExpr:
10375 case scSMaxExpr:
10376 case scUMinExpr:
10377 case scSMinExpr:
10378 case scSequentialUMinExpr: {
10379 ArrayRef<SCEVUse> Ops = V->operands();
10380 // Avoid performing the look-up in the common case where the specified
10381 // expression has no loop-variant portions.
10382 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
10383 const SCEV *OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10384 if (OpAtScope != Ops[i].getPointer()) {
10385 // Okay, at least one of these operands is loop variant but might be
10386 // foldable. Build a new instance of the folded commutative expression.
10388 NewOps.reserve(Ops.size());
10389 append_range(NewOps, Ops.take_front(i));
10390 NewOps.push_back(OpAtScope);
10391
10392 for (++i; i != e; ++i) {
10393 OpAtScope = getSCEVAtScope(Ops[i].getPointer(), L);
10394 NewOps.push_back(OpAtScope);
10395 }
10396
10397 return getWithOperands(V, NewOps);
10398 }
10399 }
10400 // If we got here, all operands are loop invariant.
10401 return V;
10402 }
10403 case scUnknown: {
10404 // If this instruction is evolved from a constant-evolving PHI, compute the
10405 // exit value from the loop without using SCEVs.
10406 const SCEVUnknown *SU = cast<SCEVUnknown>(V);
10408 if (!I)
10409 return V; // This is some other type of SCEVUnknown, just return it.
10410
10411 if (PHINode *PN = dyn_cast<PHINode>(I)) {
10412 const Loop *CurrLoop = this->LI[I->getParent()];
10413 // Looking for loop exit value.
10414 if (CurrLoop && CurrLoop->getParentLoop() == L &&
10415 PN->getParent() == CurrLoop->getHeader()) {
10416 // Okay, there is no closed form solution for the PHI node. Check
10417 // to see if the loop that contains it has a known backedge-taken
10418 // count. If so, we may be able to force computation of the exit
10419 // value.
10420 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
10421 // This trivial case can show up in some degenerate cases where
10422 // the incoming IR has not yet been fully simplified.
10423 if (BackedgeTakenCount->isZero()) {
10424 Value *InitValue = nullptr;
10425 bool MultipleInitValues = false;
10426 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
10427 if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
10428 if (!InitValue)
10429 InitValue = PN->getIncomingValue(i);
10430 else if (InitValue != PN->getIncomingValue(i)) {
10431 MultipleInitValues = true;
10432 break;
10433 }
10434 }
10435 }
10436 if (!MultipleInitValues && InitValue)
10437 return getSCEV(InitValue);
10438 }
10439 // Do we have a loop invariant value flowing around the backedge
10440 // for a loop which must execute the backedge?
10441 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
10442 isKnownNonZero(BackedgeTakenCount) &&
10443 PN->getNumIncomingValues() == 2) {
10444
10445 unsigned InLoopPred =
10446 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
10447 Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
10448 if (CurrLoop->isLoopInvariant(BackedgeVal))
10449 return getSCEV(BackedgeVal);
10450 }
10451 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
10452 // Okay, we know how many times the containing loop executes. If
10453 // this is a constant evolving PHI node, get the final value at
10454 // the specified iteration number.
10455 Constant *RV =
10456 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
10457 if (RV)
10458 return getSCEV(RV);
10459 }
10460 }
10461 }
10462
10463 // Okay, this is an expression that we cannot symbolically evaluate
10464 // into a SCEV. Check to see if it's possible to symbolically evaluate
10465 // the arguments into constants, and if so, try to constant propagate the
10466 // result. This is particularly useful for computing loop exit values.
10467 if (!CanConstantFold(I))
10468 return V; // This is some other type of SCEVUnknown, just return it.
10469
10470 SmallVector<Constant *, 4> Operands;
10471 Operands.reserve(I->getNumOperands());
10472 bool MadeImprovement = false;
10473 for (Value *Op : I->operands()) {
10474 if (Constant *C = dyn_cast<Constant>(Op)) {
10475 Operands.push_back(C);
10476 continue;
10477 }
10478
10479 // If any of the operands is non-constant and if they are
10480 // non-integer and non-pointer, don't even try to analyze them
10481 // with scev techniques.
10482 if (!isSCEVable(Op->getType()))
10483 return V;
10484
10485 const SCEV *OrigV = getSCEV(Op);
10486 const SCEV *OpV = getSCEVAtScope(OrigV, L);
10487 MadeImprovement |= OrigV != OpV;
10488
10490 if (!C)
10491 return V;
10492 assert(C->getType() == Op->getType() && "Type mismatch");
10493 Operands.push_back(C);
10494 }
10495
10496 // Check to see if getSCEVAtScope actually made an improvement.
10497 if (!MadeImprovement)
10498 return V; // This is some other type of SCEVUnknown, just return it.
10499
10500 Constant *C = nullptr;
10501 const DataLayout &DL = getDataLayout();
10502 C = ConstantFoldInstOperands(I, Operands, DL, &TLI,
10503 /*AllowNonDeterministic=*/false);
10504 if (!C)
10505 return V;
10506 return getSCEV(C);
10507 }
10508 case scCouldNotCompute:
10509 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
10510 }
10511 llvm_unreachable("Unknown SCEV type!");
10512}
10513
10515 return getSCEVAtScope(getSCEV(V), L);
10516}
10517
10518const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
10520 return stripInjectiveFunctions(ZExt->getOperand());
10522 return stripInjectiveFunctions(SExt->getOperand());
10523 return S;
10524}
10525
10526/// Finds the minimum unsigned root of the following equation:
10527///
10528/// A * X = B (mod N)
10529///
10530/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
10531/// A and B isn't important.
10532///
10533/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
10534static const SCEV *
10537 ScalarEvolution &SE, const Loop *L) {
10538 uint32_t BW = A.getBitWidth();
10539 assert(BW == SE.getTypeSizeInBits(B->getType()));
10540 assert(A != 0 && "A must be non-zero.");
10541
10542 // 1. D = gcd(A, N)
10543 //
10544 // The gcd of A and N may have only one prime factor: 2. The number of
10545 // trailing zeros in A is its multiplicity
10546 uint32_t Mult2 = A.countr_zero();
10547 // D = 2^Mult2
10548
10549 // 2. Check if B is divisible by D.
10550 //
10551 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
10552 // is not less than multiplicity of this prime factor for D.
10553 unsigned MinTZ = SE.getMinTrailingZeros(B);
10554 // Try again with the terminator of the loop predecessor for context-specific
10555 // result, if MinTZ s too small.
10556 if (MinTZ < Mult2 && L->getLoopPredecessor())
10557 MinTZ = SE.getMinTrailingZeros(B, L->getLoopPredecessor()->getTerminator());
10558 if (MinTZ < Mult2) {
10559 // Check if we can prove there's no remainder using URem.
10560 const SCEV *URem =
10561 SE.getURemExpr(B, SE.getConstant(APInt::getOneBitSet(BW, Mult2)));
10562 const SCEV *Zero = SE.getZero(B->getType());
10563 if (!SE.isKnownPredicate(CmpInst::ICMP_EQ, URem, Zero)) {
10564 // Try to add a predicate ensuring B is a multiple of 1 << Mult2.
10565 if (!Predicates)
10566 return SE.getCouldNotCompute();
10567
10568 // Avoid adding a predicate that is known to be false.
10569 if (SE.isKnownPredicate(CmpInst::ICMP_NE, URem, Zero))
10570 return SE.getCouldNotCompute();
10571 Predicates->push_back(SE.getEqualPredicate(URem, Zero));
10572 }
10573 }
10574
10575 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
10576 // modulo (N / D).
10577 //
10578 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
10579 // (N / D) in general. The inverse itself always fits into BW bits, though,
10580 // so we immediately truncate it.
10581 APInt AD = A.lshr(Mult2).trunc(BW - Mult2); // AD = A / D
10582 APInt I = AD.multiplicativeInverse().zext(BW);
10583
10584 // 4. Compute the minimum unsigned root of the equation:
10585 // I * (B / D) mod (N / D)
10586 // To simplify the computation, we factor out the divide by D:
10587 // (I * B mod N) / D
10588 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
10589 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
10590}
10591
10592/// For a given quadratic addrec, generate coefficients of the corresponding
10593/// quadratic equation, multiplied by a common value to ensure that they are
10594/// integers.
10595/// The returned value is a tuple { A, B, C, M, BitWidth }, where
10596/// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
10597/// were multiplied by, and BitWidth is the bit width of the original addrec
10598/// coefficients.
10599/// This function returns std::nullopt if the addrec coefficients are not
10600/// compile- time constants.
10601static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
10603 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
10604 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
10605 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
10606 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
10607 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
10608 << *AddRec << '\n');
10609
10610 // We currently can only solve this if the coefficients are constants.
10611 if (!LC || !MC || !NC) {
10612 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
10613 return std::nullopt;
10614 }
10615
10616 APInt L = LC->getAPInt();
10617 APInt M = MC->getAPInt();
10618 APInt N = NC->getAPInt();
10619 assert(!N.isZero() && "This is not a quadratic addrec");
10620
10621 unsigned BitWidth = LC->getAPInt().getBitWidth();
10622 unsigned NewWidth = BitWidth + 1;
10623 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
10624 << BitWidth << '\n');
10625 // The sign-extension (as opposed to a zero-extension) here matches the
10626 // extension used in SolveQuadraticEquationWrap (with the same motivation).
10627 N = N.sext(NewWidth);
10628 M = M.sext(NewWidth);
10629 L = L.sext(NewWidth);
10630
10631 // The increments are M, M+N, M+2N, ..., so the accumulated values are
10632 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
10633 // L+M, L+2M+N, L+3M+3N, ...
10634 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
10635 //
10636 // The equation Acc = 0 is then
10637 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
10638 // In a quadratic form it becomes:
10639 // N n^2 + (2M-N) n + 2L = 0.
10640
10641 APInt A = N;
10642 APInt B = 2 * M - A;
10643 APInt C = 2 * L;
10644 APInt T = APInt(NewWidth, 2);
10645 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
10646 << "x + " << C << ", coeff bw: " << NewWidth
10647 << ", multiplied by " << T << '\n');
10648 return std::make_tuple(A, B, C, T, BitWidth);
10649}
10650
10651/// Helper function to compare optional APInts:
10652/// (a) if X and Y both exist, return min(X, Y),
10653/// (b) if neither X nor Y exist, return std::nullopt,
10654/// (c) if exactly one of X and Y exists, return that value.
10655static std::optional<APInt> MinOptional(std::optional<APInt> X,
10656 std::optional<APInt> Y) {
10657 if (X && Y) {
10658 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
10659 APInt XW = X->sext(W);
10660 APInt YW = Y->sext(W);
10661 return XW.slt(YW) ? *X : *Y;
10662 }
10663 if (!X && !Y)
10664 return std::nullopt;
10665 return X ? *X : *Y;
10666}
10667
10668/// Helper function to truncate an optional APInt to a given BitWidth.
10669/// When solving addrec-related equations, it is preferable to return a value
10670/// that has the same bit width as the original addrec's coefficients. If the
10671/// solution fits in the original bit width, truncate it (except for i1).
10672/// Returning a value of a different bit width may inhibit some optimizations.
10673///
10674/// In general, a solution to a quadratic equation generated from an addrec
10675/// may require BW+1 bits, where BW is the bit width of the addrec's
10676/// coefficients. The reason is that the coefficients of the quadratic
10677/// equation are BW+1 bits wide (to avoid truncation when converting from
10678/// the addrec to the equation).
10679static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
10680 unsigned BitWidth) {
10681 if (!X)
10682 return std::nullopt;
10683 unsigned W = X->getBitWidth();
10685 return X->trunc(BitWidth);
10686 return X;
10687}
10688
10689/// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
10690/// iterations. The values L, M, N are assumed to be signed, and they
10691/// should all have the same bit widths.
10692/// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
10693/// where BW is the bit width of the addrec's coefficients.
10694/// If the calculated value is a BW-bit integer (for BW > 1), it will be
10695/// returned as such, otherwise the bit width of the returned value may
10696/// be greater than BW.
10697///
10698/// This function returns std::nullopt if
10699/// (a) the addrec coefficients are not constant, or
10700/// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
10701/// like x^2 = 5, no integer solutions exist, in other cases an integer
10702/// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
10703static std::optional<APInt>
10705 APInt A, B, C, M;
10706 unsigned BitWidth;
10707 auto T = GetQuadraticEquation(AddRec);
10708 if (!T)
10709 return std::nullopt;
10710
10711 std::tie(A, B, C, M, BitWidth) = *T;
10712 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
10713 std::optional<APInt> X =
10715 if (!X)
10716 return std::nullopt;
10717
10718 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
10719 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
10720 if (!V->isZero())
10721 return std::nullopt;
10722
10723 return TruncIfPossible(X, BitWidth);
10724}
10725
10726/// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
10727/// iterations. The values M, N are assumed to be signed, and they
10728/// should all have the same bit widths.
10729/// Find the least n such that c(n) does not belong to the given range,
10730/// while c(n-1) does.
10731///
10732/// This function returns std::nullopt if
10733/// (a) the addrec coefficients are not constant, or
10734/// (b) SolveQuadraticEquationWrap was unable to find a solution for the
10735/// bounds of the range.
10736static std::optional<APInt>
10738 const ConstantRange &Range, ScalarEvolution &SE) {
10739 assert(AddRec->getOperand(0)->isZero() &&
10740 "Starting value of addrec should be 0");
10741 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
10742 << Range << ", addrec " << *AddRec << '\n');
10743 // This case is handled in getNumIterationsInRange. Here we can assume that
10744 // we start in the range.
10745 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
10746 "Addrec's initial value should be in range");
10747
10748 APInt A, B, C, M;
10749 unsigned BitWidth;
10750 auto T = GetQuadraticEquation(AddRec);
10751 if (!T)
10752 return std::nullopt;
10753
10754 // Be careful about the return value: there can be two reasons for not
10755 // returning an actual number. First, if no solutions to the equations
10756 // were found, and second, if the solutions don't leave the given range.
10757 // The first case means that the actual solution is "unknown", the second
10758 // means that it's known, but not valid. If the solution is unknown, we
10759 // cannot make any conclusions.
10760 // Return a pair: the optional solution and a flag indicating if the
10761 // solution was found.
10762 auto SolveForBoundary =
10763 [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
10764 // Solve for signed overflow and unsigned overflow, pick the lower
10765 // solution.
10766 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
10767 << Bound << " (before multiplying by " << M << ")\n");
10768 Bound *= M; // The quadratic equation multiplier.
10769
10770 std::optional<APInt> SO;
10771 if (BitWidth > 1) {
10772 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10773 "signed overflow\n");
10775 }
10776 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
10777 "unsigned overflow\n");
10778 std::optional<APInt> UO =
10780
10781 auto LeavesRange = [&] (const APInt &X) {
10782 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
10783 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
10784 if (Range.contains(V0->getValue()))
10785 return false;
10786 // X should be at least 1, so X-1 is non-negative.
10787 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
10789 if (Range.contains(V1->getValue()))
10790 return true;
10791 return false;
10792 };
10793
10794 // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
10795 // can be a solution, but the function failed to find it. We cannot treat it
10796 // as "no solution".
10797 if (!SO || !UO)
10798 return {std::nullopt, false};
10799
10800 // Check the smaller value first to see if it leaves the range.
10801 // At this point, both SO and UO must have values.
10802 std::optional<APInt> Min = MinOptional(SO, UO);
10803 if (LeavesRange(*Min))
10804 return { Min, true };
10805 std::optional<APInt> Max = Min == SO ? UO : SO;
10806 if (LeavesRange(*Max))
10807 return { Max, true };
10808
10809 // Solutions were found, but were eliminated, hence the "true".
10810 return {std::nullopt, true};
10811 };
10812
10813 std::tie(A, B, C, M, BitWidth) = *T;
10814 // Lower bound is inclusive, subtract 1 to represent the exiting value.
10815 APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
10816 APInt Upper = Range.getUpper().sext(A.getBitWidth());
10817 auto SL = SolveForBoundary(Lower);
10818 auto SU = SolveForBoundary(Upper);
10819 // If any of the solutions was unknown, no meaninigful conclusions can
10820 // be made.
10821 if (!SL.second || !SU.second)
10822 return std::nullopt;
10823
10824 // Claim: The correct solution is not some value between Min and Max.
10825 //
10826 // Justification: Assuming that Min and Max are different values, one of
10827 // them is when the first signed overflow happens, the other is when the
10828 // first unsigned overflow happens. Crossing the range boundary is only
10829 // possible via an overflow (treating 0 as a special case of it, modeling
10830 // an overflow as crossing k*2^W for some k).
10831 //
10832 // The interesting case here is when Min was eliminated as an invalid
10833 // solution, but Max was not. The argument is that if there was another
10834 // overflow between Min and Max, it would also have been eliminated if
10835 // it was considered.
10836 //
10837 // For a given boundary, it is possible to have two overflows of the same
10838 // type (signed/unsigned) without having the other type in between: this
10839 // can happen when the vertex of the parabola is between the iterations
10840 // corresponding to the overflows. This is only possible when the two
10841 // overflows cross k*2^W for the same k. In such case, if the second one
10842 // left the range (and was the first one to do so), the first overflow
10843 // would have to enter the range, which would mean that either we had left
10844 // the range before or that we started outside of it. Both of these cases
10845 // are contradictions.
10846 //
10847 // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
10848 // solution is not some value between the Max for this boundary and the
10849 // Min of the other boundary.
10850 //
10851 // Justification: Assume that we had such Max_A and Min_B corresponding
10852 // to range boundaries A and B and such that Max_A < Min_B. If there was
10853 // a solution between Max_A and Min_B, it would have to be caused by an
10854 // overflow corresponding to either A or B. It cannot correspond to B,
10855 // since Min_B is the first occurrence of such an overflow. If it
10856 // corresponded to A, it would have to be either a signed or an unsigned
10857 // overflow that is larger than both eliminated overflows for A. But
10858 // between the eliminated overflows and this overflow, the values would
10859 // cover the entire value space, thus crossing the other boundary, which
10860 // is a contradiction.
10861
10862 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
10863}
10864
10865ScalarEvolution::ExitLimit ScalarEvolution::howFarToZero(const SCEV *V,
10866 const Loop *L,
10867 bool ControlsOnlyExit,
10868 bool AllowPredicates) {
10869
10870 // This is only used for loops with a "x != y" exit test. The exit condition
10871 // is now expressed as a single expression, V = x-y. So the exit test is
10872 // effectively V != 0. We know and take advantage of the fact that this
10873 // expression only being used in a comparison by zero context.
10874
10876 // If the value is a constant
10877 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
10878 // If the value is already zero, the branch will execute zero times.
10879 if (C->getValue()->isZero()) return C;
10880 return getCouldNotCompute(); // Otherwise it will loop infinitely.
10881 }
10882
10883 const SCEVAddRecExpr *AddRec =
10884 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
10885
10886 if (!AddRec && AllowPredicates)
10887 // Try to make this an AddRec using runtime tests, in the first X
10888 // iterations of this loop, where X is the SCEV expression found by the
10889 // algorithm below.
10890 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
10891
10892 if (!AddRec || AddRec->getLoop() != L)
10893 return getCouldNotCompute();
10894
10895 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
10896 // the quadratic equation to solve it.
10897 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
10898 // We can only use this value if the chrec ends up with an exact zero
10899 // value at this index. When solving for "X*X != 5", for example, we
10900 // should not accept a root of 2.
10901 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
10902 const auto *R = cast<SCEVConstant>(getConstant(*S));
10903 return ExitLimit(R, R, R, false, Predicates);
10904 }
10905 return getCouldNotCompute();
10906 }
10907
10908 // Otherwise we can only handle this if it is affine.
10909 if (!AddRec->isAffine())
10910 return getCouldNotCompute();
10911
10912 // If this is an affine expression, the execution count of this branch is
10913 // the minimum unsigned root of the following equation:
10914 //
10915 // Start + Step*N = 0 (mod 2^BW)
10916 //
10917 // equivalent to:
10918 //
10919 // Step*N = -Start (mod 2^BW)
10920 //
10921 // where BW is the common bit width of Start and Step.
10922
10923 // Get the initial value for the loop.
10924 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
10925 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
10926
10927 if (!isLoopInvariant(Step, L))
10928 return getCouldNotCompute();
10929
10930 LoopGuards Guards = LoopGuards::collect(L, *this);
10931 // Specialize step for this loop so we get context sensitive facts below.
10932 const SCEV *StepWLG = applyLoopGuards(Step, Guards);
10933
10934 // For positive steps (counting up until unsigned overflow):
10935 // N = -Start/Step (as unsigned)
10936 // For negative steps (counting down to zero):
10937 // N = Start/-Step
10938 // First compute the unsigned distance from zero in the direction of Step.
10939 bool CountDown = isKnownNegative(StepWLG);
10940 if (!CountDown && !isKnownNonNegative(StepWLG))
10941 return getCouldNotCompute();
10942
10943 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
10944 // Handle unitary steps, which cannot wraparound.
10945 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
10946 // N = Distance (as unsigned)
10947
10948 if (match(Step, m_CombineOr(m_scev_One(), m_scev_AllOnes()))) {
10949 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, Guards));
10950 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
10951
10952 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
10953 // we end up with a loop whose backedge-taken count is n - 1. Detect this
10954 // case, and see if we can improve the bound.
10955 //
10956 // Explicitly handling this here is necessary because getUnsignedRange
10957 // isn't context-sensitive; it doesn't know that we only care about the
10958 // range inside the loop.
10959 const SCEV *Zero = getZero(Distance->getType());
10960 const SCEV *One = getOne(Distance->getType());
10961 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
10962 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
10963 // If Distance + 1 doesn't overflow, we can compute the maximum distance
10964 // as "unsigned_max(Distance + 1) - 1".
10965 ConstantRange CR = getUnsignedRange(DistancePlusOne);
10966 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
10967 }
10968 return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
10969 Predicates);
10970 }
10971
10972 // If the condition controls loop exit (the loop exits only if the expression
10973 // is true) and the addition is no-wrap we can use unsigned divide to
10974 // compute the backedge count. In this case, the step may not divide the
10975 // distance, but we don't care because if the condition is "missed" the loop
10976 // will have undefined behavior due to wrapping.
10977 if (ControlsOnlyExit && AddRec->hasNoSelfWrap() &&
10978 loopHasNoAbnormalExits(AddRec->getLoop())) {
10979
10980 // If the stride is zero and the start is non-zero, the loop must be
10981 // infinite. In C++, most loops are finite by assumption, in which case the
10982 // step being zero implies UB must execute if the loop is entered.
10983 if (!(loopIsFiniteByAssumption(L) && isKnownNonZero(Start)) &&
10984 !isKnownNonZero(StepWLG))
10985 return getCouldNotCompute();
10986
10987 const SCEV *Exact =
10988 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
10989 const SCEV *ConstantMax = getCouldNotCompute();
10990 if (Exact != getCouldNotCompute()) {
10991 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, Guards));
10992 ConstantMax =
10994 }
10995 const SCEV *SymbolicMax =
10996 isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
10997 return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
10998 }
10999
11000 // Solve the general equation.
11001 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
11002 if (!StepC || StepC->getValue()->isZero())
11003 return getCouldNotCompute();
11004 const SCEV *E = SolveLinEquationWithOverflow(
11005 StepC->getAPInt(), getNegativeSCEV(Start),
11006 AllowPredicates ? &Predicates : nullptr, *this, L);
11007
11008 const SCEV *M = E;
11009 if (E != getCouldNotCompute()) {
11010 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, Guards));
11011 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
11012 }
11013 auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
11014 return ExitLimit(E, M, S, false, Predicates);
11015}
11016
11017ScalarEvolution::ExitLimit
11018ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
11019 // Loops that look like: while (X == 0) are very strange indeed. We don't
11020 // handle them yet except for the trivial case. This could be expanded in the
11021 // future as needed.
11022
11023 // If the value is a constant, check to see if it is known to be non-zero
11024 // already. If so, the backedge will execute zero times.
11025 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
11026 if (!C->getValue()->isZero())
11027 return getZero(C->getType());
11028 return getCouldNotCompute(); // Otherwise it will loop infinitely.
11029 }
11030
11031 // We could implement others, but I really doubt anyone writes loops like
11032 // this, and if they did, they would already be constant folded.
11033 return getCouldNotCompute();
11034}
11035
11036std::pair<const BasicBlock *, const BasicBlock *>
11037ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
11038 const {
11039 // If the block has a unique predecessor, then there is no path from the
11040 // predecessor to the block that does not go through the direct edge
11041 // from the predecessor to the block.
11042 if (const BasicBlock *Pred = BB->getSinglePredecessor())
11043 return {Pred, BB};
11044
11045 // A loop's header is defined to be a block that dominates the loop.
11046 // If the header has a unique predecessor outside the loop, it must be
11047 // a block that has exactly one successor that can reach the loop.
11048 if (const Loop *L = LI.getLoopFor(BB))
11049 return {L->getLoopPredecessor(), L->getHeader()};
11050
11051 return {nullptr, BB};
11052}
11053
11054/// SCEV structural equivalence is usually sufficient for testing whether two
11055/// expressions are equal, however for the purposes of looking for a condition
11056/// guarding a loop, it can be useful to be a little more general, since a
11057/// front-end may have replicated the controlling expression.
11058static bool HasSameValue(const SCEV *A, const SCEV *B) {
11059 // Quick check to see if they are the same SCEV.
11060 if (A == B) return true;
11061
11062 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
11063 // Not all instructions that are "identical" compute the same value. For
11064 // instance, two distinct alloca instructions allocating the same type are
11065 // identical and do not read memory; but compute distinct values.
11066 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
11067 };
11068
11069 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
11070 // two different instructions with the same value. Check for this case.
11071 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
11072 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
11073 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
11074 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
11075 if (ComputesEqualValues(AI, BI))
11076 return true;
11077
11078 // Otherwise assume they may have a different value.
11079 return false;
11080}
11081
11082static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS) {
11083 const SCEV *Op0, *Op1;
11084 if (!match(S, m_scev_Add(m_SCEV(Op0), m_SCEV(Op1))))
11085 return false;
11086 if (match(Op0, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11087 LHS = Op1;
11088 return true;
11089 }
11090 if (match(Op1, m_scev_Mul(m_scev_AllOnes(), m_SCEV(RHS)))) {
11091 LHS = Op0;
11092 return true;
11093 }
11094 return false;
11095}
11096
11098 SCEVUse &RHS, unsigned Depth) {
11099 bool Changed = false;
11100 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
11101 // '0 != 0'.
11102 auto TrivialCase = [&](bool TriviallyTrue) {
11104 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
11105 return true;
11106 };
11107 // If we hit the max recursion limit bail out.
11108 if (Depth >= 3)
11109 return false;
11110
11111 const SCEV *NewLHS, *NewRHS;
11112 if (match(LHS, m_scev_c_Mul(m_SCEV(NewLHS), m_SCEVVScale())) &&
11113 match(RHS, m_scev_c_Mul(m_SCEV(NewRHS), m_SCEVVScale()))) {
11114 const SCEVMulExpr *LMul = cast<SCEVMulExpr>(LHS);
11115 const SCEVMulExpr *RMul = cast<SCEVMulExpr>(RHS);
11116
11117 // (X * vscale) pred (Y * vscale) ==> X pred Y
11118 // when both multiples are NSW.
11119 // (X * vscale) uicmp/eq/ne (Y * vscale) ==> X uicmp/eq/ne Y
11120 // when both multiples are NUW.
11121 if ((LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap()) ||
11122 (LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap() &&
11123 !ICmpInst::isSigned(Pred))) {
11124 LHS = NewLHS;
11125 RHS = NewRHS;
11126 Changed = true;
11127 }
11128 }
11129
11130 // Canonicalize a constant to the right side.
11131 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
11132 // Check for both operands constant.
11133 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
11134 if (!ICmpInst::compare(LHSC->getAPInt(), RHSC->getAPInt(), Pred))
11135 return TrivialCase(false);
11136 return TrivialCase(true);
11137 }
11138 // Otherwise swap the operands to put the constant on the right.
11139 std::swap(LHS, RHS);
11141 Changed = true;
11142 }
11143
11144 // (K + A) pred (K + B) --> A pred B
11145 // For equality, no flags are needed.
11146 // For signed, both adds must be NSW. For unsigned, both must be NUW.
11147 {
11148 const SCEVConstant *C = nullptr;
11149 if (match(LHS, m_scev_Add(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11150 match(RHS, m_scev_Add(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11151 const auto *LAdd = cast<SCEVAddExpr>(LHS);
11152 const auto *RAdd = cast<SCEVAddExpr>(RHS);
11153 if (ICmpInst::isEquality(Pred) ||
11154 (ICmpInst::isSigned(Pred) && LAdd->hasNoSignedWrap() &&
11155 RAdd->hasNoSignedWrap()) ||
11156 (ICmpInst::isUnsigned(Pred) && LAdd->hasNoUnsignedWrap() &&
11157 RAdd->hasNoUnsignedWrap())) {
11158 LHS = NewLHS;
11159 RHS = NewRHS;
11160 Changed = true;
11161 }
11162 }
11163 }
11164
11165 // (C * A) pred (C * B) --> A pred B
11166 // For equality predicates, both muls must be NUW or both must be NSW
11167 // (either suffices to make multiplication by C injective; C == 0 is
11168 // impossible because SCEV folds 0 * X to 0).
11169 // For signed ordering, C must be positive and both muls must be NSW.
11170 // For unsigned ordering, both muls must be NUW.
11171 {
11172 const SCEVConstant *C = nullptr;
11173 if (match(LHS, m_scev_Mul(m_SCEVConstant(C), m_SCEV(NewLHS))) &&
11174 match(RHS, m_scev_Mul(m_scev_Specific(C), m_SCEV(NewRHS)))) {
11175 const auto *LMul = cast<SCEVMulExpr>(LHS);
11176 const auto *RMul = cast<SCEVMulExpr>(RHS);
11177 bool BothNUW = LMul->hasNoUnsignedWrap() && RMul->hasNoUnsignedWrap();
11178 bool BothNSW = LMul->hasNoSignedWrap() && RMul->hasNoSignedWrap();
11179 if ((ICmpInst::isEquality(Pred) && (BothNUW || BothNSW)) ||
11180 (ICmpInst::isSigned(Pred) && BothNSW &&
11181 C->getAPInt().isStrictlyPositive()) ||
11182 (ICmpInst::isUnsigned(Pred) && BothNUW)) {
11183 LHS = NewLHS;
11184 RHS = NewRHS;
11185 Changed = true;
11186 }
11187 }
11188 }
11189
11190 // If we're comparing an addrec with a value which is loop-invariant in the
11191 // addrec's loop, put the addrec on the left. Also make a dominance check,
11192 // as both operands could be addrecs loop-invariant in each other's loop.
11193 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
11194 const Loop *L = AR->getLoop();
11195 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
11196 std::swap(LHS, RHS);
11198 Changed = true;
11199 }
11200 }
11201
11202 // If there's a constant operand, canonicalize comparisons with boundary
11203 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
11204 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
11205 const APInt &RA = RC->getAPInt();
11206
11207 bool SimplifiedByConstantRange = false;
11208
11209 if (!ICmpInst::isEquality(Pred)) {
11211 if (ExactCR.isFullSet())
11212 return TrivialCase(true);
11213 if (ExactCR.isEmptySet())
11214 return TrivialCase(false);
11215
11216 APInt NewRHS;
11217 CmpInst::Predicate NewPred;
11218 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
11219 ICmpInst::isEquality(NewPred)) {
11220 // We were able to convert an inequality to an equality.
11221 Pred = NewPred;
11222 RHS = getConstant(NewRHS);
11223 Changed = SimplifiedByConstantRange = true;
11224 }
11225 }
11226
11227 if (!SimplifiedByConstantRange) {
11228 switch (Pred) {
11229 default:
11230 break;
11231 case ICmpInst::ICMP_EQ:
11232 case ICmpInst::ICMP_NE:
11233 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
11234 if (RA.isZero() && MatchBinarySub(LHS, LHS, RHS))
11235 Changed = true;
11236 break;
11237
11238 // The "Should have been caught earlier!" messages refer to the fact
11239 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
11240 // should have fired on the corresponding cases, and canonicalized the
11241 // check to trivial case.
11242
11243 case ICmpInst::ICMP_UGE:
11244 assert(!RA.isMinValue() && "Should have been caught earlier!");
11245 Pred = ICmpInst::ICMP_UGT;
11246 RHS = getConstant(RA - 1);
11247 Changed = true;
11248 break;
11249 case ICmpInst::ICMP_ULE:
11250 assert(!RA.isMaxValue() && "Should have been caught earlier!");
11251 Pred = ICmpInst::ICMP_ULT;
11252 RHS = getConstant(RA + 1);
11253 Changed = true;
11254 break;
11255 case ICmpInst::ICMP_SGE:
11256 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
11257 Pred = ICmpInst::ICMP_SGT;
11258 RHS = getConstant(RA - 1);
11259 Changed = true;
11260 break;
11261 case ICmpInst::ICMP_SLE:
11262 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
11263 Pred = ICmpInst::ICMP_SLT;
11264 RHS = getConstant(RA + 1);
11265 Changed = true;
11266 break;
11267 }
11268 }
11269 }
11270
11271 // Check for obvious equality.
11272 if (HasSameValue(LHS, RHS)) {
11273 if (ICmpInst::isTrueWhenEqual(Pred))
11274 return TrivialCase(true);
11276 return TrivialCase(false);
11277 }
11278
11279 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
11280 // adding or subtracting 1 from one of the operands.
11281 switch (Pred) {
11282 case ICmpInst::ICMP_SLE:
11283 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
11284 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11286 Pred = ICmpInst::ICMP_SLT;
11287 Changed = true;
11288 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
11289 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
11291 Pred = ICmpInst::ICMP_SLT;
11292 Changed = true;
11293 }
11294 break;
11295 case ICmpInst::ICMP_SGE:
11296 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
11297 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
11299 Pred = ICmpInst::ICMP_SGT;
11300 Changed = true;
11301 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
11302 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11304 Pred = ICmpInst::ICMP_SGT;
11305 Changed = true;
11306 }
11307 break;
11308 case ICmpInst::ICMP_ULE:
11309 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
11310 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
11312 Pred = ICmpInst::ICMP_ULT;
11313 Changed = true;
11314 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
11315 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
11316 Pred = ICmpInst::ICMP_ULT;
11317 Changed = true;
11318 }
11319 break;
11320 case ICmpInst::ICMP_UGE:
11321 // If RHS is an op we can fold the -1, try that first.
11322 // Otherwise prefer LHS to preserve the nuw flag.
11323 if ((isa<SCEVConstant>(RHS) ||
11325 isa<SCEVConstant>(cast<SCEVNAryExpr>(RHS)->getOperand(0)))) &&
11326 !getUnsignedRangeMin(RHS).isMinValue()) {
11327 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11328 Pred = ICmpInst::ICMP_UGT;
11329 Changed = true;
11330 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
11331 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
11333 Pred = ICmpInst::ICMP_UGT;
11334 Changed = true;
11335 } else if (!getUnsignedRangeMin(RHS).isMinValue()) {
11336 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
11337 Pred = ICmpInst::ICMP_UGT;
11338 Changed = true;
11339 }
11340 break;
11341 default:
11342 break;
11343 }
11344
11345 // TODO: More simplifications are possible here.
11346
11347 // Recursively simplify until we either hit a recursion limit or nothing
11348 // changes.
11349 if (Changed)
11350 (void)SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1);
11351
11352 return Changed;
11353}
11354
11356 return getSignedRangeMax(S).isNegative();
11357}
11358
11362
11364 return !getSignedRangeMin(S).isNegative();
11365}
11366
11370
11372 // Query push down for cases where the unsigned range is
11373 // less than sufficient.
11374 if (const auto *SExt = dyn_cast<SCEVSignExtendExpr>(S))
11375 return isKnownNonZero(SExt->getOperand(0));
11376 return getUnsignedRangeMin(S) != 0;
11377}
11378
11380 bool OrNegative) {
11381 auto NonRecursive = [OrNegative](const SCEV *S) {
11382 if (auto *C = dyn_cast<SCEVConstant>(S))
11383 return C->getAPInt().isPowerOf2() ||
11384 (OrNegative && C->getAPInt().isNegatedPowerOf2());
11385
11386 // vscale is a power-of-two.
11387 return isa<SCEVVScale>(S);
11388 };
11389
11390 if (NonRecursive(S))
11391 return true;
11392
11393 auto *Mul = dyn_cast<SCEVMulExpr>(S);
11394 if (!Mul)
11395 return false;
11396 return all_of(Mul->operands(), NonRecursive) && (OrZero || isKnownNonZero(S));
11397}
11398
11400 const SCEV *S, uint64_t M,
11402 if (M == 0)
11403 return false;
11404 if (M == 1)
11405 return true;
11406
11407 // Recursively check AddRec operands. An AddRecExpr S is a multiple of M if S
11408 // starts with a multiple of M and at every iteration step S only adds
11409 // multiples of M.
11410 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
11411 return isKnownMultipleOf(AddRec->getStart(), M, Assumptions) &&
11412 isKnownMultipleOf(AddRec->getStepRecurrence(*this), M, Assumptions);
11413
11414 // For a constant, check that "S % M == 0".
11415 if (auto *Cst = dyn_cast<SCEVConstant>(S)) {
11416 APInt C = Cst->getAPInt();
11417 return C.urem(M) == 0;
11418 }
11419
11420 // TODO: Also check other SCEV expressions, i.e., SCEVAddRecExpr, etc.
11421
11422 // Basic tests have failed.
11423 // Check "S % M == 0" at compile time and record runtime Assumptions.
11424 auto *STy = dyn_cast<IntegerType>(S->getType());
11425 const SCEV *SmodM =
11426 getURemExpr(S, getConstant(ConstantInt::get(STy, M, false)));
11427 const SCEV *Zero = getZero(STy);
11428
11429 // Check whether "S % M == 0" is known at compile time.
11430 if (isKnownPredicate(ICmpInst::ICMP_EQ, SmodM, Zero))
11431 return true;
11432
11433 // Check whether "S % M != 0" is known at compile time.
11434 if (isKnownPredicate(ICmpInst::ICMP_NE, SmodM, Zero))
11435 return false;
11436
11438
11439 // Detect redundant predicates.
11440 for (auto *A : Assumptions)
11441 if (A->implies(P, *this))
11442 return true;
11443
11444 // Only record non-redundant predicates.
11445 Assumptions.push_back(P);
11446 return true;
11447}
11448
11450 return ((isKnownNonNegative(S1) && isKnownNonNegative(S2)) ||
11452}
11453
11454std::pair<const SCEV *, const SCEV *>
11456 // Compute SCEV on entry of loop L.
11457 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
11458 if (Start == getCouldNotCompute())
11459 return { Start, Start };
11460 // Compute post increment SCEV for loop L.
11461 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
11462 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
11463 return { Start, PostInc };
11464}
11465
11467 SCEVUse RHS) {
11468 // First collect all loops.
11470 getUsedLoops(LHS, LoopsUsed);
11471 getUsedLoops(RHS, LoopsUsed);
11472
11473 if (LoopsUsed.empty())
11474 return false;
11475
11476 // Domination relationship must be a linear order on collected loops.
11477#ifndef NDEBUG
11478 for (const auto *L1 : LoopsUsed)
11479 for (const auto *L2 : LoopsUsed)
11480 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
11481 DT.dominates(L2->getHeader(), L1->getHeader())) &&
11482 "Domination relationship is not a linear order");
11483#endif
11484
11485 const Loop *MDL =
11486 *llvm::max_element(LoopsUsed, [&](const Loop *L1, const Loop *L2) {
11487 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
11488 });
11489
11490 // Get init and post increment value for LHS.
11491 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
11492 // if LHS contains unknown non-invariant SCEV then bail out.
11493 if (SplitLHS.first == getCouldNotCompute())
11494 return false;
11495 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
11496 // Get init and post increment value for RHS.
11497 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
11498 // if RHS contains unknown non-invariant SCEV then bail out.
11499 if (SplitRHS.first == getCouldNotCompute())
11500 return false;
11501 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
11502 // It is possible that init SCEV contains an invariant load but it does
11503 // not dominate MDL and is not available at MDL loop entry, so we should
11504 // check it here.
11505 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
11506 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
11507 return false;
11508
11509 // It seems backedge guard check is faster than entry one so in some cases
11510 // it can speed up whole estimation by short circuit
11511 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
11512 SplitRHS.second) &&
11513 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
11514}
11515
11517 SCEVUse RHS) {
11518 // Canonicalize the inputs first.
11519 (void)SimplifyICmpOperands(Pred, LHS, RHS);
11520
11521 if (isKnownViaInduction(Pred, LHS, RHS))
11522 return true;
11523
11524 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
11525 return true;
11526
11527 // Otherwise see what can be done with some simple reasoning.
11528 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
11529}
11530
11532 const SCEV *LHS,
11533 const SCEV *RHS) {
11534 if (isKnownPredicate(Pred, LHS, RHS))
11535 return true;
11537 return false;
11538 return std::nullopt;
11539}
11540
11542 const SCEV *RHS,
11543 const Instruction *CtxI) {
11544 // TODO: Analyze guards and assumes from Context's block.
11545 return isKnownPredicate(Pred, LHS, RHS) ||
11546 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
11547}
11548
11549std::optional<bool>
11551 const SCEV *RHS, const Instruction *CtxI) {
11552 std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
11553 if (KnownWithoutContext)
11554 return KnownWithoutContext;
11555
11556 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
11557 return true;
11559 CtxI->getParent(), ICmpInst::getInverseCmpPredicate(Pred), LHS, RHS))
11560 return false;
11561 return std::nullopt;
11562}
11563
11565 const SCEVAddRecExpr *LHS,
11566 const SCEV *RHS) {
11567 const Loop *L = LHS->getLoop();
11568 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
11569 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
11570}
11571
11572std::optional<ScalarEvolution::MonotonicPredicateType>
11574 ICmpInst::Predicate Pred) {
11575 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
11576
11577#ifndef NDEBUG
11578 // Verify an invariant: inverting the predicate should turn a monotonically
11579 // increasing change to a monotonically decreasing one, and vice versa.
11580 if (Result) {
11581 auto ResultSwapped =
11582 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
11583
11584 assert(*ResultSwapped != *Result &&
11585 "monotonicity should flip as we flip the predicate");
11586 }
11587#endif
11588
11589 return Result;
11590}
11591
11592std::optional<ScalarEvolution::MonotonicPredicateType>
11593ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
11594 ICmpInst::Predicate Pred) {
11595 // A zero step value for LHS means the induction variable is essentially a
11596 // loop invariant value. We don't really depend on the predicate actually
11597 // flipping from false to true (for increasing predicates, and the other way
11598 // around for decreasing predicates), all we care about is that *if* the
11599 // predicate changes then it only changes from false to true.
11600 //
11601 // A zero step value in itself is not very useful, but there may be places
11602 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
11603 // as general as possible.
11604
11605 // Only handle LE/LT/GE/GT predicates.
11606 if (!ICmpInst::isRelational(Pred))
11607 return std::nullopt;
11608
11609 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
11610 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
11611 "Should be greater or less!");
11612
11613 // Check that AR does not wrap.
11614 if (ICmpInst::isUnsigned(Pred)) {
11615 if (!LHS->hasNoUnsignedWrap())
11616 return std::nullopt;
11618 }
11619 assert(ICmpInst::isSigned(Pred) &&
11620 "Relational predicate is either signed or unsigned!");
11621 if (!LHS->hasNoSignedWrap())
11622 return std::nullopt;
11623
11624 const SCEV *Step = LHS->getStepRecurrence(*this);
11625
11626 if (isKnownNonNegative(Step))
11628
11629 if (isKnownNonPositive(Step))
11631
11632 return std::nullopt;
11633}
11634
11635std::optional<ScalarEvolution::LoopInvariantPredicate>
11637 const SCEV *RHS, const Loop *L,
11638 const Instruction *CtxI) {
11639 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11640 if (!isLoopInvariant(RHS, L)) {
11641 if (!isLoopInvariant(LHS, L))
11642 return std::nullopt;
11643
11644 std::swap(LHS, RHS);
11646 }
11647
11648 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
11649 if (!ArLHS || ArLHS->getLoop() != L)
11650 return std::nullopt;
11651
11652 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
11653 if (!MonotonicType)
11654 return std::nullopt;
11655 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
11656 // true as the loop iterates, and the backedge is control dependent on
11657 // "ArLHS `Pred` RHS" == true then we can reason as follows:
11658 //
11659 // * if the predicate was false in the first iteration then the predicate
11660 // is never evaluated again, since the loop exits without taking the
11661 // backedge.
11662 // * if the predicate was true in the first iteration then it will
11663 // continue to be true for all future iterations since it is
11664 // monotonically increasing.
11665 //
11666 // For both the above possibilities, we can replace the loop varying
11667 // predicate with its value on the first iteration of the loop (which is
11668 // loop invariant).
11669 //
11670 // A similar reasoning applies for a monotonically decreasing predicate, by
11671 // replacing true with false and false with true in the above two bullets.
11673 auto P = Increasing ? Pred : ICmpInst::getInverseCmpPredicate(Pred);
11674
11675 if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
11677 RHS);
11678
11679 if (!CtxI)
11680 return std::nullopt;
11681 // Try to prove via context.
11682 // TODO: Support other cases.
11683 switch (Pred) {
11684 default:
11685 break;
11686 case ICmpInst::ICMP_ULE:
11687 case ICmpInst::ICMP_ULT: {
11688 assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
11689 // Given preconditions
11690 // (1) ArLHS does not cross the border of positive and negative parts of
11691 // range because of:
11692 // - Positive step; (TODO: lift this limitation)
11693 // - nuw - does not cross zero boundary;
11694 // - nsw - does not cross SINT_MAX boundary;
11695 // (2) ArLHS <s RHS
11696 // (3) RHS >=s 0
11697 // we can replace the loop variant ArLHS <u RHS condition with loop
11698 // invariant Start(ArLHS) <u RHS.
11699 //
11700 // Because of (1) there are two options:
11701 // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
11702 // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
11703 // It means that ArLHS <s RHS <=> ArLHS <u RHS.
11704 // Because of (2) ArLHS <u RHS is trivially true.
11705 // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
11706 // We can strengthen this to Start(ArLHS) <u RHS.
11707 auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
11708 if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
11709 isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
11710 isKnownNonNegative(RHS) &&
11711 isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
11713 RHS);
11714 }
11715 }
11716
11717 return std::nullopt;
11718}
11719
11720std::optional<ScalarEvolution::LoopInvariantPredicate>
11722 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11723 const Instruction *CtxI, const SCEV *MaxIter) {
11725 Pred, LHS, RHS, L, CtxI, MaxIter))
11726 return LIP;
11727 if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
11728 // Number of iterations expressed as UMIN isn't always great for expressing
11729 // the value on the last iteration. If the straightforward approach didn't
11730 // work, try the following trick: if the a predicate is invariant for X, it
11731 // is also invariant for umin(X, ...). So try to find something that works
11732 // among subexpressions of MaxIter expressed as umin.
11733 for (SCEVUse Op : UMin->operands())
11735 Pred, LHS, RHS, L, CtxI, Op))
11736 return LIP;
11737 return std::nullopt;
11738}
11739
11740std::optional<ScalarEvolution::LoopInvariantPredicate>
11742 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
11743 const Instruction *CtxI, const SCEV *MaxIter) {
11744 // Try to prove the following set of facts:
11745 // - The predicate is monotonic in the iteration space.
11746 // - If the check does not fail on the 1st iteration:
11747 // - No overflow will happen during first MaxIter iterations;
11748 // - It will not fail on the MaxIter'th iteration.
11749 // If the check does fail on the 1st iteration, we leave the loop and no
11750 // other checks matter.
11751
11752 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
11753 if (!isLoopInvariant(RHS, L)) {
11754 if (!isLoopInvariant(LHS, L))
11755 return std::nullopt;
11756
11757 std::swap(LHS, RHS);
11759 }
11760
11761 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
11762 if (!AR || AR->getLoop() != L)
11763 return std::nullopt;
11764
11765 // Even if both are valid, we need to consistently chose the unsigned or the
11766 // signed predicate below, not mixtures of both. For now, prefer the unsigned
11767 // predicate.
11768 Pred = Pred.dropSameSign();
11769
11770 // The predicate must be relational (i.e. <, <=, >=, >).
11771 if (!ICmpInst::isRelational(Pred))
11772 return std::nullopt;
11773
11774 // TODO: Support steps other than +/- 1.
11775 const SCEV *Step = AR->getStepRecurrence(*this);
11776 auto *One = getOne(Step->getType());
11777 auto *MinusOne = getNegativeSCEV(One);
11778 if (Step != One && Step != MinusOne)
11779 return std::nullopt;
11780
11781 // Type mismatch here means that MaxIter is potentially larger than max
11782 // unsigned value in start type, which mean we cannot prove no wrap for the
11783 // indvar.
11784 if (AR->getType() != MaxIter->getType())
11785 return std::nullopt;
11786
11787 // Value of IV on suggested last iteration.
11788 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
11789 // Does it still meet the requirement?
11790 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
11791 return std::nullopt;
11792 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
11793 // not exceed max unsigned value of this type), this effectively proves
11794 // that there is no wrap during the iteration. To prove that there is no
11795 // signed/unsigned wrap, we need to check that
11796 // Start <= Last for step = 1 or Start >= Last for step = -1.
11797 ICmpInst::Predicate NoOverflowPred =
11799 if (Step == MinusOne)
11800 NoOverflowPred = ICmpInst::getSwappedPredicate(NoOverflowPred);
11801 const SCEV *Start = AR->getStart();
11802 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
11803 return std::nullopt;
11804
11805 // Everything is fine.
11806 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
11807}
11808
11809bool ScalarEvolution::isKnownPredicateViaConstantRanges(CmpPredicate Pred,
11810 SCEVUse LHS,
11811 SCEVUse RHS) {
11812 if (HasSameValue(LHS, RHS))
11813 return ICmpInst::isTrueWhenEqual(Pred);
11814
11815 auto CheckRange = [&](bool IsSigned) {
11816 auto RangeLHS = IsSigned ? getSignedRange(LHS) : getUnsignedRange(LHS);
11817 auto RangeRHS = IsSigned ? getSignedRange(RHS) : getUnsignedRange(RHS);
11818 return RangeLHS.icmp(Pred, RangeRHS);
11819 };
11820
11821 // The check at the top of the function catches the case where the values are
11822 // known to be equal.
11823 if (Pred == CmpInst::ICMP_EQ)
11824 return false;
11825
11826 if (Pred == CmpInst::ICMP_NE) {
11827 if (CheckRange(true) || CheckRange(false))
11828 return true;
11829 auto *Diff = getMinusSCEV(LHS, RHS);
11830 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
11831 }
11832
11833 return CheckRange(CmpInst::isSigned(Pred));
11834}
11835
11836bool ScalarEvolution::isKnownPredicateViaNoOverflow(CmpPredicate Pred,
11838 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
11839 // C1 and C2 are constant integers. If either X or Y are not add expressions,
11840 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
11841 // OutC1 and OutC2.
11842 auto MatchBinaryAddToConst = [this](SCEVUse X, SCEVUse Y, APInt &OutC1,
11843 APInt &OutC2,
11844 SCEV::NoWrapFlags ExpectedFlags) {
11845 SCEVUse XNonConstOp, XConstOp;
11846 SCEVUse YNonConstOp, YConstOp;
11847 SCEV::NoWrapFlags XFlagsPresent;
11848 SCEV::NoWrapFlags YFlagsPresent;
11849
11850 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
11851 XConstOp = getZero(X->getType());
11852 XNonConstOp = X;
11853 XFlagsPresent = ExpectedFlags;
11854 }
11855 if (!isa<SCEVConstant>(XConstOp))
11856 return false;
11857
11858 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
11859 YConstOp = getZero(Y->getType());
11860 YNonConstOp = Y;
11861 YFlagsPresent = ExpectedFlags;
11862 }
11863
11864 if (YNonConstOp != XNonConstOp)
11865 return false;
11866
11867 if (!isa<SCEVConstant>(YConstOp))
11868 return false;
11869
11870 // When matching ADDs with NUW flags (and unsigned predicates), only the
11871 // second ADD (with the larger constant) requires NUW.
11872 if ((YFlagsPresent & ExpectedFlags) != ExpectedFlags)
11873 return false;
11874 if (ExpectedFlags != SCEV::FlagNUW &&
11875 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) {
11876 return false;
11877 }
11878
11879 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
11880 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
11881
11882 return true;
11883 };
11884
11885 APInt C1;
11886 APInt C2;
11887
11888 switch (Pred) {
11889 default:
11890 break;
11891
11892 case ICmpInst::ICMP_SGE:
11893 std::swap(LHS, RHS);
11894 [[fallthrough]];
11895 case ICmpInst::ICMP_SLE:
11896 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
11897 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
11898 return true;
11899
11900 break;
11901
11902 case ICmpInst::ICMP_SGT:
11903 std::swap(LHS, RHS);
11904 [[fallthrough]];
11905 case ICmpInst::ICMP_SLT:
11906 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
11907 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
11908 return true;
11909
11910 break;
11911
11912 case ICmpInst::ICMP_UGE:
11913 std::swap(LHS, RHS);
11914 [[fallthrough]];
11915 case ICmpInst::ICMP_ULE:
11916 // (X + C1) u<= (X + C2)<nuw> for C1 u<= C2.
11917 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ule(C2))
11918 return true;
11919
11920 break;
11921
11922 case ICmpInst::ICMP_UGT:
11923 std::swap(LHS, RHS);
11924 [[fallthrough]];
11925 case ICmpInst::ICMP_ULT:
11926 // (X + C1) u< (X + C2)<nuw> if C1 u< C2.
11927 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNUW) && C1.ult(C2))
11928 return true;
11929 break;
11930 }
11931
11932 return false;
11933}
11934
11935bool ScalarEvolution::isKnownPredicateViaSplitting(CmpPredicate Pred,
11937 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
11938 return false;
11939
11940 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
11941 // the stack can result in exponential time complexity.
11942 SaveAndRestore Restore(ProvingSplitPredicate, true);
11943
11944 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
11945 //
11946 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
11947 // isKnownPredicate. isKnownPredicate is more powerful, but also more
11948 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
11949 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
11950 // use isKnownPredicate later if needed.
11951 return isKnownNonNegative(RHS) &&
11954}
11955
11956bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
11957 const SCEV *LHS, const SCEV *RHS) {
11958 // No need to even try if we know the module has no guards.
11959 if (!HasGuards)
11960 return false;
11961
11962 return any_of(*BB, [&](const Instruction &I) {
11963 using namespace llvm::PatternMatch;
11964
11965 Value *Condition;
11967 m_Value(Condition))) &&
11968 isImpliedCond(Pred, LHS, RHS, Condition, false);
11969 });
11970}
11971
11972/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
11973/// protected by a conditional between LHS and RHS. This is used to
11974/// to eliminate casts.
11976 CmpPredicate Pred,
11977 const SCEV *LHS,
11978 const SCEV *RHS) {
11979 // Interpret a null as meaning no loop, where there is obviously no guard
11980 // (interprocedural conditions notwithstanding). Do not bother about
11981 // unreachable loops.
11982 if (!L || !DT.isReachableFromEntry(L->getHeader()))
11983 return true;
11984
11985 if (VerifyIR)
11986 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
11987 "This cannot be done on broken IR!");
11988
11989
11990 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
11991 return true;
11992
11993 BasicBlock *Latch = L->getLoopLatch();
11994 if (!Latch)
11995 return false;
11996
11997 CondBrInst *LoopContinuePredicate =
11999 if (LoopContinuePredicate &&
12000 isImpliedCond(Pred, LHS, RHS, LoopContinuePredicate->getCondition(),
12001 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
12002 return true;
12003
12004 // We don't want more than one activation of the following loops on the stack
12005 // -- that can lead to O(n!) time complexity.
12006 if (WalkingBEDominatingConds)
12007 return false;
12008
12009 SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
12010
12011 // See if we can exploit a trip count to prove the predicate.
12012 const auto &BETakenInfo = getBackedgeTakenInfo(L);
12013 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
12014 if (LatchBECount != getCouldNotCompute()) {
12015 // We know that Latch branches back to the loop header exactly
12016 // LatchBECount times. This means the backdege condition at Latch is
12017 // equivalent to "{0,+,1} u< LatchBECount".
12018 Type *Ty = LatchBECount->getType();
12019 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
12020 const SCEV *LoopCounter =
12021 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
12022 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
12023 LatchBECount))
12024 return true;
12025 }
12026
12027 // Check conditions due to any @llvm.assume intrinsics.
12028 for (auto &AssumeVH : AC.assumptions()) {
12029 if (!AssumeVH)
12030 continue;
12031 auto *CI = cast<CallInst>(AssumeVH);
12032 if (!DT.dominates(CI, Latch->getTerminator()))
12033 continue;
12034
12035 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
12036 return true;
12037 }
12038
12039 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
12040 return true;
12041
12042 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
12043 DTN != HeaderDTN; DTN = DTN->getIDom()) {
12044 assert(DTN && "should reach the loop header before reaching the root!");
12045
12046 BasicBlock *BB = DTN->getBlock();
12047 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
12048 return true;
12049
12050 BasicBlock *PBB = BB->getSinglePredecessor();
12051 if (!PBB)
12052 continue;
12053
12055 if (!ContBr || ContBr->getSuccessor(0) == ContBr->getSuccessor(1))
12056 continue;
12057
12058 // If we have an edge `E` within the loop body that dominates the only
12059 // latch, the condition guarding `E` also guards the backedge. This
12060 // reasoning works only for loops with a single latch.
12061 // We're constructively (and conservatively) enumerating edges within the
12062 // loop body that dominate the latch. The dominator tree better agree
12063 // with us on this:
12064 assert(DT.dominates(BasicBlockEdge(PBB, BB), Latch) && "should be!");
12065 if (isImpliedCond(Pred, LHS, RHS, ContBr->getCondition(),
12066 BB != ContBr->getSuccessor(0)))
12067 return true;
12068 }
12069
12070 return false;
12071}
12072
12074 CmpPredicate Pred,
12075 const SCEV *LHS,
12076 const SCEV *RHS) {
12077 // Do not bother proving facts for unreachable code.
12078 if (!DT.isReachableFromEntry(BB))
12079 return true;
12080 if (VerifyIR)
12081 assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
12082 "This cannot be done on broken IR!");
12083
12084 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
12085 // the facts (a >= b && a != b) separately. A typical situation is when the
12086 // non-strict comparison is known from ranges and non-equality is known from
12087 // dominating predicates. If we are proving strict comparison, we always try
12088 // to prove non-equality and non-strict comparison separately.
12089 CmpPredicate NonStrictPredicate = ICmpInst::getNonStrictCmpPredicate(Pred);
12090 const bool ProvingStrictComparison =
12091 Pred != NonStrictPredicate.dropSameSign();
12092 bool ProvedNonStrictComparison = false;
12093 bool ProvedNonEquality = false;
12094
12095 auto SplitAndProve = [&](std::function<bool(CmpPredicate)> Fn) -> bool {
12096 if (!ProvedNonStrictComparison)
12097 ProvedNonStrictComparison = Fn(NonStrictPredicate);
12098 if (!ProvedNonEquality)
12099 ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
12100 if (ProvedNonStrictComparison && ProvedNonEquality)
12101 return true;
12102 return false;
12103 };
12104
12105 if (ProvingStrictComparison) {
12106 auto ProofFn = [&](CmpPredicate P) {
12107 return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
12108 };
12109 if (SplitAndProve(ProofFn))
12110 return true;
12111 }
12112
12113 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
12114 auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
12115 const Instruction *CtxI = &BB->front();
12116 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
12117 return true;
12118 if (ProvingStrictComparison) {
12119 auto ProofFn = [&](CmpPredicate P) {
12120 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
12121 };
12122 if (SplitAndProve(ProofFn))
12123 return true;
12124 }
12125 return false;
12126 };
12127
12128 // Starting at the block's predecessor, climb up the predecessor chain, as long
12129 // as there are predecessors that can be found that have unique successors
12130 // leading to the original block.
12131 const Loop *ContainingLoop = LI.getLoopFor(BB);
12132 const BasicBlock *PredBB;
12133 if (ContainingLoop && ContainingLoop->getHeader() == BB)
12134 PredBB = ContainingLoop->getLoopPredecessor();
12135 else
12136 PredBB = BB->getSinglePredecessor();
12137 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
12138 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
12139 const CondBrInst *BlockEntryPredicate =
12140 dyn_cast<CondBrInst>(Pair.first->getTerminator());
12141 if (!BlockEntryPredicate)
12142 continue;
12143
12144 if (ProveViaCond(BlockEntryPredicate->getCondition(),
12145 BlockEntryPredicate->getSuccessor(0) != Pair.second))
12146 return true;
12147 }
12148
12149 // Check conditions due to any @llvm.assume intrinsics.
12150 for (auto &AssumeVH : AC.assumptions()) {
12151 if (!AssumeVH)
12152 continue;
12153 auto *CI = cast<CallInst>(AssumeVH);
12154 if (!DT.dominates(CI, BB))
12155 continue;
12156
12157 if (ProveViaCond(CI->getArgOperand(0), false))
12158 return true;
12159 }
12160
12161 // Check conditions due to any @llvm.experimental.guard intrinsics.
12162 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
12163 F.getParent(), Intrinsic::experimental_guard);
12164 if (GuardDecl)
12165 for (const auto *GU : GuardDecl->users())
12166 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
12167 if (Guard->getFunction() == BB->getParent() && DT.dominates(Guard, BB))
12168 if (ProveViaCond(Guard->getArgOperand(0), false))
12169 return true;
12170 return false;
12171}
12172
12174 const SCEV *LHS,
12175 const SCEV *RHS) {
12176 // Interpret a null as meaning no loop, where there is obviously no guard
12177 // (interprocedural conditions notwithstanding).
12178 if (!L)
12179 return false;
12180
12181 // Both LHS and RHS must be available at loop entry.
12183 "LHS is not available at Loop Entry");
12185 "RHS is not available at Loop Entry");
12186
12187 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
12188 return true;
12189
12190 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
12191}
12192
12193bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12194 const SCEV *RHS,
12195 const Value *FoundCondValue, bool Inverse,
12196 const Instruction *CtxI) {
12197 // False conditions implies anything. Do not bother analyzing it further.
12198 if (FoundCondValue ==
12199 ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
12200 return true;
12201
12202 if (!PendingLoopPredicates.insert(FoundCondValue).second)
12203 return false;
12204
12205 llvm::scope_exit ClearOnExit(
12206 [&]() { PendingLoopPredicates.erase(FoundCondValue); });
12207
12208 // Recursively handle And and Or conditions.
12209 const Value *Op0, *Op1;
12210 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
12211 if (!Inverse)
12212 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12213 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12214 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
12215 if (Inverse)
12216 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
12217 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
12218 }
12219
12220 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
12221 if (!ICI) return false;
12222
12223 // Now that we found a conditional branch that dominates the loop or controls
12224 // the loop latch. Check to see if it is the comparison we are looking for.
12225 CmpPredicate FoundPred;
12226 if (Inverse)
12227 FoundPred = ICI->getInverseCmpPredicate();
12228 else
12229 FoundPred = ICI->getCmpPredicate();
12230
12231 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
12232 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
12233
12234 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
12235}
12236
12237bool ScalarEvolution::isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
12238 const SCEV *RHS, CmpPredicate FoundPred,
12239 const SCEV *FoundLHS, const SCEV *FoundRHS,
12240 const Instruction *CtxI) {
12241 // Balance the types.
12242 if (getTypeSizeInBits(LHS->getType()) <
12243 getTypeSizeInBits(FoundLHS->getType())) {
12244 // For unsigned and equality predicates, try to prove that both found
12245 // operands fit into narrow unsigned range. If so, try to prove facts in
12246 // narrow types.
12247 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
12248 !FoundRHS->getType()->isPointerTy()) {
12249 auto *NarrowType = LHS->getType();
12250 auto *WideType = FoundLHS->getType();
12251 auto BitWidth = getTypeSizeInBits(NarrowType);
12252 const SCEV *MaxValue = getZeroExtendExpr(
12254 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
12255 MaxValue) &&
12256 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
12257 MaxValue)) {
12258 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
12259 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
12260 // We cannot preserve samesign after truncation.
12261 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred.dropSameSign(),
12262 TruncFoundLHS, TruncFoundRHS, CtxI))
12263 return true;
12264 }
12265 }
12266
12267 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
12268 return false;
12269 if (CmpInst::isSigned(Pred)) {
12270 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
12271 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
12272 } else {
12273 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
12274 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
12275 }
12276 } else if (getTypeSizeInBits(LHS->getType()) >
12277 getTypeSizeInBits(FoundLHS->getType())) {
12278 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
12279 return false;
12280 if (CmpInst::isSigned(FoundPred)) {
12281 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
12282 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
12283 } else {
12284 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
12285 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
12286 }
12287 }
12288 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
12289 FoundRHS, CtxI);
12290}
12291
12292bool ScalarEvolution::isImpliedCondBalancedTypes(
12293 CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, CmpPredicate FoundPred,
12294 SCEVUse FoundLHS, SCEVUse FoundRHS, const Instruction *CtxI) {
12296 getTypeSizeInBits(FoundLHS->getType()) &&
12297 "Types should be balanced!");
12298 // Canonicalize the query to match the way instcombine will have
12299 // canonicalized the comparison.
12300 if (SimplifyICmpOperands(Pred, LHS, RHS))
12301 if (LHS == RHS)
12302 return CmpInst::isTrueWhenEqual(Pred);
12303 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
12304 if (FoundLHS == FoundRHS)
12305 return CmpInst::isFalseWhenEqual(FoundPred);
12306
12307 // Check to see if we can make the LHS or RHS match.
12308 if (LHS == FoundRHS || RHS == FoundLHS) {
12309 if (isa<SCEVConstant>(RHS)) {
12310 std::swap(FoundLHS, FoundRHS);
12311 FoundPred = ICmpInst::getSwappedCmpPredicate(FoundPred);
12312 } else {
12313 std::swap(LHS, RHS);
12315 }
12316 }
12317
12318 // Check whether the found predicate is the same as the desired predicate.
12319 if (auto P = CmpPredicate::getMatching(FoundPred, Pred))
12320 return isImpliedCondOperands(*P, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12321
12322 // Check whether swapping the found predicate makes it the same as the
12323 // desired predicate.
12324 if (auto P = CmpPredicate::getMatching(
12325 ICmpInst::getSwappedCmpPredicate(FoundPred), Pred)) {
12326 // We can write the implication
12327 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
12328 // using one of the following ways:
12329 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
12330 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
12331 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
12332 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
12333 // Forms 1. and 2. require swapping the operands of one condition. Don't
12334 // do this if it would break canonical constant/addrec ordering.
12336 return isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P), RHS,
12337 LHS, FoundLHS, FoundRHS, CtxI);
12338 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
12339 return isImpliedCondOperands(*P, LHS, RHS, FoundRHS, FoundLHS, CtxI);
12340
12341 // There's no clear preference between forms 3. and 4., try both. Avoid
12342 // forming getNotSCEV of pointer values as the resulting subtract is
12343 // not legal.
12344 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
12345 isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(*P),
12346 getNotSCEV(LHS), getNotSCEV(RHS), FoundLHS,
12347 FoundRHS, CtxI))
12348 return true;
12349
12350 if (!FoundLHS->getType()->isPointerTy() &&
12351 !FoundRHS->getType()->isPointerTy() &&
12352 isImpliedCondOperands(*P, LHS, RHS, getNotSCEV(FoundLHS),
12353 getNotSCEV(FoundRHS), CtxI))
12354 return true;
12355
12356 return false;
12357 }
12358
12359 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
12361 assert(P1 != P2 && "Handled earlier!");
12362 return CmpInst::isRelational(P2) &&
12364 };
12365 if (IsSignFlippedPredicate(Pred, FoundPred)) {
12366 // Unsigned comparison is the same as signed comparison when both the
12367 // operands are non-negative or negative.
12368 if (haveSameSign(FoundLHS, FoundRHS))
12369 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
12370 // Create local copies that we can freely swap and canonicalize our
12371 // conditions to "le/lt".
12372 CmpPredicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
12373 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
12374 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
12375 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
12376 CanonicalPred = ICmpInst::getSwappedCmpPredicate(CanonicalPred);
12377 CanonicalFoundPred = ICmpInst::getSwappedCmpPredicate(CanonicalFoundPred);
12378 std::swap(CanonicalLHS, CanonicalRHS);
12379 std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
12380 }
12381 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
12382 "Must be!");
12383 assert((ICmpInst::isLT(CanonicalFoundPred) ||
12384 ICmpInst::isLE(CanonicalFoundPred)) &&
12385 "Must be!");
12386 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
12387 // Use implication:
12388 // x <u y && y >=s 0 --> x <s y.
12389 // If we can prove the left part, the right part is also proven.
12390 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12391 CanonicalRHS, CanonicalFoundLHS,
12392 CanonicalFoundRHS);
12393 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
12394 // Use implication:
12395 // x <s y && y <s 0 --> x <u y.
12396 // If we can prove the left part, the right part is also proven.
12397 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
12398 CanonicalRHS, CanonicalFoundLHS,
12399 CanonicalFoundRHS);
12400 }
12401
12402 // Check if we can make progress by sharpening ranges.
12403 if (FoundPred == ICmpInst::ICMP_NE &&
12404 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
12405
12406 const SCEVConstant *C = nullptr;
12407 const SCEV *V = nullptr;
12408
12409 if (isa<SCEVConstant>(FoundLHS)) {
12410 C = cast<SCEVConstant>(FoundLHS);
12411 V = FoundRHS;
12412 } else {
12413 C = cast<SCEVConstant>(FoundRHS);
12414 V = FoundLHS;
12415 }
12416
12417 // The guarding predicate tells us that C != V. If the known range
12418 // of V is [C, t), we can sharpen the range to [C + 1, t). The
12419 // range we consider has to correspond to same signedness as the
12420 // predicate we're interested in folding.
12421
12422 APInt Min = ICmpInst::isSigned(Pred) ?
12424
12425 if (Min == C->getAPInt()) {
12426 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
12427 // This is true even if (Min + 1) wraps around -- in case of
12428 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
12429
12430 APInt SharperMin = Min + 1;
12431
12432 switch (Pred) {
12433 case ICmpInst::ICMP_SGE:
12434 case ICmpInst::ICMP_UGE:
12435 // We know V `Pred` SharperMin. If this implies LHS `Pred`
12436 // RHS, we're done.
12437 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
12438 CtxI))
12439 return true;
12440 [[fallthrough]];
12441
12442 case ICmpInst::ICMP_SGT:
12443 case ICmpInst::ICMP_UGT:
12444 // We know from the range information that (V `Pred` Min ||
12445 // V == Min). We know from the guarding condition that !(V
12446 // == Min). This gives us
12447 //
12448 // V `Pred` Min || V == Min && !(V == Min)
12449 // => V `Pred` Min
12450 //
12451 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
12452
12453 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
12454 return true;
12455 break;
12456
12457 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
12458 case ICmpInst::ICMP_SLE:
12459 case ICmpInst::ICMP_ULE:
12460 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12461 LHS, V, getConstant(SharperMin), CtxI))
12462 return true;
12463 [[fallthrough]];
12464
12465 case ICmpInst::ICMP_SLT:
12466 case ICmpInst::ICMP_ULT:
12467 if (isImpliedCondOperands(ICmpInst::getSwappedCmpPredicate(Pred), RHS,
12468 LHS, V, getConstant(Min), CtxI))
12469 return true;
12470 break;
12471
12472 default:
12473 // No change
12474 break;
12475 }
12476 }
12477 }
12478
12479 // Check whether the actual condition is beyond sufficient.
12480 if (FoundPred == ICmpInst::ICMP_EQ)
12481 if (ICmpInst::isTrueWhenEqual(Pred))
12482 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12483 return true;
12484 if (Pred == ICmpInst::ICMP_NE)
12485 if (!ICmpInst::isTrueWhenEqual(FoundPred))
12486 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
12487 return true;
12488
12489 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS))
12490 return true;
12491
12492 // Otherwise assume the worst.
12493 return false;
12494}
12495
12496bool ScalarEvolution::splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
12497 SCEV::NoWrapFlags &Flags) {
12498 if (!match(Expr, m_scev_Add(m_SCEV(L), m_SCEV(R))))
12499 return false;
12500
12501 Flags = cast<SCEVAddExpr>(Expr)->getNoWrapFlags();
12502 return true;
12503}
12504
12505std::optional<APInt>
12507 // We avoid subtracting expressions here because this function is usually
12508 // fairly deep in the call stack (i.e. is called many times).
12509
12510 unsigned BW = getTypeSizeInBits(More->getType());
12511 APInt Diff(BW, 0);
12512 APInt DiffMul(BW, 1);
12513 // Try various simplifications to reduce the difference to a constant. Limit
12514 // the number of allowed simplifications to keep compile-time low.
12515 for (unsigned I = 0; I < 8; ++I) {
12516 if (More == Less)
12517 return Diff;
12518
12519 // Reduce addrecs with identical steps to their start value.
12521 const auto *LAR = cast<SCEVAddRecExpr>(Less);
12522 const auto *MAR = cast<SCEVAddRecExpr>(More);
12523
12524 if (LAR->getLoop() != MAR->getLoop())
12525 return std::nullopt;
12526
12527 // We look at affine expressions only; not for correctness but to keep
12528 // getStepRecurrence cheap.
12529 if (!LAR->isAffine() || !MAR->isAffine())
12530 return std::nullopt;
12531
12532 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
12533 return std::nullopt;
12534
12535 Less = LAR->getStart();
12536 More = MAR->getStart();
12537 continue;
12538 }
12539
12540 // Try to match a common constant multiply.
12541 auto MatchConstMul =
12542 [](const SCEV *S) -> std::optional<std::pair<const SCEV *, APInt>> {
12543 const APInt *C;
12544 const SCEV *Op;
12545 if (match(S, m_scev_Mul(m_scev_APInt(C), m_SCEV(Op))))
12546 return {{Op, *C}};
12547 return std::nullopt;
12548 };
12549 if (auto MatchedMore = MatchConstMul(More)) {
12550 if (auto MatchedLess = MatchConstMul(Less)) {
12551 if (MatchedMore->second == MatchedLess->second) {
12552 More = MatchedMore->first;
12553 Less = MatchedLess->first;
12554 DiffMul *= MatchedMore->second;
12555 continue;
12556 }
12557 }
12558 }
12559
12560 // Try to cancel out common factors in two add expressions.
12562 auto Add = [&](const SCEV *S, int Mul) {
12563 if (auto *C = dyn_cast<SCEVConstant>(S)) {
12564 if (Mul == 1) {
12565 Diff += C->getAPInt() * DiffMul;
12566 } else {
12567 assert(Mul == -1);
12568 Diff -= C->getAPInt() * DiffMul;
12569 }
12570 } else
12571 Multiplicity[S] += Mul;
12572 };
12573 auto Decompose = [&](const SCEV *S, int Mul) {
12574 if (isa<SCEVAddExpr>(S)) {
12575 for (const SCEV *Op : S->operands())
12576 Add(Op, Mul);
12577 } else
12578 Add(S, Mul);
12579 };
12580 Decompose(More, 1);
12581 Decompose(Less, -1);
12582
12583 // Check whether all the non-constants cancel out, or reduce to new
12584 // More/Less values.
12585 const SCEV *NewMore = nullptr, *NewLess = nullptr;
12586 for (const auto &[S, Mul] : Multiplicity) {
12587 if (Mul == 0)
12588 continue;
12589 if (Mul == 1) {
12590 if (NewMore)
12591 return std::nullopt;
12592 NewMore = S;
12593 } else if (Mul == -1) {
12594 if (NewLess)
12595 return std::nullopt;
12596 NewLess = S;
12597 } else
12598 return std::nullopt;
12599 }
12600
12601 // Values stayed the same, no point in trying further.
12602 if (NewMore == More || NewLess == Less)
12603 return std::nullopt;
12604
12605 More = NewMore;
12606 Less = NewLess;
12607
12608 // Reduced to constant.
12609 if (!More && !Less)
12610 return Diff;
12611
12612 // Left with variable on only one side, bail out.
12613 if (!More || !Less)
12614 return std::nullopt;
12615 }
12616
12617 // Did not reduce to constant.
12618 return std::nullopt;
12619}
12620
12621bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
12622 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12623 const SCEV *FoundRHS, const Instruction *CtxI) {
12624 // Try to recognize the following pattern:
12625 //
12626 // FoundRHS = ...
12627 // ...
12628 // loop:
12629 // FoundLHS = {Start,+,W}
12630 // context_bb: // Basic block from the same loop
12631 // known(Pred, FoundLHS, FoundRHS)
12632 //
12633 // If some predicate is known in the context of a loop, it is also known on
12634 // each iteration of this loop, including the first iteration. Therefore, in
12635 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
12636 // prove the original pred using this fact.
12637 if (!CtxI)
12638 return false;
12639 const BasicBlock *ContextBB = CtxI->getParent();
12640 // Make sure AR varies in the context block.
12641 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
12642 const Loop *L = AR->getLoop();
12643 const auto *Latch = L->getLoopLatch();
12644 // Make sure that context belongs to the loop and executes on 1st iteration
12645 // (if it ever executes at all).
12646 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12647 return false;
12648 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
12649 return false;
12650 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
12651 }
12652
12653 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
12654 const Loop *L = AR->getLoop();
12655 const auto *Latch = L->getLoopLatch();
12656 // Make sure that context belongs to the loop and executes on 1st iteration
12657 // (if it ever executes at all).
12658 if (!L->contains(ContextBB) || !Latch || !DT.dominates(ContextBB, Latch))
12659 return false;
12660 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
12661 return false;
12662 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
12663 }
12664
12665 return false;
12666}
12667
12668bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred,
12669 const SCEV *LHS,
12670 const SCEV *RHS,
12671 const SCEV *FoundLHS,
12672 const SCEV *FoundRHS) {
12673 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
12674 return false;
12675
12676 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
12677 if (!AddRecLHS)
12678 return false;
12679
12680 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12681 if (!AddRecFoundLHS)
12682 return false;
12683
12684 // We'd like to let SCEV reason about control dependencies, so we constrain
12685 // both the inequalities to be about add recurrences on the same loop. This
12686 // way we can use isLoopEntryGuardedByCond later.
12687
12688 const Loop *L = AddRecFoundLHS->getLoop();
12689 if (L != AddRecLHS->getLoop())
12690 return false;
12691
12692 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
12693 //
12694 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
12695 // ... (2)
12696 //
12697 // Informal proof for (2), assuming (1) [*]:
12698 //
12699 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
12700 //
12701 // Then
12702 //
12703 // FoundLHS s< FoundRHS s< INT_MIN - C
12704 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
12705 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
12706 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
12707 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
12708 // <=> FoundLHS + C s< FoundRHS + C
12709 //
12710 // [*]: (1) can be proved by ruling out overflow.
12711 //
12712 // [**]: This can be proved by analyzing all the four possibilities:
12713 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
12714 // (A s>= 0, B s>= 0).
12715 //
12716 // Note:
12717 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
12718 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
12719 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
12720 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
12721 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
12722 // C)".
12723
12724 std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
12725 if (!LDiff)
12726 return false;
12727 std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
12728 if (!RDiff || *LDiff != *RDiff)
12729 return false;
12730
12731 if (LDiff->isMinValue())
12732 return true;
12733
12734 APInt FoundRHSLimit;
12735
12736 if (Pred == CmpInst::ICMP_ULT) {
12737 FoundRHSLimit = -(*RDiff);
12738 } else {
12739 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
12740 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
12741 }
12742
12743 // Try to prove (1) or (2), as needed.
12744 return isAvailableAtLoopEntry(FoundRHS, L) &&
12745 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
12746 getConstant(FoundRHSLimit));
12747}
12748
12749bool ScalarEvolution::isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS,
12750 const SCEV *RHS, const SCEV *FoundLHS,
12751 const SCEV *FoundRHS, unsigned Depth) {
12752 const PHINode *LPhi = nullptr, *RPhi = nullptr;
12753
12754 llvm::scope_exit ClearOnExit([&]() {
12755 if (LPhi) {
12756 bool Erased = PendingMerges.erase(LPhi);
12757 assert(Erased && "Failed to erase LPhi!");
12758 (void)Erased;
12759 }
12760 if (RPhi) {
12761 bool Erased = PendingMerges.erase(RPhi);
12762 assert(Erased && "Failed to erase RPhi!");
12763 (void)Erased;
12764 }
12765 });
12766
12767 // Find respective Phis and check that they are not being pending.
12768 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
12769 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
12770 if (!PendingMerges.insert(Phi).second)
12771 return false;
12772 LPhi = Phi;
12773 }
12774 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
12775 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
12776 // If we detect a loop of Phi nodes being processed by this method, for
12777 // example:
12778 //
12779 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
12780 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
12781 //
12782 // we don't want to deal with a case that complex, so return conservative
12783 // answer false.
12784 if (!PendingMerges.insert(Phi).second)
12785 return false;
12786 RPhi = Phi;
12787 }
12788
12789 // If none of LHS, RHS is a Phi, nothing to do here.
12790 if (!LPhi && !RPhi)
12791 return false;
12792
12793 // If there is a SCEVUnknown Phi we are interested in, make it left.
12794 if (!LPhi) {
12795 std::swap(LHS, RHS);
12796 std::swap(FoundLHS, FoundRHS);
12797 std::swap(LPhi, RPhi);
12799 }
12800
12801 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
12802 const BasicBlock *LBB = LPhi->getParent();
12803 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
12804
12805 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
12806 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
12807 isImpliedCondOperandsViaRanges(Pred, S1, S2, Pred, FoundLHS, FoundRHS) ||
12808 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
12809 };
12810
12811 if (RPhi && RPhi->getParent() == LBB) {
12812 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
12813 // If we compare two Phis from the same block, and for each entry block
12814 // the predicate is true for incoming values from this block, then the
12815 // predicate is also true for the Phis.
12816 for (const BasicBlock *IncBB : predecessors(LBB)) {
12817 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12818 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
12819 if (!ProvedEasily(L, R))
12820 return false;
12821 }
12822 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
12823 // Case two: RHS is also a Phi from the same basic block, and it is an
12824 // AddRec. It means that there is a loop which has both AddRec and Unknown
12825 // PHIs, for it we can compare incoming values of AddRec from above the loop
12826 // and latch with their respective incoming values of LPhi.
12827 // TODO: Generalize to handle loops with many inputs in a header.
12828 if (LPhi->getNumIncomingValues() != 2) return false;
12829
12830 auto *RLoop = RAR->getLoop();
12831 auto *Predecessor = RLoop->getLoopPredecessor();
12832 assert(Predecessor && "Loop with AddRec with no predecessor?");
12833 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
12834 if (!ProvedEasily(L1, RAR->getStart()))
12835 return false;
12836 auto *Latch = RLoop->getLoopLatch();
12837 assert(Latch && "Loop with AddRec with no latch?");
12838 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
12839 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
12840 return false;
12841 } else {
12842 // In all other cases go over inputs of LHS and compare each of them to RHS,
12843 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
12844 // At this point RHS is either a non-Phi, or it is a Phi from some block
12845 // different from LBB.
12846 for (const BasicBlock *IncBB : predecessors(LBB)) {
12847 // Check that RHS is available in this block.
12848 if (!dominates(RHS, IncBB))
12849 return false;
12850 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
12851 // Make sure L does not refer to a value from a potentially previous
12852 // iteration of a loop.
12853 if (!properlyDominates(L, LBB))
12854 return false;
12855 // Addrecs are considered to properly dominate their loop, so are missed
12856 // by the previous check. Discard any values that have computable
12857 // evolution in this loop.
12858 if (auto *Loop = LI.getLoopFor(LBB))
12859 if (hasComputableLoopEvolution(L, Loop))
12860 return false;
12861 if (!ProvedEasily(L, RHS))
12862 return false;
12863 }
12864 }
12865 return true;
12866}
12867
12868bool ScalarEvolution::isImpliedCondOperandsViaShift(CmpPredicate Pred,
12869 const SCEV *LHS,
12870 const SCEV *RHS,
12871 const SCEV *FoundLHS,
12872 const SCEV *FoundRHS) {
12873 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
12874 // sure that we are dealing with same LHS.
12875 if (RHS == FoundRHS) {
12876 std::swap(LHS, RHS);
12877 std::swap(FoundLHS, FoundRHS);
12879 }
12880 if (LHS != FoundLHS)
12881 return false;
12882
12883 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
12884 if (!SUFoundRHS)
12885 return false;
12886
12887 Value *Shiftee, *ShiftValue;
12888
12889 using namespace PatternMatch;
12890 if (match(SUFoundRHS->getValue(),
12891 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
12892 auto *ShifteeS = getSCEV(Shiftee);
12893 // Prove one of the following:
12894 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
12895 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
12896 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12897 // ---> LHS <s RHS
12898 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
12899 // ---> LHS <=s RHS
12900 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
12901 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
12902 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
12903 if (isKnownNonNegative(ShifteeS))
12904 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
12905 }
12906
12907 return false;
12908}
12909
12910bool ScalarEvolution::isImpliedCondOperandsViaMatchingDiff(
12911 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const SCEV *FoundLHS,
12912 const SCEV *FoundRHS) {
12913 // Only valid for equality predicates: (A == B) implies (C == D) when
12914 // the SCEV difference A - B equals C - D (they check the same
12915 // underlying relationship at every iteration).
12916 if (!ICmpInst::isEquality(Pred))
12917 return false;
12918
12919 // Restrict to cases involving loop recurrences - that's where this
12920 // pattern arises (correlated IV comparisons). This avoids calling
12921 // getMinusSCEV on arbitrary non-loop expressions.
12923 (!isa<SCEVAddRecExpr>(FoundLHS) && !isa<SCEVAddRecExpr>(FoundRHS)))
12924 return false;
12925
12926 // AddRecs from different loops can never produce matching differences.
12927 const SCEVAddRecExpr *QueryAddRec = dyn_cast<SCEVAddRecExpr>(LHS);
12928 if (!QueryAddRec)
12929 QueryAddRec = cast<SCEVAddRecExpr>(RHS);
12930 const SCEVAddRecExpr *FoundAddRec = dyn_cast<SCEVAddRecExpr>(FoundLHS);
12931 if (!FoundAddRec)
12932 FoundAddRec = cast<SCEVAddRecExpr>(FoundRHS);
12933 if (QueryAddRec->getLoop() != FoundAddRec->getLoop())
12934 return false;
12935
12936 // If the strides differ, the differences can never match.
12937 if (QueryAddRec->getStepRecurrence(*this) !=
12938 FoundAddRec->getStepRecurrence(*this))
12939 return false;
12940
12941 // Compute differences. For pointer-typed operands sharing the same base,
12942 // getMinusSCEV strips the common base and returns an integer SCEV.
12943 // For example, {base,+,8} - (base+8*n) = {-8n,+,8}
12944 const SCEV *FoundDiff = getMinusSCEV(FoundLHS, FoundRHS);
12945 if (isa<SCEVCouldNotCompute>(FoundDiff))
12946 return false;
12947
12948 const SCEV *Diff = getMinusSCEV(LHS, RHS);
12949 if (isa<SCEVCouldNotCompute>(Diff))
12950 return false;
12951
12952 return Diff == FoundDiff;
12953}
12954
12955bool ScalarEvolution::isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
12956 const SCEV *RHS,
12957 const SCEV *FoundLHS,
12958 const SCEV *FoundRHS,
12959 const Instruction *CtxI) {
12960 return isImpliedCondOperandsViaRanges(Pred, LHS, RHS, Pred, FoundLHS,
12961 FoundRHS) ||
12962 isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS,
12963 FoundRHS) ||
12964 isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS) ||
12965 isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
12966 CtxI) ||
12967 isImpliedCondOperandsViaMatchingDiff(Pred, LHS, RHS, FoundLHS,
12968 FoundRHS) ||
12969 isImpliedCondOperandsHelper(Pred, LHS, RHS, FoundLHS, FoundRHS);
12970}
12971
12972/// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
12973template <typename MinMaxExprType>
12974static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
12975 const SCEV *Candidate) {
12976 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
12977 if (!MinMaxExpr)
12978 return false;
12979
12980 return is_contained(MinMaxExpr->operands(), Candidate);
12981}
12982
12984 CmpPredicate Pred, const SCEV *LHS,
12985 const SCEV *RHS) {
12986 // If both sides are affine addrecs for the same loop, with equal
12987 // steps, and we know the recurrences don't wrap, then we only
12988 // need to check the predicate on the starting values.
12989
12990 if (!ICmpInst::isRelational(Pred))
12991 return false;
12992
12993 const SCEV *LStart, *RStart, *Step;
12994 const Loop *L;
12995 if (!match(LHS,
12996 m_scev_AffineAddRec(m_SCEV(LStart), m_SCEV(Step), m_Loop(L))) ||
12998 m_SpecificLoop(L))))
12999 return false;
13004 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
13005 return false;
13006
13007 return SE.isKnownPredicate(Pred, LStart, RStart);
13008}
13009
13010/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
13011/// expression?
13013 const SCEV *LHS, const SCEV *RHS) {
13014 switch (Pred) {
13015 default:
13016 return false;
13017
13018 case ICmpInst::ICMP_SGE:
13019 std::swap(LHS, RHS);
13020 [[fallthrough]];
13021 case ICmpInst::ICMP_SLE:
13022 return
13023 // min(A, ...) <= A
13025 // A <= max(A, ...)
13027
13028 case ICmpInst::ICMP_UGE:
13029 std::swap(LHS, RHS);
13030 [[fallthrough]];
13031 case ICmpInst::ICMP_ULE:
13032 return
13033 // min(A, ...) <= A
13034 // FIXME: what about umin_seq?
13036 // A <= max(A, ...)
13038
13039 case ICmpInst::ICMP_UGT:
13040 std::swap(LHS, RHS);
13041 [[fallthrough]];
13042 case ICmpInst::ICMP_ULT:
13043 // umin(Ops) u<= each Op, so proving Op u< RHS for any Op proves
13044 // umin(Ops) u< RHS.
13045 //
13046 // Use computeConstantDifference instead of the more powerful
13047 // isKnownPredicate to keep this check cheap: isKnownPredicateViaMinOrMax
13048 // is called from isKnownViaNonRecursiveReasoning, so recursing into
13049 // the full predicate prover would be expensive.
13050 if (const auto *Min = dyn_cast<SCEVUMinExpr>(LHS)) {
13051 for (SCEVUse Op : Min->operands()) {
13052 std::optional<APInt> Diff = SE.computeConstantDifference(RHS, Op);
13053 // When Op and RHS share a common base differing by a
13054 // constant offset D (RHS - Op = D), Op u< RHS holds iff D != 0 and
13055 // RHS >= D (unsigned), i.e. the subtraction doesn't underflow.
13056 if (Diff && !Diff->isZero() && SE.getUnsignedRangeMin(RHS).uge(*Diff))
13057 return true;
13058 }
13059 }
13060 return false;
13061 }
13062
13063 llvm_unreachable("covered switch fell through?!");
13064}
13065
13066bool ScalarEvolution::isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
13067 const SCEV *RHS,
13068 const SCEV *FoundLHS,
13069 const SCEV *FoundRHS,
13070 unsigned Depth) {
13073 "LHS and RHS have different sizes?");
13074 assert(getTypeSizeInBits(FoundLHS->getType()) ==
13075 getTypeSizeInBits(FoundRHS->getType()) &&
13076 "FoundLHS and FoundRHS have different sizes?");
13077 // We want to avoid hurting the compile time with analysis of too big trees.
13079 return false;
13080
13081 // We only want to work with GT comparison so far.
13082 if (ICmpInst::isLT(Pred)) {
13084 std::swap(LHS, RHS);
13085 std::swap(FoundLHS, FoundRHS);
13086 }
13087
13089
13090 // For unsigned, try to reduce it to corresponding signed comparison.
13091 if (P == ICmpInst::ICMP_UGT)
13092 // We can replace unsigned predicate with its signed counterpart if all
13093 // involved values are non-negative.
13094 // TODO: We could have better support for unsigned.
13095 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
13096 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
13097 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
13098 // use this fact to prove that LHS and RHS are non-negative.
13099 const SCEV *MinusOne = getMinusOne(LHS->getType());
13100 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
13101 FoundRHS) &&
13102 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
13103 FoundRHS))
13105 }
13106
13107 if (P != ICmpInst::ICMP_SGT)
13108 return false;
13109
13110 auto GetOpFromSExt = [&](const SCEV *S) -> const SCEV * {
13111 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
13112 return Ext->getOperand();
13113 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
13114 // the constant in some cases.
13115 return S;
13116 };
13117
13118 // Acquire values from extensions.
13119 auto *OrigLHS = LHS;
13120 auto *OrigFoundLHS = FoundLHS;
13121 LHS = GetOpFromSExt(LHS);
13122 FoundLHS = GetOpFromSExt(FoundLHS);
13123
13124 // Is the SGT predicate can be proved trivially or using the found context.
13125 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
13126 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
13127 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
13128 FoundRHS, Depth + 1);
13129 };
13130
13131 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
13132 // We want to avoid creation of any new non-constant SCEV. Since we are
13133 // going to compare the operands to RHS, we should be certain that we don't
13134 // need any size extensions for this. So let's decline all cases when the
13135 // sizes of types of LHS and RHS do not match.
13136 // TODO: Maybe try to get RHS from sext to catch more cases?
13138 return false;
13139
13140 // Should not overflow.
13141 if (!LHSAddExpr->hasNoSignedWrap())
13142 return false;
13143
13144 SCEVUse LL = LHSAddExpr->getOperand(0);
13145 SCEVUse LR = LHSAddExpr->getOperand(1);
13146 auto *MinusOne = getMinusOne(RHS->getType());
13147
13148 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
13149 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
13150 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
13151 };
13152 // Try to prove the following rule:
13153 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
13154 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
13155 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
13156 return true;
13157 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
13158 Value *LL, *LR;
13159 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
13160
13161 using namespace llvm::PatternMatch;
13162
13163 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
13164 // Rules for division.
13165 // We are going to perform some comparisons with Denominator and its
13166 // derivative expressions. In general case, creating a SCEV for it may
13167 // lead to a complex analysis of the entire graph, and in particular it
13168 // can request trip count recalculation for the same loop. This would
13169 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
13170 // this, we only want to create SCEVs that are constants in this section.
13171 // So we bail if Denominator is not a constant.
13172 if (!isa<ConstantInt>(LR))
13173 return false;
13174
13175 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
13176
13177 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
13178 // then a SCEV for the numerator already exists and matches with FoundLHS.
13179 auto *Numerator = getExistingSCEV(LL);
13180 if (!Numerator || Numerator->getType() != FoundLHS->getType())
13181 return false;
13182
13183 // Make sure that the numerator matches with FoundLHS and the denominator
13184 // is positive.
13185 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
13186 return false;
13187
13188 auto *DTy = Denominator->getType();
13189 auto *FRHSTy = FoundRHS->getType();
13190 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
13191 // One of types is a pointer and another one is not. We cannot extend
13192 // them properly to a wider type, so let us just reject this case.
13193 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
13194 // to avoid this check.
13195 return false;
13196
13197 // Given that:
13198 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
13199 auto *WTy = getWiderType(DTy, FRHSTy);
13200 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
13201 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
13202
13203 // Try to prove the following rule:
13204 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
13205 // For example, given that FoundLHS > 2. It means that FoundLHS is at
13206 // least 3. If we divide it by Denominator < 4, we will have at least 1.
13207 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
13208 if (isKnownNonPositive(RHS) &&
13209 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
13210 return true;
13211
13212 // Try to prove the following rule:
13213 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
13214 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
13215 // If we divide it by Denominator > 2, then:
13216 // 1. If FoundLHS is negative, then the result is 0.
13217 // 2. If FoundLHS is non-negative, then the result is non-negative.
13218 // Anyways, the result is non-negative.
13219 auto *MinusOne = getMinusOne(WTy);
13220 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
13221 if (isKnownNegative(RHS) &&
13222 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
13223 return true;
13224 }
13225 }
13226
13227 // If our expression contained SCEVUnknown Phis, and we split it down and now
13228 // need to prove something for them, try to prove the predicate for every
13229 // possible incoming values of those Phis.
13230 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
13231 return true;
13232
13233 return false;
13234}
13235
13237 const SCEV *RHS) {
13238 // zext x u<= sext x, sext x s<= zext x
13239 const SCEV *Op;
13240 switch (Pred) {
13241 case ICmpInst::ICMP_SGE:
13242 std::swap(LHS, RHS);
13243 [[fallthrough]];
13244 case ICmpInst::ICMP_SLE: {
13245 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
13246 return match(LHS, m_scev_SExt(m_SCEV(Op))) &&
13248 }
13249 case ICmpInst::ICMP_UGE:
13250 std::swap(LHS, RHS);
13251 [[fallthrough]];
13252 case ICmpInst::ICMP_ULE: {
13253 // If operand >=u 0 then ZExt == SExt. If operand <u 0 then ZExt <u SExt.
13254 return match(LHS, m_scev_ZExt(m_SCEV(Op))) &&
13256 }
13257 default:
13258 return false;
13259 };
13260 llvm_unreachable("unhandled case");
13261}
13262
13263bool ScalarEvolution::isKnownViaNonRecursiveReasoning(CmpPredicate Pred,
13264 SCEVUse LHS,
13265 SCEVUse RHS) {
13266 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
13267 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
13268 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
13269 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
13270 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
13271}
13272
13273bool ScalarEvolution::isImpliedCondOperandsHelper(CmpPredicate Pred,
13274 const SCEV *LHS,
13275 const SCEV *RHS,
13276 const SCEV *FoundLHS,
13277 const SCEV *FoundRHS) {
13278 switch (Pred) {
13279 default:
13280 llvm_unreachable("Unexpected CmpPredicate value!");
13281 case ICmpInst::ICMP_EQ:
13282 case ICmpInst::ICMP_NE:
13283 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
13284 return true;
13285 break;
13286 case ICmpInst::ICMP_SLT:
13287 case ICmpInst::ICMP_SLE:
13288 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
13289 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
13290 return true;
13291 break;
13292 case ICmpInst::ICMP_SGT:
13293 case ICmpInst::ICMP_SGE:
13294 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
13295 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
13296 return true;
13297 break;
13298 case ICmpInst::ICMP_ULT:
13299 case ICmpInst::ICMP_ULE:
13300 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
13301 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
13302 return true;
13303 break;
13304 case ICmpInst::ICMP_UGT:
13305 case ICmpInst::ICMP_UGE:
13306 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
13307 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
13308 return true;
13309 break;
13310 }
13311
13312 // Maybe it can be proved via operations?
13313 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
13314 return true;
13315
13316 return false;
13317}
13318
13319bool ScalarEvolution::isImpliedCondOperandsViaRanges(
13320 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, CmpPredicate FoundPred,
13321 const SCEV *FoundLHS, const SCEV *FoundRHS) {
13322 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
13323 // The restriction on `FoundRHS` be lifted easily -- it exists only to
13324 // reduce the compile time impact of this optimization.
13325 return false;
13326
13327 std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
13328 if (!Addend)
13329 return false;
13330
13331 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
13332
13333 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
13334 // antecedent "`FoundLHS` `FoundPred` `FoundRHS`".
13335 ConstantRange FoundLHSRange =
13336 ConstantRange::makeExactICmpRegion(FoundPred, ConstFoundRHS);
13337
13338 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
13339 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
13340
13341 // We can also compute the range of values for `LHS` that satisfy the
13342 // consequent, "`LHS` `Pred` `RHS`":
13343 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
13344 // The antecedent implies the consequent if every value of `LHS` that
13345 // satisfies the antecedent also satisfies the consequent.
13346 return LHSRange.icmp(Pred, ConstRHS);
13347}
13348
13349bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
13350 bool IsSigned) {
13351 assert(isKnownPositive(Stride) && "Positive stride expected!");
13352
13353 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13354 const SCEV *One = getOne(Stride->getType());
13355
13356 if (IsSigned) {
13357 APInt MaxRHS = getSignedRangeMax(RHS);
13358 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
13359 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13360
13361 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
13362 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
13363 }
13364
13365 APInt MaxRHS = getUnsignedRangeMax(RHS);
13366 APInt MaxValue = APInt::getMaxValue(BitWidth);
13367 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13368
13369 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
13370 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
13371}
13372
13373bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
13374 bool IsSigned) {
13375
13376 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
13377 const SCEV *One = getOne(Stride->getType());
13378
13379 if (IsSigned) {
13380 APInt MinRHS = getSignedRangeMin(RHS);
13381 APInt MinValue = APInt::getSignedMinValue(BitWidth);
13382 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
13383
13384 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
13385 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
13386 }
13387
13388 APInt MinRHS = getUnsignedRangeMin(RHS);
13389 APInt MinValue = APInt::getMinValue(BitWidth);
13390 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
13391
13392 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
13393 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
13394}
13395
13397 // umin(N, 1) + floor((N - umin(N, 1)) / D)
13398 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
13399 // expression fixes the case of N=0.
13400 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
13401 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
13402 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
13403}
13404
13405const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
13406 const SCEV *Stride,
13407 const SCEV *End,
13408 unsigned BitWidth,
13409 bool IsSigned) {
13410 // The logic in this function assumes we can represent a positive stride.
13411 // If we can't, the backedge-taken count must be zero.
13412 if (IsSigned && BitWidth == 1)
13413 return getZero(Stride->getType());
13414
13415 // This code below only been closely audited for negative strides in the
13416 // unsigned comparison case, it may be correct for signed comparison, but
13417 // that needs to be established.
13418 if (IsSigned && isKnownNegative(Stride))
13419 return getCouldNotCompute();
13420
13421 // Calculate the maximum backedge count based on the range of values
13422 // permitted by Start, End, and Stride.
13423 APInt MinStart =
13424 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
13425
13426 APInt MinStride =
13427 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
13428
13429 // We assume either the stride is positive, or the backedge-taken count
13430 // is zero. So force StrideForMaxBECount to be at least one.
13431 APInt One(BitWidth, 1);
13432 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
13433 : APIntOps::umax(One, MinStride);
13434
13435 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
13436 : APInt::getMaxValue(BitWidth);
13437 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
13438
13439 // Although End can be a MAX expression we estimate MaxEnd considering only
13440 // the case End = RHS of the loop termination condition. This is safe because
13441 // in the other case (End - Start) is zero, leading to a zero maximum backedge
13442 // taken count.
13443 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
13444 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
13445
13446 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
13447 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
13448 : APIntOps::umax(MaxEnd, MinStart);
13449
13450 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
13451 getConstant(StrideForMaxBECount) /* Step */);
13452}
13453
13455ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
13456 const Loop *L, bool IsSigned,
13457 bool ControlsOnlyExit, bool AllowPredicates) {
13459
13461 bool PredicatedIV = false;
13462 if (!IV) {
13463 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
13464 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
13465 if (AR && AR->getLoop() == L && AR->isAffine()) {
13466 auto canProveNUW = [&]() {
13467 // We can use the comparison to infer no-wrap flags only if it fully
13468 // controls the loop exit.
13469 if (!ControlsOnlyExit)
13470 return false;
13471
13472 if (!isLoopInvariant(RHS, L))
13473 return false;
13474
13475 if (!isKnownNonZero(AR->getStepRecurrence(*this)))
13476 // We need the sequence defined by AR to strictly increase in the
13477 // unsigned integer domain for the logic below to hold.
13478 return false;
13479
13480 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
13481 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
13482 // If RHS <=u Limit, then there must exist a value V in the sequence
13483 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
13484 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
13485 // overflow occurs. This limit also implies that a signed comparison
13486 // (in the wide bitwidth) is equivalent to an unsigned comparison as
13487 // the high bits on both sides must be zero.
13488 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
13489 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
13490 Limit = Limit.zext(OuterBitWidth);
13491 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
13492 };
13493 auto Flags = AR->getNoWrapFlags();
13494 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
13495 Flags = setFlags(Flags, SCEV::FlagNUW);
13496
13497 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
13498 if (AR->hasNoUnsignedWrap()) {
13499 // Emulate what getZeroExtendExpr would have done during construction
13500 // if we'd been able to infer the fact just above at that time.
13501 const SCEV *Step = AR->getStepRecurrence(*this);
13502 Type *Ty = ZExt->getType();
13503 auto *S = getAddRecExpr(
13505 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
13507 }
13508 }
13509 }
13510 }
13511
13512
13513 if (!IV && AllowPredicates) {
13514 // Try to make this an AddRec using runtime tests, in the first X
13515 // iterations of this loop, where X is the SCEV expression found by the
13516 // algorithm below.
13517 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13518 PredicatedIV = true;
13519 }
13520
13521 // Avoid weird loops
13522 if (!IV || IV->getLoop() != L || !IV->isAffine())
13523 return getCouldNotCompute();
13524
13525 // A precondition of this method is that the condition being analyzed
13526 // reaches an exiting branch which dominates the latch. Given that, we can
13527 // assume that an increment which violates the nowrap specification and
13528 // produces poison must cause undefined behavior when the resulting poison
13529 // value is branched upon and thus we can conclude that the backedge is
13530 // taken no more often than would be required to produce that poison value.
13531 // Note that a well defined loop can exit on the iteration which violates
13532 // the nowrap specification if there is another exit (either explicit or
13533 // implicit/exceptional) which causes the loop to execute before the
13534 // exiting instruction we're analyzing would trigger UB.
13535 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13536 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13538
13539 const SCEV *Stride = IV->getStepRecurrence(*this);
13540
13541 bool PositiveStride = isKnownPositive(Stride);
13542
13543 // Avoid negative or zero stride values.
13544 if (!PositiveStride) {
13545 // We can compute the correct backedge taken count for loops with unknown
13546 // strides if we can prove that the loop is not an infinite loop with side
13547 // effects. Here's the loop structure we are trying to handle -
13548 //
13549 // i = start
13550 // do {
13551 // A[i] = i;
13552 // i += s;
13553 // } while (i < end);
13554 //
13555 // The backedge taken count for such loops is evaluated as -
13556 // (max(end, start + stride) - start - 1) /u stride
13557 //
13558 // The additional preconditions that we need to check to prove correctness
13559 // of the above formula is as follows -
13560 //
13561 // a) IV is either nuw or nsw depending upon signedness (indicated by the
13562 // NoWrap flag).
13563 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
13564 // no side effects within the loop)
13565 // c) loop has a single static exit (with no abnormal exits)
13566 //
13567 // Precondition a) implies that if the stride is negative, this is a single
13568 // trip loop. The backedge taken count formula reduces to zero in this case.
13569 //
13570 // Precondition b) and c) combine to imply that if rhs is invariant in L,
13571 // then a zero stride means the backedge can't be taken without executing
13572 // undefined behavior.
13573 //
13574 // The positive stride case is the same as isKnownPositive(Stride) returning
13575 // true (original behavior of the function).
13576 //
13577 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
13579 return getCouldNotCompute();
13580
13581 if (!isKnownNonZero(Stride)) {
13582 // If we have a step of zero, and RHS isn't invariant in L, we don't know
13583 // if it might eventually be greater than start and if so, on which
13584 // iteration. We can't even produce a useful upper bound.
13585 if (!isLoopInvariant(RHS, L))
13586 return getCouldNotCompute();
13587
13588 // We allow a potentially zero stride, but we need to divide by stride
13589 // below. Since the loop can't be infinite and this check must control
13590 // the sole exit, we can infer the exit must be taken on the first
13591 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
13592 // we know the numerator in the divides below must be zero, so we can
13593 // pick an arbitrary non-zero value for the denominator (e.g. stride)
13594 // and produce the right result.
13595 // FIXME: Handle the case where Stride is poison?
13596 auto wouldZeroStrideBeUB = [&]() {
13597 // Proof by contradiction. Suppose the stride were zero. If we can
13598 // prove that the backedge *is* taken on the first iteration, then since
13599 // we know this condition controls the sole exit, we must have an
13600 // infinite loop. We can't have a (well defined) infinite loop per
13601 // check just above.
13602 // Note: The (Start - Stride) term is used to get the start' term from
13603 // (start' + stride,+,stride). Remember that we only care about the
13604 // result of this expression when stride == 0 at runtime.
13605 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
13606 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
13607 };
13608 if (!wouldZeroStrideBeUB()) {
13609 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
13610 }
13611 }
13612 } else if (!NoWrap) {
13613 // Avoid proven overflow cases: this will ensure that the backedge taken
13614 // count will not generate any unsigned overflow.
13615 if (canIVOverflowOnLT(RHS, Stride, IsSigned))
13616 return getCouldNotCompute();
13617 }
13618
13619 // On all paths just preceeding, we established the following invariant:
13620 // IV can be assumed not to overflow up to and including the exiting
13621 // iteration. We proved this in one of two ways:
13622 // 1) We can show overflow doesn't occur before the exiting iteration
13623 // 1a) canIVOverflowOnLT, and b) step of one
13624 // 2) We can show that if overflow occurs, the loop must execute UB
13625 // before any possible exit.
13626 // Note that we have not yet proved RHS invariant (in general).
13627
13628 const SCEV *Start = IV->getStart();
13629
13630 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
13631 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
13632 // Use integer-typed versions for actual computation; we can't subtract
13633 // pointers in general.
13634 const SCEV *OrigStart = Start;
13635 const SCEV *OrigRHS = RHS;
13636 if (Start->getType()->isPointerTy()) {
13637 Start = getPtrToAddrExpr(Start);
13638 if (isa<SCEVCouldNotCompute>(Start))
13639 return Start;
13640 }
13641 if (RHS->getType()->isPointerTy()) {
13644 return RHS;
13645 }
13646
13647 const SCEV *End = nullptr, *BECount = nullptr,
13648 *BECountIfBackedgeTaken = nullptr;
13649 if (!isLoopInvariant(RHS, L)) {
13650 const auto *RHSAddRec = dyn_cast<SCEVAddRecExpr>(RHS);
13651 if (PositiveStride && RHSAddRec != nullptr && RHSAddRec->getLoop() == L &&
13652 any(RHSAddRec->getNoWrapFlags())) {
13653 // The structure of loop we are trying to calculate backedge count of:
13654 //
13655 // left = left_start
13656 // right = right_start
13657 //
13658 // while(left < right){
13659 // ... do something here ...
13660 // left += s1; // stride of left is s1 (s1 > 0)
13661 // right += s2; // stride of right is s2 (s2 < 0)
13662 // }
13663 //
13664
13665 const SCEV *RHSStart = RHSAddRec->getStart();
13666 const SCEV *RHSStride = RHSAddRec->getStepRecurrence(*this);
13667
13668 // If Stride - RHSStride is positive and does not overflow, we can write
13669 // backedge count as ->
13670 // ceil((End - Start) /u (Stride - RHSStride))
13671 // Where, End = max(RHSStart, Start)
13672
13673 // Check if RHSStride < 0 and Stride - RHSStride will not overflow.
13674 if (isKnownNegative(RHSStride) &&
13675 willNotOverflow(Instruction::Sub, /*Signed=*/true, Stride,
13676 RHSStride)) {
13677
13678 const SCEV *Denominator = getMinusSCEV(Stride, RHSStride);
13679 if (isKnownPositive(Denominator)) {
13680 End = IsSigned ? getSMaxExpr(RHSStart, Start)
13681 : getUMaxExpr(RHSStart, Start);
13682
13683 // We can do this because End >= Start, as End = max(RHSStart, Start)
13684 const SCEV *Delta = getMinusSCEV(End, Start);
13685
13686 BECount = getUDivCeilSCEV(Delta, Denominator);
13687 BECountIfBackedgeTaken =
13688 getUDivCeilSCEV(getMinusSCEV(RHSStart, Start), Denominator);
13689 }
13690 }
13691 }
13692 if (BECount == nullptr) {
13693 // If we cannot calculate ExactBECount, we can calculate the MaxBECount,
13694 // given the start, stride and max value for the end bound of the
13695 // loop (RHS), and the fact that IV does not overflow (which is
13696 // checked above).
13697 const SCEV *MaxBECount = computeMaxBECountForLT(
13698 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13699 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
13700 MaxBECount, false /*MaxOrZero*/, Predicates);
13701 }
13702 } else {
13703 // We use the expression (max(End,Start)-Start)/Stride to describe the
13704 // backedge count, as if the backedge is taken at least once
13705 // max(End,Start) is End and so the result is as above, and if not
13706 // max(End,Start) is Start so we get a backedge count of zero.
13707 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
13708 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
13709 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
13710 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
13711 // Can we prove (max(RHS,Start) > Start - Stride?
13712 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
13713 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
13714 // In this case, we can use a refined formula for computing backedge
13715 // taken count. The general formula remains:
13716 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
13717 // We want to use the alternate formula:
13718 // "((End - 1) - (Start - Stride)) /u Stride"
13719 // Let's do a quick case analysis to show these are equivalent under
13720 // our precondition that max(RHS,Start) > Start - Stride.
13721 // * For RHS <= Start, the backedge-taken count must be zero.
13722 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13723 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
13724 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
13725 // of Stride. For 0 stride, we've use umin(1,Stride) above,
13726 // reducing this to the stride of 1 case.
13727 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil
13728 // Stride".
13729 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
13730 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
13731 // "((RHS - (Start - Stride) - 1) /u Stride".
13732 // Our preconditions trivially imply no overflow in that form.
13733 const SCEV *MinusOne = getMinusOne(Stride->getType());
13734 const SCEV *Numerator =
13735 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
13736 BECount = getUDivExpr(Numerator, Stride);
13737 }
13738
13739 if (!BECount) {
13740 auto canProveRHSGreaterThanEqualStart = [&]() {
13741 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
13742 const SCEV *GuardedRHS = applyLoopGuards(OrigRHS, L);
13743 const SCEV *GuardedStart = applyLoopGuards(OrigStart, L);
13744
13745 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart) ||
13746 isKnownPredicate(CondGE, GuardedRHS, GuardedStart))
13747 return true;
13748
13749 // (RHS > Start - 1) implies RHS >= Start.
13750 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
13751 // "Start - 1" doesn't overflow.
13752 // * For signed comparison, if Start - 1 does overflow, it's equal
13753 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
13754 // * For unsigned comparison, if Start - 1 does overflow, it's equal
13755 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
13756 //
13757 // FIXME: Should isLoopEntryGuardedByCond do this for us?
13758 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
13759 auto *StartMinusOne =
13760 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
13761 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
13762 };
13763
13764 // If we know that RHS >= Start in the context of loop, then we know
13765 // that max(RHS, Start) = RHS at this point.
13766 if (canProveRHSGreaterThanEqualStart()) {
13767 End = RHS;
13768 } else {
13769 // If RHS < Start, the backedge will be taken zero times. So in
13770 // general, we can write the backedge-taken count as:
13771 //
13772 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
13773 //
13774 // We convert it to the following to make it more convenient for SCEV:
13775 //
13776 // ceil(max(RHS, Start) - Start) / Stride
13777 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
13778
13779 // See what would happen if we assume the backedge is taken. This is
13780 // used to compute MaxBECount.
13781 BECountIfBackedgeTaken =
13782 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
13783 }
13784
13785 // At this point, we know:
13786 //
13787 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
13788 // 2. The index variable doesn't overflow.
13789 //
13790 // Therefore, we know N exists such that
13791 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
13792 // doesn't overflow.
13793 //
13794 // Using this information, try to prove whether the addition in
13795 // "(Start - End) + (Stride - 1)" has unsigned overflow.
13796 const SCEV *One = getOne(Stride->getType());
13797 bool MayAddOverflow = [&] {
13798 if (isKnownToBeAPowerOfTwo(Stride)) {
13799 // Suppose Stride is a power of two, and Start/End are unsigned
13800 // integers. Let UMAX be the largest representable unsigned
13801 // integer.
13802 //
13803 // By the preconditions of this function, we know
13804 // "(Start + Stride * N) >= End", and this doesn't overflow.
13805 // As a formula:
13806 //
13807 // End <= (Start + Stride * N) <= UMAX
13808 //
13809 // Subtracting Start from all the terms:
13810 //
13811 // End - Start <= Stride * N <= UMAX - Start
13812 //
13813 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
13814 //
13815 // End - Start <= Stride * N <= UMAX
13816 //
13817 // Stride * N is a multiple of Stride. Therefore,
13818 //
13819 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
13820 //
13821 // Since Stride is a power of two, UMAX + 1 is divisible by
13822 // Stride. Therefore, UMAX mod Stride == Stride - 1. So we can
13823 // write:
13824 //
13825 // End - Start <= Stride * N <= UMAX - Stride - 1
13826 //
13827 // Dropping the middle term:
13828 //
13829 // End - Start <= UMAX - Stride - 1
13830 //
13831 // Adding Stride - 1 to both sides:
13832 //
13833 // (End - Start) + (Stride - 1) <= UMAX
13834 //
13835 // In other words, the addition doesn't have unsigned overflow.
13836 //
13837 // A similar proof works if we treat Start/End as signed values.
13838 // Just rewrite steps before "End - Start <= Stride * N <= UMAX"
13839 // to use signed max instead of unsigned max. Note that we're
13840 // trying to prove a lack of unsigned overflow in either case.
13841 return false;
13842 }
13843 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
13844 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End
13845 // - 1. If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1
13846 // <u End. If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End -
13847 // 1 <s End.
13848 //
13849 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 ==
13850 // End.
13851 return false;
13852 }
13853 return true;
13854 }();
13855
13856 const SCEV *Delta = getMinusSCEV(End, Start);
13857 if (!MayAddOverflow) {
13858 // floor((D + (S - 1)) / S)
13859 // We prefer this formulation if it's legal because it's fewer
13860 // operations.
13861 BECount =
13862 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
13863 } else {
13864 BECount = getUDivCeilSCEV(Delta, Stride);
13865 }
13866 }
13867 }
13868
13869 const SCEV *ConstantMaxBECount;
13870 bool MaxOrZero = false;
13871 if (isa<SCEVConstant>(BECount)) {
13872 ConstantMaxBECount = BECount;
13873 } else if (BECountIfBackedgeTaken &&
13874 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
13875 // If we know exactly how many times the backedge will be taken if it's
13876 // taken at least once, then the backedge count will either be that or
13877 // zero.
13878 ConstantMaxBECount = BECountIfBackedgeTaken;
13879 MaxOrZero = true;
13880 } else {
13881 ConstantMaxBECount = computeMaxBECountForLT(
13882 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
13883 }
13884
13885 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
13886 !isa<SCEVCouldNotCompute>(BECount))
13887 ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
13888
13889 const SCEV *SymbolicMaxBECount =
13890 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13891 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
13892 Predicates);
13893}
13894
13895ScalarEvolution::ExitLimit ScalarEvolution::howManyGreaterThans(
13896 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
13897 bool ControlsOnlyExit, bool AllowPredicates) {
13899 // We handle only IV > Invariant
13900 if (!isLoopInvariant(RHS, L))
13901 return getCouldNotCompute();
13902
13903 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
13904 if (!IV && AllowPredicates)
13905 // Try to make this an AddRec using runtime tests, in the first X
13906 // iterations of this loop, where X is the SCEV expression found by the
13907 // algorithm below.
13908 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
13909
13910 // Avoid weird loops
13911 if (!IV || IV->getLoop() != L || !IV->isAffine())
13912 return getCouldNotCompute();
13913
13914 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
13915 bool NoWrap = ControlsOnlyExit && any(IV->getNoWrapFlags(WrapType));
13917
13918 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
13919
13920 // Avoid negative or zero stride values
13921 if (!isKnownPositive(Stride))
13922 return getCouldNotCompute();
13923
13924 // Avoid proven overflow cases: this will ensure that the backedge taken count
13925 // will not generate any unsigned overflow. Relaxed no-overflow conditions
13926 // exploit NoWrapFlags, allowing to optimize in presence of undefined
13927 // behaviors like the case of C language.
13928 if (!Stride->isOne() && !NoWrap)
13929 if (canIVOverflowOnGT(RHS, Stride, IsSigned))
13930 return getCouldNotCompute();
13931
13932 const SCEV *Start = IV->getStart();
13933 const SCEV *End = RHS;
13934 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
13935 // If we know that Start >= RHS in the context of loop, then we know that
13936 // min(RHS, Start) = RHS at this point.
13938 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
13939 End = RHS;
13940 else
13941 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
13942 }
13943
13944 if (Start->getType()->isPointerTy()) {
13945 Start = getPtrToAddrExpr(Start);
13946 if (isa<SCEVCouldNotCompute>(Start))
13947 return Start;
13948 }
13949 if (End->getType()->isPointerTy()) {
13950 End = getPtrToAddrExpr(End);
13951 if (isa<SCEVCouldNotCompute>(End))
13952 return End;
13953 }
13954
13955 // Compute ((Start - End) + (Stride - 1)) / Stride.
13956 // FIXME: This can overflow. Holding off on fixing this for now;
13957 // howManyGreaterThans will hopefully be gone soon.
13958 const SCEV *One = getOne(Stride->getType());
13959 const SCEV *BECount = getUDivExpr(
13960 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
13961
13962 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
13964
13965 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
13966 : getUnsignedRangeMin(Stride);
13967
13968 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
13969 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
13970 : APInt::getMinValue(BitWidth) + (MinStride - 1);
13971
13972 // Although End can be a MIN expression we estimate MinEnd considering only
13973 // the case End = RHS. This is safe because in the other case (Start - End)
13974 // is zero, leading to a zero maximum backedge taken count.
13975 APInt MinEnd =
13976 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
13977 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
13978
13979 const SCEV *ConstantMaxBECount =
13980 isa<SCEVConstant>(BECount)
13981 ? BECount
13982 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
13983 getConstant(MinStride));
13984
13985 if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
13986 ConstantMaxBECount = BECount;
13987 const SCEV *SymbolicMaxBECount =
13988 isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
13989
13990 return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
13991 Predicates);
13992}
13993
13995 ScalarEvolution &SE) const {
13996 if (Range.isFullSet()) // Infinite loop.
13997 return SE.getCouldNotCompute();
13998
13999 // If the start is a non-zero constant, shift the range to simplify things.
14000 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
14001 if (!SC->getValue()->isZero()) {
14003 Operands[0] = SE.getZero(SC->getType());
14004 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
14006 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
14007 return ShiftedAddRec->getNumIterationsInRange(
14008 Range.subtract(SC->getAPInt()), SE);
14009 // This is strange and shouldn't happen.
14010 return SE.getCouldNotCompute();
14011 }
14012
14013 // The only time we can solve this is when we have all constant indices.
14014 // Otherwise, we cannot determine the overflow conditions.
14015 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
14016 return SE.getCouldNotCompute();
14017
14018 // Okay at this point we know that all elements of the chrec are constants and
14019 // that the start element is zero.
14020
14021 // First check to see if the range contains zero. If not, the first
14022 // iteration exits.
14023 unsigned BitWidth = SE.getTypeSizeInBits(getType());
14024 if (!Range.contains(APInt(BitWidth, 0)))
14025 return SE.getZero(getType());
14026
14027 if (isAffine()) {
14028 // If this is an affine expression then we have this situation:
14029 // Solve {0,+,A} in Range === Ax in Range
14030
14031 // We know that zero is in the range. If A is positive then we know that
14032 // the upper value of the range must be the first possible exit value.
14033 // If A is negative then the lower of the range is the last possible loop
14034 // value. Also note that we already checked for a full range.
14035 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
14036 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
14037
14038 // The exit value should be (End+A)/A.
14039 APInt ExitVal = (End + A).udiv(A);
14040 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
14041
14042 // Evaluate at the exit value. If we really did fall out of the valid
14043 // range, then we computed our trip count, otherwise wrap around or other
14044 // things must have happened.
14045 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
14046 if (Range.contains(Val->getValue()))
14047 return SE.getCouldNotCompute(); // Something strange happened
14048
14049 // Ensure that the previous value is in the range.
14050 assert(Range.contains(
14052 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
14053 "Linear scev computation is off in a bad way!");
14054 return SE.getConstant(ExitValue);
14055 }
14056
14057 if (isQuadratic()) {
14058 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
14059 return SE.getConstant(*S);
14060 }
14061
14062 return SE.getCouldNotCompute();
14063}
14064
14065const SCEVAddRecExpr *
14067 assert(getNumOperands() > 1 && "AddRec with zero step?");
14068 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
14069 // but in this case we cannot guarantee that the value returned will be an
14070 // AddRec because SCEV does not have a fixed point where it stops
14071 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
14072 // may happen if we reach arithmetic depth limit while simplifying. So we
14073 // construct the returned value explicitly.
14075 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
14076 // (this + Step) is {A+B,+,B+C,+...,+,N}.
14077 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
14078 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
14079 // We know that the last operand is not a constant zero (otherwise it would
14080 // have been popped out earlier). This guarantees us that if the result has
14081 // the same last operand, then it will also not be popped out, meaning that
14082 // the returned value will be an AddRec.
14083 const SCEV *Last = getOperand(getNumOperands() - 1);
14084 assert(!Last->isZero() && "Recurrency with zero step?");
14085 Ops.push_back(Last);
14088}
14089
14090// Return true when S contains at least an undef value.
14092 return SCEVExprContains(
14093 S, [](const SCEV *S) { return match(S, m_scev_UndefOrPoison()); });
14094}
14095
14096// Return true when S contains a value that is a nullptr.
14098 return SCEVExprContains(S, [](const SCEV *S) {
14099 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
14100 return SU->getValue() == nullptr;
14101 return false;
14102 });
14103}
14104
14105/// Return the size of an element read or written by Inst.
14107 Type *Ty;
14108 Type *PtrTy;
14109 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
14110 Ty = Store->getValueOperand()->getType();
14111 PtrTy = Store->getPointerOperandType();
14112 } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
14113 Ty = Load->getType();
14114 PtrTy = Load->getPointerOperandType();
14115 } else {
14116 return nullptr;
14117 }
14118
14119 Type *ETy = getEffectiveSCEVType(PtrTy);
14120 return getSizeOfExpr(ETy, Ty);
14121}
14122
14123//===----------------------------------------------------------------------===//
14124// SCEVCallbackVH Class Implementation
14125//===----------------------------------------------------------------------===//
14126
14128 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14129 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
14130 SE->ConstantEvolutionLoopExitValue.erase(PN);
14131 SE->eraseValueFromMap(getValPtr());
14132 // this now dangles!
14133}
14134
14135void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
14136 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
14137
14138 // Forget all the expressions associated with users of the old value,
14139 // so that future queries will recompute the expressions using the new
14140 // value.
14141 SE->forgetValue(getValPtr());
14142 // this now dangles!
14143}
14144
14145ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
14146 : CallbackVH(V), SE(se) {}
14147
14148//===----------------------------------------------------------------------===//
14149// ScalarEvolution Class Implementation
14150//===----------------------------------------------------------------------===//
14151
14154 LoopInfo &LI)
14155 : F(F), DL(F.getDataLayout()), TLI(TLI), AC(AC), DT(DT), LI(LI),
14156 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
14157 LoopDispositions(64), BlockDispositions(64) {
14158 // To use guards for proving predicates, we need to scan every instruction in
14159 // relevant basic blocks, and not just terminators. Doing this is a waste of
14160 // time if the IR does not actually contain any calls to
14161 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
14162 //
14163 // This pessimizes the case where a pass that preserves ScalarEvolution wants
14164 // to _add_ guards to the module when there weren't any before, and wants
14165 // ScalarEvolution to optimize based on those guards. For now we prefer to be
14166 // efficient in lieu of being smart in that rather obscure case.
14167
14168 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
14169 F.getParent(), Intrinsic::experimental_guard);
14170 HasGuards = GuardDecl && !GuardDecl->use_empty();
14171}
14172
14174 : F(Arg.F), DL(Arg.DL), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC),
14175 DT(Arg.DT), LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
14176 ValueExprMap(std::move(Arg.ValueExprMap)),
14177 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
14178 PendingMerges(std::move(Arg.PendingMerges)),
14179 ConstantMultipleCache(std::move(Arg.ConstantMultipleCache)),
14180 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
14181 PredicatedBackedgeTakenCounts(
14182 std::move(Arg.PredicatedBackedgeTakenCounts)),
14183 BECountUsers(std::move(Arg.BECountUsers)),
14184 ConstantEvolutionLoopExitValue(
14185 std::move(Arg.ConstantEvolutionLoopExitValue)),
14186 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
14187 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
14188 LoopDispositions(std::move(Arg.LoopDispositions)),
14189 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
14190 BlockDispositions(std::move(Arg.BlockDispositions)),
14191 SCEVUsers(std::move(Arg.SCEVUsers)),
14192 UnsignedRanges(std::move(Arg.UnsignedRanges)),
14193 SignedRanges(std::move(Arg.SignedRanges)),
14194 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
14195 UniquePreds(std::move(Arg.UniquePreds)),
14196 SCEVAllocator(std::move(Arg.SCEVAllocator)),
14197 ConstantSCEVs(std::move(Arg.ConstantSCEVs)),
14198 LoopUsers(std::move(Arg.LoopUsers)),
14199 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
14200 FirstUnknown(Arg.FirstUnknown) {
14201 Arg.FirstUnknown = nullptr;
14202}
14203
14205 // Iterate through all the SCEVUnknown instances and call their
14206 // destructors, so that they release their references to their values.
14207 for (SCEVUnknown *U = FirstUnknown; U;) {
14208 SCEVUnknown *Tmp = U;
14209 U = U->Next;
14210 Tmp->~SCEVUnknown();
14211 }
14212 FirstUnknown = nullptr;
14213
14214 ExprValueMap.clear();
14215 ValueExprMap.clear();
14216 HasRecMap.clear();
14217 BackedgeTakenCounts.clear();
14218 PredicatedBackedgeTakenCounts.clear();
14219
14220 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
14221 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
14222 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
14223 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
14224}
14225
14229
14230/// When printing a top-level SCEV for trip counts, it's helpful to include
14231/// a type for constants which are otherwise hard to disambiguate.
14232static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV* S) {
14233 if (isa<SCEVConstant>(S))
14234 OS << *S->getType() << " ";
14235 OS << *S;
14236}
14237
14239 const Loop *L) {
14240 // Print all inner loops first
14241 for (Loop *I : *L)
14242 PrintLoopInfo(OS, SE, I);
14243
14244 OS << "Loop ";
14245 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14246 OS << ": ";
14247
14248 SmallVector<BasicBlock *, 8> ExitingBlocks;
14249 L->getExitingBlocks(ExitingBlocks);
14250 if (ExitingBlocks.size() != 1)
14251 OS << "<multiple exits> ";
14252
14253 auto *BTC = SE->getBackedgeTakenCount(L);
14254 if (!isa<SCEVCouldNotCompute>(BTC)) {
14255 OS << "backedge-taken count is ";
14256 PrintSCEVWithTypeHint(OS, BTC);
14257 } else
14258 OS << "Unpredictable backedge-taken count.";
14259 OS << "\n";
14260
14261 if (ExitingBlocks.size() > 1)
14262 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14263 OS << " exit count for " << ExitingBlock->getName() << ": ";
14264 const SCEV *EC = SE->getExitCount(L, ExitingBlock);
14265 PrintSCEVWithTypeHint(OS, EC);
14266 if (isa<SCEVCouldNotCompute>(EC)) {
14267 // Retry with predicates.
14269 EC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates);
14270 if (!isa<SCEVCouldNotCompute>(EC)) {
14271 OS << "\n predicated exit count for " << ExitingBlock->getName()
14272 << ": ";
14273 PrintSCEVWithTypeHint(OS, EC);
14274 OS << "\n Predicates:\n";
14275 for (const auto *P : Predicates)
14276 P->print(OS, 4);
14277 }
14278 }
14279 OS << "\n";
14280 }
14281
14282 OS << "Loop ";
14283 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14284 OS << ": ";
14285
14286 auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
14287 if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
14288 OS << "constant max backedge-taken count is ";
14289 PrintSCEVWithTypeHint(OS, ConstantBTC);
14291 OS << ", actual taken count either this or zero.";
14292 } else {
14293 OS << "Unpredictable constant max backedge-taken count. ";
14294 }
14295
14296 OS << "\n"
14297 "Loop ";
14298 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14299 OS << ": ";
14300
14301 auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
14302 if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
14303 OS << "symbolic max backedge-taken count is ";
14304 PrintSCEVWithTypeHint(OS, SymbolicBTC);
14306 OS << ", actual taken count either this or zero.";
14307 } else {
14308 OS << "Unpredictable symbolic max backedge-taken count. ";
14309 }
14310 OS << "\n";
14311
14312 if (ExitingBlocks.size() > 1)
14313 for (BasicBlock *ExitingBlock : ExitingBlocks) {
14314 OS << " symbolic max exit count for " << ExitingBlock->getName() << ": ";
14315 auto *ExitBTC = SE->getExitCount(L, ExitingBlock,
14317 PrintSCEVWithTypeHint(OS, ExitBTC);
14318 if (isa<SCEVCouldNotCompute>(ExitBTC)) {
14319 // Retry with predicates.
14321 ExitBTC = SE->getPredicatedExitCount(L, ExitingBlock, &Predicates,
14323 if (!isa<SCEVCouldNotCompute>(ExitBTC)) {
14324 OS << "\n predicated symbolic max exit count for "
14325 << ExitingBlock->getName() << ": ";
14326 PrintSCEVWithTypeHint(OS, ExitBTC);
14327 OS << "\n Predicates:\n";
14328 for (const auto *P : Predicates)
14329 P->print(OS, 4);
14330 }
14331 }
14332 OS << "\n";
14333 }
14334
14336 auto *PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
14337 if (PBT != BTC) {
14338 OS << "Loop ";
14339 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14340 OS << ": ";
14341 if (!isa<SCEVCouldNotCompute>(PBT)) {
14342 OS << "Predicated backedge-taken count is ";
14343 PrintSCEVWithTypeHint(OS, PBT);
14344 } else
14345 OS << "Unpredictable predicated backedge-taken count.";
14346 OS << "\n";
14347 OS << " Predicates:\n";
14348 for (const auto *P : Preds)
14349 P->print(OS, 4);
14350 }
14351 Preds.clear();
14352
14353 auto *PredConstantMax =
14355 if (PredConstantMax != ConstantBTC) {
14356 OS << "Loop ";
14357 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14358 OS << ": ";
14359 if (!isa<SCEVCouldNotCompute>(PredConstantMax)) {
14360 OS << "Predicated constant max backedge-taken count is ";
14361 PrintSCEVWithTypeHint(OS, PredConstantMax);
14362 } else
14363 OS << "Unpredictable predicated constant max backedge-taken count.";
14364 OS << "\n";
14365 OS << " Predicates:\n";
14366 for (const auto *P : Preds)
14367 P->print(OS, 4);
14368 }
14369 Preds.clear();
14370
14371 auto *PredSymbolicMax =
14373 if (SymbolicBTC != PredSymbolicMax) {
14374 OS << "Loop ";
14375 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14376 OS << ": ";
14377 if (!isa<SCEVCouldNotCompute>(PredSymbolicMax)) {
14378 OS << "Predicated symbolic max backedge-taken count is ";
14379 PrintSCEVWithTypeHint(OS, PredSymbolicMax);
14380 } else
14381 OS << "Unpredictable predicated symbolic max backedge-taken count.";
14382 OS << "\n";
14383 OS << " Predicates:\n";
14384 for (const auto *P : Preds)
14385 P->print(OS, 4);
14386 }
14387
14389 OS << "Loop ";
14390 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14391 OS << ": ";
14392 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
14393 }
14394}
14395
14396namespace llvm {
14397// Note: these overloaded operators need to be in the llvm namespace for them
14398// to be resolved correctly. If we put them outside the llvm namespace, the
14399//
14400// OS << ": " << SE.getLoopDisposition(SV, InnerL);
14401//
14402// code below "breaks" and start printing raw enum values as opposed to the
14403// string values.
14406 switch (LD) {
14408 OS << "Variant";
14409 break;
14411 OS << "Invariant";
14412 break;
14414 OS << "Uniform";
14415 break;
14417 OS << "Computable";
14418 break;
14419 }
14420 return OS;
14421}
14422
14425 switch (BD) {
14427 OS << "DoesNotDominate";
14428 break;
14430 OS << "Dominates";
14431 break;
14433 OS << "ProperlyDominates";
14434 break;
14435 }
14436 return OS;
14437}
14438} // namespace llvm
14439
14441 // ScalarEvolution's implementation of the print method is to print
14442 // out SCEV values of all instructions that are interesting. Doing
14443 // this potentially causes it to create new SCEV objects though,
14444 // which technically conflicts with the const qualifier. This isn't
14445 // observable from outside the class though, so casting away the
14446 // const isn't dangerous.
14447 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14448
14449 if (ClassifyExpressions) {
14450 OS << "Classifying expressions for: ";
14451 F.printAsOperand(OS, /*PrintType=*/false);
14452 OS << "\n";
14453 for (Instruction &I : instructions(F))
14454 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
14455 OS << I << '\n';
14456 OS << " --> ";
14457 const SCEV *SV = SE.getSCEV(&I);
14458 SV->print(OS);
14459 if (!isa<SCEVCouldNotCompute>(SV)) {
14460 OS << " U: ";
14461 SE.getUnsignedRange(SV).print(OS);
14462 OS << " S: ";
14463 SE.getSignedRange(SV).print(OS);
14464 }
14465
14466 const Loop *L = LI.getLoopFor(I.getParent());
14467
14468 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
14469 if (AtUse != SV) {
14470 OS << " --> ";
14471 AtUse->print(OS);
14472 if (!isa<SCEVCouldNotCompute>(AtUse)) {
14473 OS << " U: ";
14474 SE.getUnsignedRange(AtUse).print(OS);
14475 OS << " S: ";
14476 SE.getSignedRange(AtUse).print(OS);
14477 }
14478 }
14479
14480 if (L) {
14481 OS << "\t\t" "Exits: ";
14482 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
14483 if (!SE.isLoopInvariant(ExitValue, L)) {
14484 OS << "<<Unknown>>";
14485 } else {
14486 OS << *ExitValue;
14487 }
14488
14489 ListSeparator LS(", ", "\t\tLoopDispositions: { ");
14490 for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
14491 OS << LS;
14492 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14493 OS << ": " << SE.getLoopDisposition(SV, Iter);
14494 }
14495
14496 for (const auto *InnerL : depth_first(L)) {
14497 if (InnerL == L)
14498 continue;
14499 OS << LS;
14500 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
14501 OS << ": " << SE.getLoopDisposition(SV, InnerL);
14502 }
14503
14504 OS << " }";
14505 }
14506
14507 OS << "\n";
14508 }
14509 }
14510
14511 OS << "Determining loop execution counts for: ";
14512 F.printAsOperand(OS, /*PrintType=*/false);
14513 OS << "\n";
14514 for (Loop *I : LI)
14515 PrintLoopInfo(OS, &SE, I);
14516}
14517
14520 auto &Values = LoopDispositions[S];
14521 for (auto &V : Values) {
14522 if (V.getPointer() == L)
14523 return V.getInt();
14524 }
14525 Values.emplace_back(L, LoopVariant);
14526 LoopDisposition D = computeLoopDisposition(S, L);
14527 auto &Values2 = LoopDispositions[S];
14528 for (auto &V : llvm::reverse(Values2)) {
14529 if (V.getPointer() == L) {
14530 V.setInt(D);
14531 break;
14532 }
14533 }
14534 return D;
14535}
14536
14538ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
14539 switch (S->getSCEVType()) {
14540 case scConstant:
14541 case scVScale:
14542 return LoopInvariant;
14543 case scAddRecExpr: {
14544 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14545
14546 // If L is the addrec's loop, it's computable.
14547 if (AR->getLoop() == L)
14548 return LoopComputable;
14549
14550 // Add recurrences are never invariant in the function-body (null loop).
14551 if (!L)
14552 return LoopVariant;
14553
14554 // Everything that is not defined at loop entry is variant.
14555 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) {
14556 if (L->contains(AR->getLoop()) &&
14557 llvm::all_of(AR->operands(),
14558 [&](const SCEV *Op) { return isLoopUniform(Op, L); }))
14559 return LoopUniform;
14560
14561 return LoopVariant;
14562 }
14563 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
14564 " dominate the contained loop's header?");
14565
14566 // This recurrence is invariant w.r.t. L if AR's loop contains L.
14567 if (AR->getLoop()->contains(L))
14568 return LoopInvariant;
14569
14570 // This recurrence is variant w.r.t. L if any of its operands
14571 // are variant.
14572 for (SCEVUse Op : AR->operands())
14573 if (!isLoopInvariant(Op, L))
14574 return LoopVariant;
14575
14576 // Otherwise it's loop-invariant.
14577 return LoopInvariant;
14578 }
14579 case scTruncate:
14580 case scZeroExtend:
14581 case scSignExtend:
14582 case scPtrToAddr:
14583 case scPtrToInt:
14584 case scAddExpr:
14585 case scMulExpr:
14586 case scUDivExpr:
14587 case scUMaxExpr:
14588 case scSMaxExpr:
14589 case scUMinExpr:
14590 case scSMinExpr:
14591 case scSequentialUMinExpr: {
14592 bool HasVarying = false;
14593 bool HasUniform = false;
14594 for (SCEVUse Op : S->operands()) {
14596 if (D == LoopVariant)
14597 return LoopVariant;
14598 if (D == LoopComputable)
14599 HasVarying = true;
14600 if (D == LoopUniform)
14601 HasUniform = true;
14602 }
14603 return HasVarying ? (HasUniform ? LoopVariant : LoopComputable)
14604 : (HasUniform ? LoopUniform : LoopInvariant);
14605 }
14606 case scUnknown:
14607 // All non-instruction values are loop invariant. All instructions are loop
14608 // invariant if they are not contained in the specified loop.
14609 // Instructions are never considered invariant in the function body
14610 // (null loop) because they are defined within the "loop".
14612 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
14613 return LoopInvariant;
14614 case scCouldNotCompute:
14615 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14616 }
14617 llvm_unreachable("Unknown SCEV kind!");
14618}
14619
14620bool ScalarEvolution::isLoopUniform(const SCEV *S, const Loop *L) {
14622 return D == LoopUniform || D == LoopInvariant;
14623}
14624
14626 return getLoopDisposition(S, L) == LoopInvariant;
14627}
14628
14630 return getLoopDisposition(S, L) == LoopComputable;
14631}
14632
14635 auto &Values = BlockDispositions[S];
14636 for (auto &V : Values) {
14637 if (V.getPointer() == BB)
14638 return V.getInt();
14639 }
14640 Values.emplace_back(BB, DoesNotDominateBlock);
14641 BlockDisposition D = computeBlockDisposition(S, BB);
14642 auto &Values2 = BlockDispositions[S];
14643 for (auto &V : llvm::reverse(Values2)) {
14644 if (V.getPointer() == BB) {
14645 V.setInt(D);
14646 break;
14647 }
14648 }
14649 return D;
14650}
14651
14653ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
14654 switch (S->getSCEVType()) {
14655 case scConstant:
14656 case scVScale:
14658 case scAddRecExpr: {
14659 // This uses a "dominates" query instead of "properly dominates" query
14660 // to test for proper dominance too, because the instruction which
14661 // produces the addrec's value is a PHI, and a PHI effectively properly
14662 // dominates its entire containing block.
14663 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
14664 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
14665 return DoesNotDominateBlock;
14666
14667 // Fall through into SCEVNAryExpr handling.
14668 [[fallthrough]];
14669 }
14670 case scTruncate:
14671 case scZeroExtend:
14672 case scSignExtend:
14673 case scPtrToAddr:
14674 case scPtrToInt:
14675 case scAddExpr:
14676 case scMulExpr:
14677 case scUDivExpr:
14678 case scUMaxExpr:
14679 case scSMaxExpr:
14680 case scUMinExpr:
14681 case scSMinExpr:
14682 case scSequentialUMinExpr: {
14683 bool Proper = true;
14684 for (const SCEV *NAryOp : S->operands()) {
14686 if (D == DoesNotDominateBlock)
14687 return DoesNotDominateBlock;
14688 if (D == DominatesBlock)
14689 Proper = false;
14690 }
14691 return Proper ? ProperlyDominatesBlock : DominatesBlock;
14692 }
14693 case scUnknown:
14694 if (Instruction *I =
14696 if (I->getParent() == BB)
14697 return DominatesBlock;
14698 if (DT.properlyDominates(I->getParent(), BB))
14700 return DoesNotDominateBlock;
14701 }
14703 case scCouldNotCompute:
14704 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
14705 }
14706 llvm_unreachable("Unknown SCEV kind!");
14707}
14708
14709bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
14710 return getBlockDisposition(S, BB) >= DominatesBlock;
14711}
14712
14715}
14716
14717bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
14718 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
14719}
14720
14721void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
14722 bool Predicated) {
14723 auto &BECounts =
14724 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
14725 auto It = BECounts.find(L);
14726 if (It != BECounts.end()) {
14727 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
14728 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
14729 if (!isa<SCEVConstant>(S)) {
14730 auto UserIt = BECountUsers.find(S);
14731 assert(UserIt != BECountUsers.end());
14732 UserIt->second.erase({L, Predicated});
14733 }
14734 }
14735 }
14736 BECounts.erase(It);
14737 }
14738}
14739
14740void ScalarEvolution::forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs) {
14741 SmallPtrSet<const SCEV *, 8> ToForget(llvm::from_range, SCEVs);
14742 SmallVector<SCEVUse, 8> Worklist(ToForget.begin(), ToForget.end());
14743
14744 while (!Worklist.empty()) {
14745 const SCEV *Curr = Worklist.pop_back_val();
14746 auto Users = SCEVUsers.find(Curr);
14747 if (Users != SCEVUsers.end())
14748 for (const auto *User : Users->second)
14749 if (ToForget.insert(User).second)
14750 Worklist.push_back(User);
14751 }
14752
14753 for (const auto *S : ToForget)
14754 forgetMemoizedResultsImpl(S);
14755
14756 PredicatedSCEVRewrites.remove_if(
14757 [&](const auto &Entry) { return ToForget.count(Entry.first.first); });
14758}
14759
14760void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
14761 LoopDispositions.erase(S);
14762 BlockDispositions.erase(S);
14763 UnsignedRanges.erase(S);
14764 SignedRanges.erase(S);
14765 HasRecMap.erase(S);
14766 ConstantMultipleCache.erase(S);
14767
14768 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
14769 UnsignedWrapViaInductionTried.erase(AR);
14770 SignedWrapViaInductionTried.erase(AR);
14771 }
14772
14773 auto ExprIt = ExprValueMap.find(S);
14774 if (ExprIt != ExprValueMap.end()) {
14775 for (Value *V : ExprIt->second) {
14776 auto ValueIt = ValueExprMap.find_as(V);
14777 if (ValueIt != ValueExprMap.end())
14778 ValueExprMap.erase(ValueIt);
14779 }
14780 ExprValueMap.erase(ExprIt);
14781 }
14782
14783 auto ScopeIt = ValuesAtScopes.find(S);
14784 if (ScopeIt != ValuesAtScopes.end()) {
14785 for (const auto &Pair : ScopeIt->second)
14786 if (!isa_and_nonnull<SCEVConstant>(Pair.second))
14787 llvm::erase(ValuesAtScopesUsers[Pair.second],
14788 std::make_pair(Pair.first, S));
14789 ValuesAtScopes.erase(ScopeIt);
14790 }
14791
14792 auto ScopeUserIt = ValuesAtScopesUsers.find(S);
14793 if (ScopeUserIt != ValuesAtScopesUsers.end()) {
14794 for (const auto &Pair : ScopeUserIt->second)
14795 llvm::erase(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
14796 ValuesAtScopesUsers.erase(ScopeUserIt);
14797 }
14798
14799 auto BEUsersIt = BECountUsers.find(S);
14800 if (BEUsersIt != BECountUsers.end()) {
14801 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
14802 auto Copy = BEUsersIt->second;
14803 for (const auto &Pair : Copy)
14804 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
14805 BECountUsers.erase(BEUsersIt);
14806 }
14807
14808 auto FoldUser = FoldCacheUser.find(S);
14809 if (FoldUser != FoldCacheUser.end())
14810 for (auto &KV : FoldUser->second)
14811 FoldCache.erase(KV);
14812 FoldCacheUser.erase(S);
14813}
14814
14815void
14816ScalarEvolution::getUsedLoops(const SCEV *S,
14817 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
14818 struct FindUsedLoops {
14819 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
14820 : LoopsUsed(LoopsUsed) {}
14821 SmallPtrSetImpl<const Loop *> &LoopsUsed;
14822 bool follow(const SCEV *S) {
14823 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
14824 LoopsUsed.insert(AR->getLoop());
14825 return true;
14826 }
14827
14828 bool isDone() const { return false; }
14829 };
14830
14831 FindUsedLoops F(LoopsUsed);
14832 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
14833}
14834
14835void ScalarEvolution::getReachableBlocks(
14838 Worklist.push_back(&F.getEntryBlock());
14839 while (!Worklist.empty()) {
14840 BasicBlock *BB = Worklist.pop_back_val();
14841 if (!Reachable.insert(BB).second)
14842 continue;
14843
14844 Value *Cond;
14845 BasicBlock *TrueBB, *FalseBB;
14846 if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
14847 m_BasicBlock(FalseBB)))) {
14848 if (auto *C = dyn_cast<ConstantInt>(Cond)) {
14849 Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
14850 continue;
14851 }
14852
14853 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
14854 const SCEV *L = getSCEV(Cmp->getOperand(0));
14855 const SCEV *R = getSCEV(Cmp->getOperand(1));
14856 if (isKnownPredicateViaConstantRanges(Cmp->getCmpPredicate(), L, R)) {
14857 Worklist.push_back(TrueBB);
14858 continue;
14859 }
14860 if (isKnownPredicateViaConstantRanges(Cmp->getInverseCmpPredicate(), L,
14861 R)) {
14862 Worklist.push_back(FalseBB);
14863 continue;
14864 }
14865 }
14866 }
14867
14868 append_range(Worklist, successors(BB));
14869 }
14870}
14871
14873 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
14874 ScalarEvolution SE2(F, TLI, AC, DT, LI);
14875
14876 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
14877
14878 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
14879 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
14880 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
14881
14882 const SCEV *visitConstant(const SCEVConstant *Constant) {
14883 return SE.getConstant(Constant->getAPInt());
14884 }
14885
14886 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
14887 return SE.getUnknown(Expr->getValue());
14888 }
14889
14890 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
14891 return SE.getCouldNotCompute();
14892 }
14893 };
14894
14895 SCEVMapper SCM(SE2);
14896 SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
14897 SE2.getReachableBlocks(ReachableBlocks, F);
14898
14899 auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
14900 if (containsUndefs(Old) || containsUndefs(New)) {
14901 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
14902 // not propagate undef aggressively). This means we can (and do) fail
14903 // verification in cases where a transform makes a value go from "undef"
14904 // to "undef+1" (say). The transform is fine, since in both cases the
14905 // result is "undef", but SCEV thinks the value increased by 1.
14906 return nullptr;
14907 }
14908
14909 // Unless VerifySCEVStrict is set, we only compare constant deltas.
14910 const SCEV *Delta = SE2.getMinusSCEV(Old, New);
14911 if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
14912 return nullptr;
14913
14914 return Delta;
14915 };
14916
14917 while (!LoopStack.empty()) {
14918 auto *L = LoopStack.pop_back_val();
14919 llvm::append_range(LoopStack, *L);
14920
14921 // Only verify BECounts in reachable loops. For an unreachable loop,
14922 // any BECount is legal.
14923 if (!ReachableBlocks.contains(L->getHeader()))
14924 continue;
14925
14926 // Only verify cached BECounts. Computing new BECounts may change the
14927 // results of subsequent SCEV uses.
14928 auto It = BackedgeTakenCounts.find(L);
14929 if (It == BackedgeTakenCounts.end())
14930 continue;
14931
14932 auto *CurBECount =
14933 SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
14934 auto *NewBECount = SE2.getBackedgeTakenCount(L);
14935
14936 if (CurBECount == SE2.getCouldNotCompute() ||
14937 NewBECount == SE2.getCouldNotCompute()) {
14938 // NB! This situation is legal, but is very suspicious -- whatever pass
14939 // change the loop to make a trip count go from could not compute to
14940 // computable or vice-versa *should have* invalidated SCEV. However, we
14941 // choose not to assert here (for now) since we don't want false
14942 // positives.
14943 continue;
14944 }
14945
14946 if (SE.getTypeSizeInBits(CurBECount->getType()) >
14947 SE.getTypeSizeInBits(NewBECount->getType()))
14948 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
14949 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
14950 SE.getTypeSizeInBits(NewBECount->getType()))
14951 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
14952
14953 const SCEV *Delta = GetDelta(CurBECount, NewBECount);
14954 if (Delta && !Delta->isZero()) {
14955 dbgs() << "Trip Count for " << *L << " Changed!\n";
14956 dbgs() << "Old: " << *CurBECount << "\n";
14957 dbgs() << "New: " << *NewBECount << "\n";
14958 dbgs() << "Delta: " << *Delta << "\n";
14959 std::abort();
14960 }
14961 }
14962
14963 // Collect all valid loops currently in LoopInfo.
14964 SmallPtrSet<Loop *, 32> ValidLoops;
14965 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
14966 while (!Worklist.empty()) {
14967 Loop *L = Worklist.pop_back_val();
14968 if (ValidLoops.insert(L).second)
14969 Worklist.append(L->begin(), L->end());
14970 }
14971 for (const auto &KV : ValueExprMap) {
14972#ifndef NDEBUG
14973 // Check for SCEV expressions referencing invalid/deleted loops.
14974 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
14975 assert(ValidLoops.contains(AR->getLoop()) &&
14976 "AddRec references invalid loop");
14977 }
14978#endif
14979
14980 // Check that the value is also part of the reverse map.
14981 auto It = ExprValueMap.find(KV.second);
14982 if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
14983 dbgs() << "Value " << *KV.first
14984 << " is in ValueExprMap but not in ExprValueMap\n";
14985 std::abort();
14986 }
14987
14988 if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
14989 if (!ReachableBlocks.contains(I->getParent()))
14990 continue;
14991 const SCEV *OldSCEV = SCM.visit(KV.second);
14992 const SCEV *NewSCEV = SE2.getSCEV(I);
14993 const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
14994 if (Delta && !Delta->isZero()) {
14995 dbgs() << "SCEV for value " << *I << " changed!\n"
14996 << "Old: " << *OldSCEV << "\n"
14997 << "New: " << *NewSCEV << "\n"
14998 << "Delta: " << *Delta << "\n";
14999 std::abort();
15000 }
15001 }
15002 }
15003
15004 for (const auto &KV : ExprValueMap) {
15005 for (Value *V : KV.second) {
15006 const SCEV *S = ValueExprMap.lookup(V);
15007 if (!S) {
15008 dbgs() << "Value " << *V
15009 << " is in ExprValueMap but not in ValueExprMap\n";
15010 std::abort();
15011 }
15012 if (S != KV.first) {
15013 dbgs() << "Value " << *V << " mapped to " << *S << " rather than "
15014 << *KV.first << "\n";
15015 std::abort();
15016 }
15017 }
15018 }
15019
15020 // Verify integrity of SCEV users.
15021 for (const auto &S : UniqueSCEVs) {
15022 for (SCEVUse Op : S.operands()) {
15023 // We do not store dependencies of constants.
15024 if (isa<SCEVConstant>(Op))
15025 continue;
15026 auto It = SCEVUsers.find(Op);
15027 if (It != SCEVUsers.end() && It->second.count(&S))
15028 continue;
15029 dbgs() << "Use of operand " << *Op << " by user " << S
15030 << " is not being tracked!\n";
15031 std::abort();
15032 }
15033 }
15034
15035 // Verify integrity of ValuesAtScopes users.
15036 for (const auto &ValueAndVec : ValuesAtScopes) {
15037 const SCEV *Value = ValueAndVec.first;
15038 for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
15039 const Loop *L = LoopAndValueAtScope.first;
15040 const SCEV *ValueAtScope = LoopAndValueAtScope.second;
15041 if (!isa<SCEVConstant>(ValueAtScope)) {
15042 auto It = ValuesAtScopesUsers.find(ValueAtScope);
15043 if (It != ValuesAtScopesUsers.end() &&
15044 is_contained(It->second, std::make_pair(L, Value)))
15045 continue;
15046 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15047 << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
15048 std::abort();
15049 }
15050 }
15051 }
15052
15053 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
15054 const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
15055 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
15056 const Loop *L = LoopAndValue.first;
15057 const SCEV *Value = LoopAndValue.second;
15059 auto It = ValuesAtScopes.find(Value);
15060 if (It != ValuesAtScopes.end() &&
15061 is_contained(It->second, std::make_pair(L, ValueAtScope)))
15062 continue;
15063 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
15064 << *ValueAtScope << " missing in ValuesAtScopes\n";
15065 std::abort();
15066 }
15067 }
15068
15069 // Verify integrity of BECountUsers.
15070 auto VerifyBECountUsers = [&](bool Predicated) {
15071 auto &BECounts =
15072 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
15073 for (const auto &LoopAndBEInfo : BECounts) {
15074 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
15075 for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
15076 if (!isa<SCEVConstant>(S)) {
15077 auto UserIt = BECountUsers.find(S);
15078 if (UserIt != BECountUsers.end() &&
15079 UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
15080 continue;
15081 dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
15082 << " missing from BECountUsers\n";
15083 std::abort();
15084 }
15085 }
15086 }
15087 }
15088 };
15089 VerifyBECountUsers(/* Predicated */ false);
15090 VerifyBECountUsers(/* Predicated */ true);
15091
15092 // Verify intergity of loop disposition cache.
15093 for (auto &[S, Values] : LoopDispositions) {
15094 for (auto [Loop, CachedDisposition] : Values) {
15095 const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
15096 if (CachedDisposition != RecomputedDisposition) {
15097 dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
15098 << " is incorrect: cached " << CachedDisposition << ", actual "
15099 << RecomputedDisposition << "\n";
15100 std::abort();
15101 }
15102 }
15103 }
15104
15105 // Verify integrity of the block disposition cache.
15106 for (auto &[S, Values] : BlockDispositions) {
15107 for (auto [BB, CachedDisposition] : Values) {
15108 const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
15109 if (CachedDisposition != RecomputedDisposition) {
15110 dbgs() << "Cached disposition of " << *S << " for block %"
15111 << BB->getName() << " is incorrect: cached " << CachedDisposition
15112 << ", actual " << RecomputedDisposition << "\n";
15113 std::abort();
15114 }
15115 }
15116 }
15117
15118 // Verify FoldCache/FoldCacheUser caches.
15119 for (auto [FoldID, Expr] : FoldCache) {
15120 auto I = FoldCacheUser.find(Expr);
15121 if (I == FoldCacheUser.end()) {
15122 dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
15123 << "!\n";
15124 std::abort();
15125 }
15126 if (!is_contained(I->second, FoldID)) {
15127 dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
15128 std::abort();
15129 }
15130 }
15131 for (auto [Expr, IDs] : FoldCacheUser) {
15132 for (auto &FoldID : IDs) {
15133 const SCEV *S = FoldCache.lookup(FoldID);
15134 if (!S) {
15135 dbgs() << "Missing entry in FoldCache for expression " << *Expr
15136 << "!\n";
15137 std::abort();
15138 }
15139 if (S != Expr) {
15140 dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: " << *S
15141 << " != " << *Expr << "!\n";
15142 std::abort();
15143 }
15144 }
15145 }
15146
15147 // Verify that ConstantMultipleCache computations are correct. We check that
15148 // cached multiples and recomputed multiples are multiples of each other to
15149 // verify correctness. It is possible that a recomputed multiple is different
15150 // from the cached multiple due to strengthened no wrap flags or changes in
15151 // KnownBits computations.
15152 for (auto [S, Multiple] : ConstantMultipleCache) {
15153 APInt RecomputedMultiple = SE2.getConstantMultiple(S);
15154 if ((Multiple != 0 && RecomputedMultiple != 0 &&
15155 Multiple.urem(RecomputedMultiple) != 0 &&
15156 RecomputedMultiple.urem(Multiple) != 0)) {
15157 dbgs() << "Incorrect cached computation in ConstantMultipleCache for "
15158 << *S << " : Computed " << RecomputedMultiple
15159 << " but cache contains " << Multiple << "!\n";
15160 std::abort();
15161 }
15162 }
15163}
15164
15166 Function &F, const PreservedAnalyses &PA,
15167 FunctionAnalysisManager::Invalidator &Inv) {
15168 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
15169 // of its dependencies is invalidated.
15170 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
15171 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
15172 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
15173 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
15174 Inv.invalidate<LoopAnalysis>(F, PA);
15175}
15176
15177AnalysisKey ScalarEvolutionAnalysis::Key;
15178
15181 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
15182 auto &AC = AM.getResult<AssumptionAnalysis>(F);
15183 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
15184 auto &LI = AM.getResult<LoopAnalysis>(F);
15185 return ScalarEvolution(F, TLI, AC, DT, LI);
15186}
15187
15193
15196 // For compatibility with opt's -analyze feature under legacy pass manager
15197 // which was not ported to NPM. This keeps tests using
15198 // update_analyze_test_checks.py working.
15199 OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
15200 << F.getName() << "':\n";
15202 return PreservedAnalyses::all();
15203}
15204
15206 "Scalar Evolution Analysis", false, true)
15212 "Scalar Evolution Analysis", false, true)
15213
15215
15217
15219 SE.reset(new ScalarEvolution(
15221 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
15223 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
15224 return false;
15225}
15226
15228
15230 SE->print(OS);
15231}
15232
15234 if (!VerifySCEV)
15235 return;
15236
15237 SE->verify();
15238}
15239
15247
15249 const SCEV *RHS) {
15250 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
15251}
15252
15253const SCEVPredicate *
15255 const SCEV *LHS, const SCEV *RHS) {
15257 assert(LHS->getType() == RHS->getType() &&
15258 "Type mismatch between LHS and RHS");
15259 // Unique this node based on the arguments
15260 ID.AddInteger(SCEVPredicate::P_Compare);
15261 ID.AddInteger(Pred);
15262 ID.AddPointer(LHS);
15263 ID.AddPointer(RHS);
15264 void *IP = nullptr;
15265 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15266 return S;
15267 SCEVComparePredicate *Eq = new (SCEVAllocator)
15268 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
15269 UniquePreds.InsertNode(Eq, IP);
15270 return Eq;
15271}
15272
15274 const SCEVAddRecExpr *AR,
15277 // Unique this node based on the arguments
15278 ID.AddInteger(SCEVPredicate::P_Wrap);
15279 ID.AddPointer(AR);
15280 ID.AddInteger(AddedFlags);
15281 void *IP = nullptr;
15282 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
15283 return S;
15284 auto *OF = new (SCEVAllocator)
15285 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
15286 UniquePreds.InsertNode(OF, IP);
15287 return OF;
15288}
15289
15290namespace {
15291
15292class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
15293public:
15294
15295 /// Rewrites \p S in the context of a loop L and the SCEV predication
15296 /// infrastructure.
15297 ///
15298 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
15299 /// equivalences present in \p Pred.
15300 ///
15301 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
15302 /// \p NewPreds such that the result will be an AddRecExpr.
15303 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
15305 const SCEVPredicate *Pred) {
15306 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
15307 return Rewriter.visit(S);
15308 }
15309
15310 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
15311 if (Pred) {
15312 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
15313 for (const auto *Pred : U->getPredicates())
15314 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
15315 if (IPred->getLHS() == Expr &&
15316 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15317 return IPred->getRHS();
15318 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
15319 if (IPred->getLHS() == Expr &&
15320 IPred->getPredicate() == ICmpInst::ICMP_EQ)
15321 return IPred->getRHS();
15322 }
15323 }
15324 return convertToAddRecWithPreds(Expr);
15325 }
15326
15327 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
15328 const SCEV *Operand = visit(Expr->getOperand());
15329 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15330 if (AR && AR->getLoop() == L && AR->isAffine()) {
15331 // This couldn't be folded because the operand didn't have the nuw
15332 // flag. Add the nusw flag as an assumption that we could make.
15333 const SCEV *Step = AR->getStepRecurrence(SE);
15334 Type *Ty = Expr->getType();
15335 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
15336 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
15337 SE.getSignExtendExpr(Step, Ty), L,
15338 AR->getNoWrapFlags());
15339 }
15340 return SE.getZeroExtendExpr(Operand, Expr->getType());
15341 }
15342
15343 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
15344 const SCEV *Operand = visit(Expr->getOperand());
15345 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
15346 if (AR && AR->getLoop() == L && AR->isAffine()) {
15347 // This couldn't be folded because the operand didn't have the nsw
15348 // flag. Add the nssw flag as an assumption that we could make.
15349 const SCEV *Step = AR->getStepRecurrence(SE);
15350 Type *Ty = Expr->getType();
15351 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
15352 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
15353 SE.getSignExtendExpr(Step, Ty), L,
15354 AR->getNoWrapFlags());
15355 }
15356 return SE.getSignExtendExpr(Operand, Expr->getType());
15357 }
15358
15359private:
15360 explicit SCEVPredicateRewriter(
15361 const Loop *L, ScalarEvolution &SE,
15362 SmallVectorImpl<const SCEVPredicate *> *NewPreds,
15363 const SCEVPredicate *Pred)
15364 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
15365
15366 bool addOverflowAssumption(const SCEVPredicate *P) {
15367 if (!NewPreds) {
15368 // Check if we've already made this assumption.
15369 return Pred && Pred->implies(P, SE);
15370 }
15371 NewPreds->push_back(P);
15372 return true;
15373 }
15374
15375 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
15377 auto *A = SE.getWrapPredicate(AR, AddedFlags);
15378 return addOverflowAssumption(A);
15379 }
15380
15381 // If \p Expr represents a PHINode, we try to see if it can be represented
15382 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
15383 // to add this predicate as a runtime overflow check, we return the AddRec.
15384 // If \p Expr does not meet these conditions (is not a PHI node, or we
15385 // couldn't create an AddRec for it, or couldn't add the predicate), we just
15386 // return \p Expr.
15387 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
15388 if (!isa<PHINode>(Expr->getValue()))
15389 return Expr;
15390 std::optional<
15391 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
15392 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
15393 if (!PredicatedRewrite)
15394 return Expr;
15395 for (const auto *P : PredicatedRewrite->second){
15396 // Wrap predicates from outer loops are not supported.
15397 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
15398 if (L != WP->getExpr()->getLoop())
15399 return Expr;
15400 }
15401 if (!addOverflowAssumption(P))
15402 return Expr;
15403 }
15404 return PredicatedRewrite->first;
15405 }
15406
15407 SmallVectorImpl<const SCEVPredicate *> *NewPreds;
15408 const SCEVPredicate *Pred;
15409 const Loop *L;
15410};
15411
15412} // end anonymous namespace
15413
15414const SCEV *
15416 const SCEVPredicate &Preds) {
15417 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
15418}
15419
15421 const SCEV *S, const Loop *L,
15424 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
15425 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
15426
15427 if (!AddRec)
15428 return nullptr;
15429
15430 // Check if any of the transformed predicates is known to be false. In that
15431 // case, it doesn't make sense to convert to a predicated AddRec, as the
15432 // versioned loop will never execute.
15433 for (const SCEVPredicate *Pred : TransformPreds) {
15434 auto *WrapPred = dyn_cast<SCEVWrapPredicate>(Pred);
15435 if (!WrapPred || WrapPred->getFlags() != SCEVWrapPredicate::IncrementNSSW)
15436 continue;
15437
15438 const SCEVAddRecExpr *AddRecToCheck = WrapPred->getExpr();
15439 const SCEV *ExitCount = getBackedgeTakenCount(AddRecToCheck->getLoop());
15440 if (isa<SCEVCouldNotCompute>(ExitCount))
15441 continue;
15442
15443 const SCEV *Step = AddRecToCheck->getStepRecurrence(*this);
15444 if (!Step->isOne())
15445 continue;
15446
15447 ExitCount = getTruncateOrSignExtend(ExitCount, Step->getType());
15448 const SCEV *Add = getAddExpr(AddRecToCheck->getStart(), ExitCount);
15449 if (isKnownPredicate(CmpInst::ICMP_SLT, Add, AddRecToCheck->getStart()))
15450 return nullptr;
15451 }
15452
15453 // Since the transformation was successful, we can now transfer the SCEV
15454 // predicates.
15455 Preds.append(TransformPreds.begin(), TransformPreds.end());
15456
15457 return AddRec;
15458}
15459
15460/// SCEV predicates
15464
15466 const ICmpInst::Predicate Pred,
15467 const SCEV *LHS, const SCEV *RHS)
15468 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
15469 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
15470 assert(LHS != RHS && "LHS and RHS are the same SCEV");
15471}
15472
15474 ScalarEvolution &SE) const {
15475 const auto *Op = dyn_cast<SCEVComparePredicate>(N);
15476
15477 if (!Op)
15478 return false;
15479
15480 if (Pred != ICmpInst::ICMP_EQ)
15481 return false;
15482
15483 return Op->LHS == LHS && Op->RHS == RHS;
15484}
15485
15486bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
15487
15489 if (Pred == ICmpInst::ICMP_EQ)
15490 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
15491 else
15492 OS.indent(Depth) << "Compare predicate: " << *LHS << " " << Pred << ") "
15493 << *RHS << "\n";
15494
15495}
15496
15498 const SCEVAddRecExpr *AR,
15499 IncrementWrapFlags Flags)
15500 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
15501
15502const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
15503
15505 ScalarEvolution &SE) const {
15506 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
15507 if (!Op || setFlags(Flags, Op->Flags) != Flags)
15508 return false;
15509
15510 if (Op->AR == AR)
15511 return true;
15512
15513 if (Flags != SCEVWrapPredicate::IncrementNSSW &&
15515 return false;
15516
15517 const SCEV *Start = AR->getStart();
15518 const SCEV *OpStart = Op->AR->getStart();
15519 if (Start->getType()->isPointerTy() != OpStart->getType()->isPointerTy())
15520 return false;
15521
15522 // Reject pointers to different address spaces.
15523 if (Start->getType()->isPointerTy() && Start->getType() != OpStart->getType())
15524 return false;
15525
15526 // NUSW/NSSW on a wider-type AddRec does not imply the same on a
15527 // narrower-type AddRec.
15528 if (SE.getTypeSizeInBits(AR->getType()) >
15529 SE.getTypeSizeInBits(Op->AR->getType()))
15530 return false;
15531
15532 const SCEV *Step = AR->getStepRecurrence(SE);
15533 const SCEV *OpStep = Op->AR->getStepRecurrence(SE);
15534 if (!SE.isKnownPositive(Step) || !SE.isKnownPositive(OpStep))
15535 return false;
15536
15537 // If both steps are positive, this implies N, if N's start and step are
15538 // ULE/SLE (for NSUW/NSSW) than this'.
15539 Type *WiderTy = SE.getWiderType(Step->getType(), OpStep->getType());
15540 Step = SE.getNoopOrZeroExtend(Step, WiderTy);
15541 OpStep = SE.getNoopOrZeroExtend(OpStep, WiderTy);
15542
15543 bool IsNUW = Flags == SCEVWrapPredicate::IncrementNUSW;
15544 OpStart = IsNUW ? SE.getNoopOrZeroExtend(OpStart, WiderTy)
15545 : SE.getNoopOrSignExtend(OpStart, WiderTy);
15546 Start = IsNUW ? SE.getNoopOrZeroExtend(Start, WiderTy)
15547 : SE.getNoopOrSignExtend(Start, WiderTy);
15549 return SE.isKnownPredicate(Pred, OpStep, Step) &&
15550 SE.isKnownPredicate(Pred, OpStart, Start);
15551}
15552
15554 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
15555 IncrementWrapFlags IFlags = Flags;
15556
15557 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
15558 IFlags = clearFlags(IFlags, IncrementNSSW);
15559
15560 return IFlags == IncrementAnyWrap;
15561}
15562
15563void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
15564 OS.indent(Depth) << *getExpr() << " Added Flags: ";
15566 OS << "<nusw>";
15568 OS << "<nssw>";
15569 OS << "\n";
15570}
15571
15574 ScalarEvolution &SE) {
15575 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
15576 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
15577
15578 // We can safely transfer the NSW flag as NSSW.
15579 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
15580 ImpliedFlags = IncrementNSSW;
15581
15582 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
15583 // If the increment is positive, the SCEV NUW flag will also imply the
15584 // WrapPredicate NUSW flag.
15585 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
15586 if (Step->getValue()->getValue().isNonNegative())
15587 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
15588 }
15589
15590 return ImpliedFlags;
15591}
15592
15593/// Union predicates don't get cached so create a dummy set ID for it.
15595 ScalarEvolution &SE)
15596 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
15597 for (const auto *P : Preds)
15598 add(P, SE);
15599}
15600
15602 return all_of(Preds,
15603 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
15604}
15605
15607 ScalarEvolution &SE) const {
15608 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
15609 return all_of(Set->Preds, [this, &SE](const SCEVPredicate *I) {
15610 return this->implies(I, SE);
15611 });
15612
15613 if (any_of(Preds,
15614 [N, &SE](const SCEVPredicate *I) { return I->implies(N, SE); }))
15615 return true;
15616
15617 // A wrap predicate may be implied by a wrap predicate in Preds after applying
15618 // equal predicates.
15619 const auto *NWrap = dyn_cast<SCEVWrapPredicate>(N);
15620 if (!NWrap)
15621 return false;
15622 const Loop *L = NWrap->getExpr()->getLoop();
15623 return any_of(Preds, [&](const SCEVPredicate *I) {
15624 const auto *IWrap = dyn_cast<SCEVWrapPredicate>(I);
15625 if (!IWrap)
15626 return false;
15627 const auto *RewrittenAR = dyn_cast<SCEVAddRecExpr>(
15628 SE.rewriteUsingPredicate(IWrap->getExpr(), L, *this));
15629 return RewrittenAR &&
15630 SE.getWrapPredicate(RewrittenAR, IWrap->getFlags())->implies(N, SE);
15631 });
15632}
15633
15635 for (const auto *Pred : Preds)
15636 Pred->print(OS, Depth);
15637}
15638
15639void SCEVUnionPredicate::add(const SCEVPredicate *N, ScalarEvolution &SE) {
15640 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
15641 for (const auto *Pred : Set->Preds)
15642 add(Pred, SE);
15643 return;
15644 }
15645
15646 // Implication checks are quadratic in the number of predicates. Stop doing
15647 // them if there are many predicates, as they should be too expensive to use
15648 // anyway at that point.
15649 bool CheckImplies = Preds.size() < 16;
15650
15651 // Only add predicate if it is not already implied by this union predicate.
15652 if (CheckImplies && implies(N, SE))
15653 return;
15654
15655 // Build a new vector containing the current predicates, except the ones that
15656 // are implied by the new predicate N.
15658 for (auto *P : Preds) {
15659 if (CheckImplies && N->implies(P, SE))
15660 continue;
15661 PrunedPreds.push_back(P);
15662 }
15663 Preds = std::move(PrunedPreds);
15664 Preds.push_back(N);
15665}
15666
15668 Loop &L)
15669 : SE(SE), L(L) {
15671 Preds = std::make_unique<SCEVUnionPredicate>(Empty, SE);
15672}
15673
15676 for (const auto *Op : Ops)
15677 // We do not expect that forgetting cached data for SCEVConstants will ever
15678 // open any prospects for sharpening or introduce any correctness issues,
15679 // so we don't bother storing their dependencies.
15680 if (!isa<SCEVConstant>(Op))
15681 SCEVUsers[Op].insert(User);
15682}
15683
15685 for (const SCEV *Op : Ops)
15686 // We do not expect that forgetting cached data for SCEVConstants will ever
15687 // open any prospects for sharpening or introduce any correctness issues,
15688 // so we don't bother storing their dependencies.
15689 if (!isa<SCEVConstant>(Op))
15690 SCEVUsers[Op].insert(User);
15691}
15692
15694 const SCEV *Expr = SE.getSCEV(V);
15695 return getPredicatedSCEV(Expr);
15696}
15697
15699 RewriteEntry &Entry = RewriteMap[Expr];
15700
15701 // If we already have an entry and the version matches, return it.
15702 if (Entry.second && Generation == Entry.first)
15703 return Entry.second;
15704
15705 // We found an entry but it's stale. Rewrite the stale entry
15706 // according to the current predicate.
15707 if (Entry.second)
15708 Expr = Entry.second;
15709
15710 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
15711 Entry = {Generation, NewSCEV};
15712
15713 return NewSCEV;
15714}
15715
15717 if (!BackedgeCount) {
15719 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
15720 for (const auto *P : Preds)
15721 addPredicate(*P);
15722 }
15723 return BackedgeCount;
15724}
15725
15727 if (!SymbolicMaxBackedgeCount) {
15729 SymbolicMaxBackedgeCount =
15730 SE.getPredicatedSymbolicMaxBackedgeTakenCount(&L, Preds);
15731 for (const auto *P : Preds)
15732 addPredicate(*P);
15733 }
15734 return SymbolicMaxBackedgeCount;
15735}
15736
15738 if (!SmallConstantMaxTripCount) {
15740 SmallConstantMaxTripCount = SE.getSmallConstantMaxTripCount(&L, &Preds);
15741 for (const auto *P : Preds)
15742 addPredicate(*P);
15743 }
15744 return *SmallConstantMaxTripCount;
15745}
15746
15748 if (Preds->implies(&Pred, SE))
15749 return;
15750
15751 SmallVector<const SCEVPredicate *, 4> NewPreds(Preds->getPredicates());
15752 NewPreds.push_back(&Pred);
15753 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds, SE);
15754 updateGeneration();
15755}
15756
15759 for (const SCEVPredicate *P : Preds)
15760 addPredicate(*P);
15761}
15762
15764 return *Preds;
15765}
15766
15767void PredicatedScalarEvolution::updateGeneration() {
15768 // If the generation number wrapped recompute everything.
15769 if (++Generation == 0) {
15770 for (auto &II : RewriteMap) {
15771 const SCEV *Rewritten = II.second.second;
15772 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
15773 }
15774 }
15775}
15776
15779 const auto *AR = dyn_cast<SCEVAddRecExpr>(getSCEV(V));
15780 if (!AR)
15781 return false;
15782
15784 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
15785
15787}
15788
15791 const SCEV *Expr = this->getSCEV(V);
15793 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
15794
15795 if (!New)
15796 return nullptr;
15797
15798 if (ExtraPreds) {
15799 ExtraPreds->append(NewPreds);
15800 return New;
15801 }
15802
15803 addPredicates(NewPreds);
15804
15805 RewriteMap[SE.getSCEV(V)] = {Generation, New};
15806 return New;
15807}
15808
15811 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
15812 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates(),
15813 SE)),
15814 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {}
15815
15817 // For each block.
15818 for (auto *BB : L.getBlocks())
15819 for (auto &I : *BB) {
15820 if (!SE.isSCEVable(I.getType()))
15821 continue;
15822
15823 auto *Expr = SE.getSCEV(&I);
15824 auto II = RewriteMap.find(Expr);
15825
15826 if (II == RewriteMap.end())
15827 continue;
15828
15829 // Don't print things that are not interesting.
15830 if (II->second.second == Expr)
15831 continue;
15832
15833 OS.indent(Depth) << "[PSE]" << I << ":\n";
15834 OS.indent(Depth + 2) << *Expr << "\n";
15835 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
15836 }
15837}
15838
15841 BasicBlock *Header = L->getHeader();
15842 BasicBlock *Pred = L->getLoopPredecessor();
15843 LoopGuards Guards(SE);
15844 if (!Pred)
15845 return Guards;
15847 collectFromBlock(SE, Guards, Header, Pred, VisitedBlocks);
15848 return Guards;
15849}
15850
15851void ScalarEvolution::LoopGuards::collectFromPHI(
15855 unsigned Depth) {
15856 if (!SE.isSCEVable(Phi.getType()))
15857 return;
15858
15859 using MinMaxPattern = std::pair<const SCEVConstant *, SCEVTypes>;
15860 auto GetMinMaxConst = [&](unsigned IncomingIdx) -> MinMaxPattern {
15861 const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx);
15862 if (!VisitedBlocks.insert(InBlock).second)
15863 return {nullptr, scCouldNotCompute};
15864
15865 // Avoid analyzing unreachable blocks so that we don't get trapped
15866 // traversing cycles with ill-formed dominance or infinite cycles
15867 if (!SE.DT.isReachableFromEntry(InBlock))
15868 return {nullptr, scCouldNotCompute};
15869
15870 auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE));
15871 if (Inserted)
15872 collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks,
15873 Depth + 1);
15874 auto &RewriteMap = G->second.RewriteMap;
15875 if (RewriteMap.empty())
15876 return {nullptr, scCouldNotCompute};
15877 auto S = RewriteMap.find(SE.getSCEV(Phi.getIncomingValue(IncomingIdx)));
15878 if (S == RewriteMap.end())
15879 return {nullptr, scCouldNotCompute};
15880 auto *SM = dyn_cast_if_present<SCEVMinMaxExpr>(S->second);
15881 if (!SM)
15882 return {nullptr, scCouldNotCompute};
15883 if (const SCEVConstant *C0 = dyn_cast<SCEVConstant>(SM->getOperand(0)))
15884 return {C0, SM->getSCEVType()};
15885 return {nullptr, scCouldNotCompute};
15886 };
15887 auto MergeMinMaxConst = [](MinMaxPattern P1,
15888 MinMaxPattern P2) -> MinMaxPattern {
15889 auto [C1, T1] = P1;
15890 auto [C2, T2] = P2;
15891 if (!C1 || !C2 || T1 != T2)
15892 return {nullptr, scCouldNotCompute};
15893 switch (T1) {
15894 case scUMaxExpr:
15895 return {C1->getAPInt().ult(C2->getAPInt()) ? C1 : C2, T1};
15896 case scSMaxExpr:
15897 return {C1->getAPInt().slt(C2->getAPInt()) ? C1 : C2, T1};
15898 case scUMinExpr:
15899 return {C1->getAPInt().ugt(C2->getAPInt()) ? C1 : C2, T1};
15900 case scSMinExpr:
15901 return {C1->getAPInt().sgt(C2->getAPInt()) ? C1 : C2, T1};
15902 default:
15903 llvm_unreachable("Trying to merge non-MinMaxExpr SCEVs.");
15904 }
15905 };
15906 auto P = GetMinMaxConst(0);
15907 for (unsigned int In = 1; In < Phi.getNumIncomingValues(); In++) {
15908 if (!P.first)
15909 break;
15910 P = MergeMinMaxConst(P, GetMinMaxConst(In));
15911 }
15912 if (P.first) {
15913 const SCEV *LHS = SE.getSCEV(const_cast<PHINode *>(&Phi));
15914 SmallVector<SCEVUse, 2> Ops({P.first, LHS});
15915 const SCEV *RHS = SE.getMinMaxExpr(P.second, Ops);
15916 Guards.RewriteMap.insert({LHS, RHS});
15917 }
15918}
15919
15920// Return a new SCEV that modifies \p Expr to the closest number divides by
15921// \p Divisor and less or equal than Expr. For now, only handle constant
15922// Expr.
15924 const APInt &DivisorVal,
15925 ScalarEvolution &SE) {
15926 const APInt *ExprVal;
15927 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15928 DivisorVal.isNonPositive())
15929 return Expr;
15930 APInt Rem = ExprVal->urem(DivisorVal);
15931 // return the SCEV: Expr - Expr % Divisor
15932 return SE.getConstant(*ExprVal - Rem);
15933}
15934
15935// Return a new SCEV that modifies \p Expr to the closest number divides by
15936// \p Divisor and greater or equal than Expr. For now, only handle constant
15937// Expr.
15938static const SCEV *getNextSCEVDivisibleByDivisor(const SCEV *Expr,
15939 const APInt &DivisorVal,
15940 ScalarEvolution &SE) {
15941 const APInt *ExprVal;
15942 if (!match(Expr, m_scev_APInt(ExprVal)) || ExprVal->isNegative() ||
15943 DivisorVal.isNonPositive())
15944 return Expr;
15945 APInt Rem = ExprVal->urem(DivisorVal);
15946 if (Rem.isZero())
15947 return Expr;
15948 // return the SCEV: Expr + Divisor - Expr % Divisor
15949 return SE.getConstant(*ExprVal + DivisorVal - Rem);
15950}
15951
15953 ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS,
15956 // If we have LHS == 0, check if LHS is computing a property of some unknown
15957 // SCEV %v which we can rewrite %v to express explicitly.
15959 return false;
15960 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
15961 // explicitly express that.
15962 const SCEVUnknown *URemLHS = nullptr;
15963 const SCEV *URemRHS = nullptr;
15964 if (!match(LHS, m_scev_URem(m_SCEVUnknown(URemLHS), m_SCEV(URemRHS), SE)))
15965 return false;
15966
15967 const SCEV *Multiple =
15968 SE.getMulExpr(SE.getUDivExpr(URemLHS, URemRHS), URemRHS);
15969 DivInfo[URemLHS] = Multiple;
15970 if (auto *C = dyn_cast<SCEVConstant>(URemRHS))
15971 Multiples[URemLHS] = C->getAPInt();
15972 return true;
15973}
15974
15975// Check if the condition is a divisibility guard (A % B == 0).
15976static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS,
15977 ScalarEvolution &SE) {
15978 const SCEV *X, *Y;
15979 return match(LHS, m_scev_URem(m_SCEV(X), m_SCEV(Y), SE)) && RHS->isZero();
15980}
15981
15982// Apply divisibility by \p Divisor on MinMaxExpr with constant values,
15983// recursively. This is done by aligning up/down the constant value to the
15984// Divisor.
15985static const SCEV *applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr,
15986 APInt Divisor,
15987 ScalarEvolution &SE) {
15988 // Return true if \p Expr is a MinMax SCEV expression with a non-negative
15989 // constant operand. If so, return in \p SCTy the SCEV type and in \p RHS
15990 // the non-constant operand and in \p LHS the constant operand.
15991 auto IsMinMaxSCEVWithNonNegativeConstant =
15992 [&](const SCEV *Expr, SCEVTypes &SCTy, const SCEV *&LHS,
15993 const SCEV *&RHS) {
15994 if (auto *MinMax = dyn_cast<SCEVMinMaxExpr>(Expr)) {
15995 if (MinMax->getNumOperands() != 2)
15996 return false;
15997 if (auto *C = dyn_cast<SCEVConstant>(MinMax->getOperand(0))) {
15998 if (C->getAPInt().isNegative())
15999 return false;
16000 SCTy = MinMax->getSCEVType();
16001 LHS = MinMax->getOperand(0);
16002 RHS = MinMax->getOperand(1);
16003 return true;
16004 }
16005 }
16006 return false;
16007 };
16008
16009 const SCEV *MinMaxLHS = nullptr, *MinMaxRHS = nullptr;
16010 SCEVTypes SCTy;
16011 if (!IsMinMaxSCEVWithNonNegativeConstant(MinMaxExpr, SCTy, MinMaxLHS,
16012 MinMaxRHS))
16013 return MinMaxExpr;
16014 auto IsMin = isa<SCEVSMinExpr>(MinMaxExpr) || isa<SCEVUMinExpr>(MinMaxExpr);
16015 assert(SE.isKnownNonNegative(MinMaxLHS) && "Expected non-negative operand!");
16016 auto *DivisibleExpr =
16017 IsMin ? getPreviousSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE)
16018 : getNextSCEVDivisibleByDivisor(MinMaxLHS, Divisor, SE);
16020 applyDivisibilityOnMinMaxExpr(MinMaxRHS, Divisor, SE), DivisibleExpr};
16021 return SE.getMinMaxExpr(SCTy, Ops);
16022}
16023
16024void ScalarEvolution::LoopGuards::collectFromBlock(
16025 ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
16026 const BasicBlock *Block, const BasicBlock *Pred,
16027 SmallPtrSetImpl<const BasicBlock *> &VisitedBlocks, unsigned Depth) {
16028
16030
16031 SmallVector<SCEVUse> ExprsToRewrite;
16032 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
16033 const SCEV *RHS,
16034 DenseMap<const SCEV *, const SCEV *> &RewriteMap,
16035 const LoopGuards &DivGuards) {
16036 // WARNING: It is generally unsound to apply any wrap flags to the proposed
16037 // replacement SCEV which isn't directly implied by the structure of that
16038 // SCEV. In particular, using contextual facts to imply flags is *NOT*
16039 // legal. See the scoping rules for flags in the header to understand why.
16040
16041 // Puts rewrite rule \p From -> \p To into the rewrite map. Also if \p From
16042 // and \p FromRewritten are the same (i.e. there has been no rewrite
16043 // registered for \p From), then puts this value in the list of rewritten
16044 // expressions.
16045 auto AddRewrite = [&](const SCEV *From, const SCEV *FromRewritten,
16046 const SCEV *To) {
16047 if (From == FromRewritten)
16048 ExprsToRewrite.push_back(From);
16049 RewriteMap[From] = To;
16050 };
16051
16052 // Checks whether \p S has already been rewritten. In that case returns the
16053 // existing rewrite because we want to chain further rewrites onto the
16054 // already rewritten value. Otherwise returns \p S.
16055 auto GetMaybeRewritten = [&](const SCEV *S) {
16056 return RewriteMap.lookup_or(S, S);
16057 };
16058
16059 // Check for a condition of the form (-C1 + X < C2). InstCombine will
16060 // create this form when combining two checks of the form (X u< C2 + C1) and
16061 // (X >=u C1).
16062 auto MatchRangeCheckIdiom = [&](ICmpInst::Predicate Pred,
16063 const SCEV *MatchLHS,
16064 const SCEV *MatchRHS) {
16065 const SCEVConstant *C1;
16066 const SCEVUnknown *LHSUnknown;
16067 auto *C2 = dyn_cast<SCEVConstant>(MatchRHS);
16068 if (!match(MatchLHS,
16069 m_scev_Add(m_SCEVConstant(C1), m_SCEVUnknown(LHSUnknown))) ||
16070 !C2)
16071 return false;
16072
16073 auto ExactRegion =
16074 ConstantRange::makeExactICmpRegion(Pred, C2->getAPInt())
16075 .sub(C1->getAPInt());
16076
16077 // Tighten the raw range with what we already know about LHSUnknown
16078 // from prior guards recorded in RewriteMap, or from SCEV's own range
16079 // analysis.
16080 const SCEV *RewrittenLHS = GetMaybeRewritten(LHSUnknown);
16081 ExactRegion = ExactRegion.intersectWith(SE.getUnsignedRange(RewrittenLHS),
16083
16084 // Bail if the guard is inconsistent with prior facts, or if the range
16085 // is still not a monotonic non-wrapping interval after tightening.
16086 if (ExactRegion.isEmptySet() || ExactRegion.isWrappedSet() ||
16087 ExactRegion.isFullSet())
16088 return false;
16089
16090 const SCEV *RegionMin = SE.getConstant(ExactRegion.getUnsignedMin());
16091 const SCEV *RegionMax = SE.getConstant(ExactRegion.getUnsignedMax());
16092 const SCEV *ClampedLHS =
16093 SE.getUMaxExpr(RegionMin, SE.getUMinExpr(RewrittenLHS, RegionMax));
16094 AddRewrite(LHSUnknown, RewrittenLHS, ClampedLHS);
16095 return true;
16096 };
16097 if (MatchRangeCheckIdiom(Predicate, LHS, RHS))
16098 return;
16099
16100 // Do not apply information for constants or if RHS contains an AddRec.
16102 return;
16103
16104 // If RHS is SCEVUnknown, make sure the information is applied to it.
16106 std::swap(LHS, RHS);
16108 }
16109
16110 const SCEV *RewrittenLHS = GetMaybeRewritten(LHS);
16111 // Apply divisibility information when computing the constant multiple.
16112 const APInt &DividesBy =
16113 SE.getConstantMultiple(DivGuards.rewrite(RewrittenLHS));
16114
16115 // Collect rewrites for LHS and its transitive operands based on the
16116 // condition.
16117 // For min/max expressions, also apply the guard to its operands:
16118 // 'min(a, b) >= c' -> '(a >= c) and (b >= c)',
16119 // 'min(a, b) > c' -> '(a > c) and (b > c)',
16120 // 'max(a, b) <= c' -> '(a <= c) and (b <= c)',
16121 // 'max(a, b) < c' -> '(a < c) and (b < c)'.
16122
16123 // We cannot express strict predicates in SCEV, so instead we replace them
16124 // with non-strict ones against plus or minus one of RHS depending on the
16125 // predicate.
16126 const SCEV *One = SE.getOne(RHS->getType());
16127 switch (Predicate) {
16128 case CmpInst::ICMP_ULT:
16129 if (RHS->getType()->isPointerTy())
16130 return;
16131 RHS = SE.getUMaxExpr(RHS, One);
16132 [[fallthrough]];
16133 case CmpInst::ICMP_SLT: {
16134 RHS = SE.getMinusSCEV(RHS, One);
16135 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16136 break;
16137 }
16138 case CmpInst::ICMP_UGT:
16139 case CmpInst::ICMP_SGT:
16140 RHS = SE.getAddExpr(RHS, One);
16141 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16142 break;
16143 case CmpInst::ICMP_ULE:
16144 case CmpInst::ICMP_SLE:
16145 RHS = getPreviousSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16146 break;
16147 case CmpInst::ICMP_UGE:
16148 case CmpInst::ICMP_SGE:
16149 RHS = getNextSCEVDivisibleByDivisor(RHS, DividesBy, SE);
16150 break;
16151 default:
16152 break;
16153 }
16154
16155 SmallVector<SCEVUse, 16> Worklist(1, LHS);
16156 SmallPtrSet<const SCEV *, 16> Visited;
16157
16158 auto EnqueueOperands = [&Worklist](const SCEVNAryExpr *S) {
16159 append_range(Worklist, S->operands());
16160 };
16161
16162 while (!Worklist.empty()) {
16163 const SCEV *From = Worklist.pop_back_val();
16164 if (isa<SCEVConstant>(From))
16165 continue;
16166 if (!Visited.insert(From).second)
16167 continue;
16168 const SCEV *FromRewritten = GetMaybeRewritten(From);
16169 const SCEV *To = nullptr;
16170
16171 switch (Predicate) {
16172 case CmpInst::ICMP_ULT:
16173 case CmpInst::ICMP_ULE:
16174 To = SE.getUMinExpr(FromRewritten, RHS);
16175 if (auto *UMax = dyn_cast<SCEVUMaxExpr>(FromRewritten))
16176 EnqueueOperands(UMax);
16177 break;
16178 case CmpInst::ICMP_SLT:
16179 case CmpInst::ICMP_SLE:
16180 To = SE.getSMinExpr(FromRewritten, RHS);
16181 if (auto *SMax = dyn_cast<SCEVSMaxExpr>(FromRewritten))
16182 EnqueueOperands(SMax);
16183 break;
16184 case CmpInst::ICMP_UGT:
16185 case CmpInst::ICMP_UGE:
16186 To = SE.getUMaxExpr(FromRewritten, RHS);
16187 if (auto *UMin = dyn_cast<SCEVUMinExpr>(FromRewritten))
16188 EnqueueOperands(UMin);
16189 break;
16190 case CmpInst::ICMP_SGT:
16191 case CmpInst::ICMP_SGE:
16192 To = SE.getSMaxExpr(FromRewritten, RHS);
16193 if (auto *SMin = dyn_cast<SCEVSMinExpr>(FromRewritten))
16194 EnqueueOperands(SMin);
16195 break;
16196 case CmpInst::ICMP_EQ:
16198 To = RHS;
16199 break;
16200 case CmpInst::ICMP_NE:
16201 if (match(RHS, m_scev_Zero())) {
16202 const SCEV *OneAlignedUp =
16203 getNextSCEVDivisibleByDivisor(One, DividesBy, SE);
16204 To = SE.getUMaxExpr(FromRewritten, OneAlignedUp);
16205 } else {
16206 // LHS != RHS can be rewritten as (LHS - RHS) = UMax(1, LHS - RHS),
16207 // but creating the subtraction eagerly is expensive. Track the
16208 // inequalities in a separate map, and materialize the rewrite lazily
16209 // when encountering a suitable subtraction while re-writing.
16210 if (LHS->getType()->isPointerTy()) {
16211 LHS = SE.getPtrToAddrExpr(LHS);
16212 RHS = SE.getPtrToAddrExpr(RHS);
16214 break;
16215 }
16216 const SCEVConstant *C;
16217 const SCEV *A, *B;
16220 RHS = A;
16221 LHS = B;
16222 }
16223 if (LHS > RHS)
16224 std::swap(LHS, RHS);
16225 Guards.NotEqual.insert({LHS, RHS});
16226 continue;
16227 }
16228 break;
16229 default:
16230 break;
16231 }
16232
16233 if (To)
16234 AddRewrite(From, FromRewritten, To);
16235 }
16236 };
16237
16239 // First, collect information from assumptions dominating the loop.
16240 for (auto &AssumeVH : SE.AC.assumptions()) {
16241 if (!AssumeVH)
16242 continue;
16243 auto *AssumeI = cast<CallInst>(AssumeVH);
16244 if (!SE.DT.dominates(AssumeI, Block))
16245 continue;
16246 Terms.emplace_back(AssumeI->getOperand(0), true);
16247 }
16248
16249 // Second, collect information from llvm.experimental.guards dominating the loop.
16250 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
16251 SE.F.getParent(), Intrinsic::experimental_guard);
16252 if (GuardDecl)
16253 for (const auto *GU : GuardDecl->users())
16254 if (const auto *Guard = dyn_cast<IntrinsicInst>(GU))
16255 if (Guard->getFunction() == Block->getParent() &&
16256 SE.DT.dominates(Guard, Block))
16257 Terms.emplace_back(Guard->getArgOperand(0), true);
16258
16259 // Third, collect conditions from dominating branches. Starting at the loop
16260 // predecessor, climb up the predecessor chain, as long as there are
16261 // predecessors that can be found that have unique successors leading to the
16262 // original header.
16263 // TODO: share this logic with isLoopEntryGuardedByCond.
16264 unsigned NumCollectedConditions = 0;
16266 std::pair<const BasicBlock *, const BasicBlock *> Pair(Pred, Block);
16267 for (; Pair.first;
16268 Pair = SE.getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
16269 VisitedBlocks.insert(Pair.second);
16270 const CondBrInst *LoopEntryPredicate =
16271 dyn_cast<CondBrInst>(Pair.first->getTerminator());
16272 if (!LoopEntryPredicate)
16273 continue;
16274
16275 Terms.emplace_back(LoopEntryPredicate->getCondition(),
16276 LoopEntryPredicate->getSuccessor(0) == Pair.second);
16277 NumCollectedConditions++;
16278
16279 // If we are recursively collecting guards stop after 2
16280 // conditions to limit compile-time impact for now.
16281 if (Depth > 0 && NumCollectedConditions == 2)
16282 break;
16283 }
16284 // Finally, if we stopped climbing the predecessor chain because
16285 // there wasn't a unique one to continue, try to collect conditions
16286 // for PHINodes by recursively following all of their incoming
16287 // blocks and try to merge the found conditions to build a new one
16288 // for the Phi.
16289 if (Pair.second->hasNPredecessorsOrMore(2) &&
16291 SmallDenseMap<const BasicBlock *, LoopGuards> IncomingGuards;
16292 for (auto &Phi : Pair.second->phis())
16293 collectFromPHI(SE, Guards, Phi, VisitedBlocks, IncomingGuards, Depth);
16294 }
16295
16296 // Now apply the information from the collected conditions to
16297 // Guards.RewriteMap. Conditions are processed in reverse order, so the
16298 // earliest conditions is processed first, except guards with divisibility
16299 // information, which are moved to the back. This ensures the SCEVs with the
16300 // shortest dependency chains are constructed first.
16302 GuardsToProcess;
16303 for (auto [Term, EnterIfTrue] : reverse(Terms)) {
16304 SmallVector<Value *, 8> Worklist;
16305 SmallPtrSet<Value *, 8> Visited;
16306 Worklist.push_back(Term);
16307 while (!Worklist.empty()) {
16308 Value *Cond = Worklist.pop_back_val();
16309 if (!Visited.insert(Cond).second)
16310 continue;
16311
16312 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
16313 auto Predicate =
16314 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
16315 const auto *LHS = SE.getSCEV(Cmp->getOperand(0));
16316 const auto *RHS = SE.getSCEV(Cmp->getOperand(1));
16317 // If LHS is a constant, apply information to the other expression.
16318 // TODO: If LHS is not a constant, check if using CompareSCEVComplexity
16319 // can improve results.
16320 if (isa<SCEVConstant>(LHS)) {
16321 std::swap(LHS, RHS);
16323 }
16324 GuardsToProcess.emplace_back(Predicate, LHS, RHS);
16325 continue;
16326 }
16327
16328 Value *L, *R;
16329 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
16330 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
16331 Worklist.push_back(L);
16332 Worklist.push_back(R);
16333 }
16334 }
16335 }
16336
16337 // Process divisibility guards in reverse order to populate DivGuards early.
16338 DenseMap<const SCEV *, APInt> Multiples;
16339 LoopGuards DivGuards(SE);
16340 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess) {
16341 if (!isDivisibilityGuard(LHS, RHS, SE))
16342 continue;
16343 collectDivisibilityInformation(Predicate, LHS, RHS, DivGuards.RewriteMap,
16344 Multiples, SE);
16345 }
16346
16347 for (const auto &[Predicate, LHS, RHS] : GuardsToProcess)
16348 CollectCondition(Predicate, LHS, RHS, Guards.RewriteMap, DivGuards);
16349
16350 // Apply divisibility information last. This ensures it is applied to the
16351 // outermost expression after other rewrites for the given value.
16352 for (const auto &[K, Divisor] : Multiples) {
16353 const SCEV *DivisorSCEV = SE.getConstant(Divisor);
16354 Guards.RewriteMap[K] =
16356 Guards.rewrite(K), Divisor, SE),
16357 DivisorSCEV),
16358 DivisorSCEV);
16359 ExprsToRewrite.push_back(K);
16360 }
16361
16362 // Let the rewriter preserve NUW/NSW flags if the unsigned/signed ranges of
16363 // the replacement expressions are contained in the ranges of the replaced
16364 // expressions.
16365 Guards.PreserveNUW = true;
16366 Guards.PreserveNSW = true;
16367 for (const SCEV *Expr : ExprsToRewrite) {
16368 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16369 Guards.PreserveNUW &=
16370 SE.getUnsignedRange(Expr).contains(SE.getUnsignedRange(RewriteTo));
16371 Guards.PreserveNSW &=
16372 SE.getSignedRange(Expr).contains(SE.getSignedRange(RewriteTo));
16373 }
16374
16375 // Now that all rewrite information is collect, rewrite the collected
16376 // expressions with the information in the map. This applies information to
16377 // sub-expressions.
16378 if (ExprsToRewrite.size() > 1) {
16379 for (const SCEV *Expr : ExprsToRewrite) {
16380 const SCEV *RewriteTo = Guards.RewriteMap[Expr];
16381 Guards.RewriteMap.erase(Expr);
16382 Guards.RewriteMap.insert({Expr, Guards.rewrite(RewriteTo)});
16383 }
16384 }
16385}
16386
16388 /// A rewriter to replace SCEV expressions in Map with the corresponding entry
16389 /// in the map. It skips AddRecExpr because we cannot guarantee that the
16390 /// replacement is loop invariant in the loop of the AddRec.
16391 class SCEVLoopGuardRewriter
16392 : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
16395
16397
16398 public:
16399 SCEVLoopGuardRewriter(ScalarEvolution &SE,
16400 const ScalarEvolution::LoopGuards &Guards)
16401 : SCEVRewriteVisitor(SE), Map(Guards.RewriteMap),
16402 NotEqual(Guards.NotEqual) {
16403 if (Guards.PreserveNUW)
16404 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNUW);
16405 if (Guards.PreserveNSW)
16406 FlagMask = ScalarEvolution::setFlags(FlagMask, SCEV::FlagNSW);
16407 }
16408
16409 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
16410
16411 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
16412 return Map.lookup_or(Expr, Expr);
16413 }
16414
16415 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
16416 if (const SCEV *S = Map.lookup(Expr))
16417 return S;
16418
16419 // If we didn't find the extact ZExt expr in the map, check if there's
16420 // an entry for a smaller ZExt we can use instead.
16421 Type *Ty = Expr->getType();
16422 const SCEV *Op = Expr->getOperand(0);
16423 unsigned Bitwidth = Ty->getScalarSizeInBits() / 2;
16424 while (Bitwidth % 8 == 0 && Bitwidth >= 8 &&
16425 Bitwidth > Op->getType()->getScalarSizeInBits()) {
16426 Type *NarrowTy = IntegerType::get(SE.getContext(), Bitwidth);
16427 auto *NarrowExt = SE.getZeroExtendExpr(Op, NarrowTy);
16428 if (const SCEV *S = Map.lookup(NarrowExt))
16429 return SE.getZeroExtendExpr(S, Ty);
16430 Bitwidth = Bitwidth / 2;
16431 }
16432
16434 Expr);
16435 }
16436
16437 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
16438 if (const SCEV *S = Map.lookup(Expr))
16439 return S;
16441 Expr);
16442 }
16443
16444 const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
16445 if (const SCEV *S = Map.lookup(Expr))
16446 return S;
16448 }
16449
16450 const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
16451 if (const SCEV *S = Map.lookup(Expr))
16452 return S;
16454 }
16455
16456 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
16457 // Helper to check if S is a subtraction (A - B) where A != B, and if so,
16458 // return UMax(S, 1).
16459 auto RewriteSubtraction = [&](const SCEV *S) -> const SCEV * {
16460 SCEVUse LHS, RHS;
16461 if (MatchBinarySub(S, LHS, RHS)) {
16462 if (LHS > RHS)
16463 std::swap(LHS, RHS);
16464 if (NotEqual.contains({LHS, RHS})) {
16465 const SCEV *OneAlignedUp = getNextSCEVDivisibleByDivisor(
16466 SE.getOne(S->getType()), SE.getConstantMultiple(S), SE);
16467 return SE.getUMaxExpr(OneAlignedUp, S);
16468 }
16469 }
16470 return nullptr;
16471 };
16472
16473 // Check if Expr itself is a subtraction pattern with guard info.
16474 if (const SCEV *Rewritten = RewriteSubtraction(Expr))
16475 return Rewritten;
16476
16477 // Trip count expressions sometimes consist of adding 3 operands, i.e.
16478 // (Const + A + B). There may be guard info for A + B, and if so, apply
16479 // it.
16480 // TODO: Could more generally apply guards to Add sub-expressions.
16481 if (isa<SCEVConstant>(Expr->getOperand(0)) &&
16482 Expr->getNumOperands() == 3) {
16483 const SCEV *Add =
16484 SE.getAddExpr(Expr->getOperand(1), Expr->getOperand(2));
16485 if (const SCEV *Rewritten = RewriteSubtraction(Add))
16486 return SE.getAddExpr(
16487 Expr->getOperand(0), Rewritten,
16488 ScalarEvolution::maskFlags(Expr->getNoWrapFlags(), FlagMask));
16489 if (const SCEV *S = Map.lookup(Add))
16490 return SE.getAddExpr(Expr->getOperand(0), S);
16491 }
16492 SmallVector<SCEVUse, 2> Operands;
16493 bool Changed = false;
16494 for (SCEVUse Op : Expr->operands()) {
16495 Operands.push_back(
16497 Changed |= Op != Operands.back();
16498 }
16499 // We are only replacing operands with equivalent values, so transfer the
16500 // flags from the original expression.
16501 return !Changed ? Expr
16502 : SE.getAddExpr(Operands,
16504 Expr->getNoWrapFlags(), FlagMask));
16505 }
16506
16507 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
16508 SmallVector<SCEVUse, 2> Operands;
16509 bool Changed = false;
16510 for (SCEVUse Op : Expr->operands()) {
16511 Operands.push_back(
16513 Changed |= Op != Operands.back();
16514 }
16515 // We are only replacing operands with equivalent values, so transfer the
16516 // flags from the original expression.
16517 return !Changed ? Expr
16518 : SE.getMulExpr(Operands,
16520 Expr->getNoWrapFlags(), FlagMask));
16521 }
16522 };
16523
16524 if (RewriteMap.empty() && NotEqual.empty())
16525 return Expr;
16526
16527 SCEVLoopGuardRewriter Rewriter(SE, *this);
16528 return Rewriter.visit(Expr);
16529}
16530
16531const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
16532 return applyLoopGuards(Expr, LoopGuards::collect(L, *this));
16533}
16534
16536 const LoopGuards &Guards) {
16537 return Guards.rewrite(Expr);
16538}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:856
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:672
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool isSigned(unsigned Opcode)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define op(i)
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This defines the Use class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define T
#define T1
MachineInstr unsigned OpIdx
static constexpr unsigned SM(unsigned Version)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops verify
PowerPC Reduce CR logical Operation
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI 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 insertFoldCacheEntry(const ScalarEvolution::FoldID &ID, const SCEV *S, DenseMap< ScalarEvolution::FoldID, const SCEV * > &FoldCache, DenseMap< const SCEV *, SmallVector< ScalarEvolution::FoldID, 2 > > &FoldCacheUser)
static cl::opt< bool > ClassifyExpressions("scalar-evolution-classify-expressions", cl::Hidden, cl::init(true), cl::desc("When printing analysis, include information on every instruction"))
static bool hasHugeExpression(ArrayRef< SCEVUse > Ops)
Returns true if Ops contains a huge SCEV (the subtree of S contains at least HugeExprThreshold nodes)...
static bool CanConstantFold(const Instruction *I)
Return true if we can constant fold an instruction of the specified type, assuming that all operands ...
static cl::opt< unsigned > AddOpsInlineThreshold("scev-addops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining addition operands into a SCEV"), cl::init(500))
static cl::opt< unsigned > MaxLoopGuardCollectionDepth("scalar-evolution-max-loop-guard-collection-depth", cl::Hidden, cl::desc("Maximum depth for recursive loop guard collection"), cl::init(1))
static cl::opt< bool > VerifyIR("scev-verify-ir", cl::Hidden, cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), cl::init(false))
static bool RangeRefPHIAllowedOperands(DominatorTree &DT, PHINode *PHI)
static const SCEV * getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static std::optional< APInt > MinOptional(std::optional< APInt > X, std::optional< APInt > Y)
Helper function to compare optional APInts: (a) if X and Y both exist, return min(X,...
static cl::opt< unsigned > MulOpsInlineThreshold("scev-mulops-inline-threshold", cl::Hidden, cl::desc("Threshold for inlining multiplication operands into a SCEV"), cl::init(32))
static BinaryOperator * getCommonInstForPHI(PHINode *PN)
static bool isDivisibilityGuard(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE)
static std::optional< const SCEV * > createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr, const SCEV *TrueExpr, const SCEV *FalseExpr)
static Constant * BuildConstantFromSCEV(const SCEV *V)
This builds up a Constant using the ConstantExpr interface.
static ConstantInt * EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, ScalarEvolution &SE)
static const SCEV * BinomialCoefficient(const SCEV *It, unsigned K, ScalarEvolution &SE, Type *ResultTy)
Compute BC(It, K). The result has width W. Assume, K > 0.
static cl::opt< unsigned > MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), cl::init(8))
static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, const SCEV *Candidate)
Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
static PHINode * getConstantEvolvingPHI(Value *V, const Loop *L)
getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node in the loop that V is deri...
static const SCEV * SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, SmallVectorImpl< const SCEVPredicate * > *Predicates, ScalarEvolution &SE, const Loop *L)
Finds the minimum unsigned root of the following equation:
static cl::opt< unsigned > MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, cl::desc("Maximum number of iterations SCEV will " "symbolically execute a constant " "derived loop"), cl::init(100))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static void PrintSCEVWithTypeHint(raw_ostream &OS, const SCEV *S)
When printing a top-level SCEV for trip counts, it's helpful to include a type for constants which ar...
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, const Loop *L)
static SCEV::NoWrapFlags StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, ArrayRef< SCEVUse > Ops, SCEV::NoWrapFlags Flags)
static bool containsConstantInAddMulChain(const SCEV *StartExpr)
Determine if any of the operands in this SCEV are a constant or if any of the add or multiply express...
static const SCEV * getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, ScalarEvolution *SE, unsigned Depth)
static bool CollectAddOperandsWithScales(SmallDenseMap< SCEVUse, APInt, 16 > &M, SmallVectorImpl< SCEVUse > &NewOps, APInt &AccumulatedConstant, ArrayRef< SCEVUse > Ops, const APInt &Scale, ScalarEvolution &SE)
Process the given Ops list, which is a list of operands to be added under the given scale,...
static const SCEV * constantFoldAndGroupOps(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, SmallVectorImpl< SCEVUse > &Ops, FoldT Fold, IsIdentityT IsIdentity, IsAbsorberT IsAbsorber)
Performs a number of common optimizations on the passed Ops.
static cl::opt< unsigned > MaxPhiSCCAnalysisSize("scalar-evolution-max-scc-analysis-depth", cl::Hidden, cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " "Phi strongly connected components"), cl::init(8))
static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static void GroupByComplexity(SmallVectorImpl< SCEVUse > &Ops, LoopInfo *LI, DominatorTree &DT)
Given a list of SCEV objects, order them by their complexity, and group objects of the same complexit...
static bool collectDivisibilityInformation(ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, DenseMap< const SCEV *, const SCEV * > &DivInfo, DenseMap< const SCEV *, APInt > &Multiples, ScalarEvolution &SE)
static cl::opt< unsigned > MaxSCEVOperationsImplicationDepth("scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV operations implication analysis"), cl::init(2))
static void PushDefUseChildren(Instruction *I, SmallVectorImpl< Instruction * > &Worklist, SmallPtrSetImpl< Instruction * > &Visited)
Push users of the given Instruction onto the given Worklist.
static std::optional< APInt > SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, const ConstantRange &Range, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n iterations.
static cl::opt< bool > UseContextForNoWrapFlagInference("scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden, cl::desc("Infer nuw/nsw flags using context where suitable"), cl::init(true))
static cl::opt< bool > EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden, cl::desc("Handle <= and >= in finite loops"), cl::init(true))
static bool getOperandsForSelectLikePHI(DominatorTree &DT, PHINode *PN, Value *&Cond, Value *&LHS, Value *&RHS)
static std::optional< std::tuple< APInt, APInt, APInt, APInt, unsigned > > GetQuadraticEquation(const SCEVAddRecExpr *AddRec)
For a given quadratic addrec, generate coefficients of the corresponding quadratic equation,...
static bool isKnownPredicateExtendIdiom(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static std::optional< BinaryOp > MatchBinaryOp(Value *V, const DataLayout &DL, AssumptionCache &AC, const DominatorTree &DT, const Instruction *CxtI)
Try to map V into a BinaryOp, and return std::nullopt on failure.
static std::optional< APInt > SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE)
Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n iterations.
static std::optional< APInt > TruncIfPossible(std::optional< APInt > X, unsigned BitWidth)
Helper function to truncate an optional APInt to a given BitWidth.
static cl::opt< unsigned > MaxSCEVCompareDepth("scalar-evolution-max-scev-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive SCEV complexity comparisons"), cl::init(32))
static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, const SCEVConstant *ConstantTerm, const SCEVAddExpr *WholeAddExpr)
static cl::opt< unsigned > MaxConstantEvolvingDepth("scalar-evolution-max-constant-evolving-depth", cl::Hidden, cl::desc("Maximum depth of recursive constant evolving"), cl::init(32))
static bool MatchBinarySub(const SCEV *S, SCEVUse &LHS, SCEVUse &RHS)
static std::optional< ConstantRange > GetRangeFromMetadata(Value *V)
Helper method to assign a range to V from metadata present in the IR.
static cl::opt< unsigned > HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, cl::desc("Size of the expression which is considered huge"), cl::init(4096))
static Type * isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, bool &Signed, ScalarEvolution &SE)
Helper function to createAddRecFromPHIWithCasts.
static Constant * EvaluateExpression(Value *V, const Loop *L, DenseMap< Instruction *, Constant * > &Vals, const DataLayout &DL, const TargetLibraryInfo *TLI)
EvaluateExpression - Given an expression that passes the getConstantEvolvingPHI predicate,...
static const SCEV * getPreviousSCEVDivisibleByDivisor(const SCEV *Expr, const APInt &DivisorVal, ScalarEvolution &SE)
static const SCEV * MatchNotExpr(const SCEV *Expr)
If Expr computes ~A, return A else return nullptr.
static std::pair< ConstantRange, bool > getRangeForAffineARHelper(APInt Step, const ConstantRange &StartRange, const APInt &MaxBECount, bool Signed)
static cl::opt< unsigned > MaxValueCompareDepth("scalar-evolution-max-value-compare-depth", cl::Hidden, cl::desc("Maximum depth of recursive value complexity comparisons"), cl::init(2))
static const SCEV * applyDivisibilityOnMinMaxExpr(const SCEV *MinMaxExpr, APInt Divisor, ScalarEvolution &SE)
static cl::opt< bool, true > VerifySCEVOpt("verify-scev", cl::Hidden, cl::location(VerifySCEV), cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"))
static const SCEV * getSignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static cl::opt< unsigned > MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, cl::desc("Maximum depth of recursive arithmetics"), cl::init(32))
static bool HasSameValue(const SCEV *A, const SCEV *B)
SCEV structural equivalence is usually sufficient for testing whether two expressions are equal,...
static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow)
Compute the result of "n choose k", the binomial coefficient.
static std::optional< int > CompareSCEVComplexity(const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, DominatorTree &DT, unsigned Depth=0)
static bool canConstantEvolve(Instruction *I, const Loop *L)
Determine whether this instruction can constant evolve within this loop assuming its operands can all...
static PHINode * getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, DenseMap< Instruction *, PHINode * > &PHIMap, unsigned Depth)
getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by recursing through each instructi...
static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind)
static cl::opt< bool > VerifySCEVStrict("verify-scev-strict", cl::Hidden, cl::desc("Enable stricter verification with -verify-scev is passed"))
static Constant * getOtherIncomingValue(PHINode *PN, BasicBlock *BB)
static cl::opt< bool > UseExpensiveRangeSharpening("scalar-evolution-use-expensive-range-sharpening", cl::Hidden, cl::init(false), cl::desc("Use more powerful methods of sharpening expression ranges. May " "be costly in terms of compile time"))
static const SCEV * getUnsignedOverflowLimitForStep(const SCEV *Step, ICmpInst::Predicate *Pred, ScalarEvolution *SE)
static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Is LHS Pred RHS true on the virtue of LHS or RHS being a Min or Max expression?
static bool BrPHIToSelect(DominatorTree &DT, CondBrInst *BI, PHINode *Merge, Value *&C, Value *&LHS, Value *&RHS)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static bool InBlock(const Value *V, const BasicBlock *BB)
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
Virtual Register Rewriter
Value * RHS
Value * LHS
BinaryOperator * Mul
static const uint32_t IV[8]
Definition blake3_impl.h:83
SCEVCastSinkingRewriter(ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
static const SCEV * rewrite(const SCEV *Scev, ScalarEvolution &SE, Type *TargetTy, ConversionFn CreatePtrCast)
const SCEV * visitUnknown(const SCEVUnknown *Expr)
const SCEV * visitMulExpr(const SCEVMulExpr *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:2006
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1210
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:467
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1970
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
bool isNonPositive() const
Determine if this APInt Value is non-positive (<= 0).
Definition APInt.h:362
unsigned countTrailingZeros() const
Definition APInt.h:1672
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
unsigned logBase2() const
Definition APInt.h:1786
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:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
bool isSignBitSet() const
Determine if sign bit of this APInt is set.
Definition APInt.h:342
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1139
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:433
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
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:461
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:484
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
This class represents a function call, abstracting a target machine's calling convention.
virtual void deleted()
Callback for Value destruction.
void setValPtr(Value *P)
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
bool isUnsigned() const
Definition InstrTypes.h:999
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition InstrTypes.h:989
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1497
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
LLVM_ABI void print(raw_ostream &OS) const
Print out the bounds to a stream.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
LLVM_ABI unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
LLVM_ABI ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:133
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition DenseMap.h:236
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
void swap(DerivedT &RHS)
Definition DenseMap.h:437
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:306
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This class describes a reference to an interned FoldingSetNodeID, which can be a useful to store node...
Definition FoldingSet.h:171
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
static GEPNoWrapFlags none()
static LLVM_ABI Type * getTypeAtIndex(Type *Ty, Value *Idx)
Return the type of the element at the given index of an indexable type.
Module * getParent()
Get the module that this global value is contained inside of...
static bool isPrivateLinkage(LinkageTypes Linkage)
static bool isInternalLinkage(LinkageTypes Linkage)
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getCmpPredicate() const
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
CmpPredicate getSwappedCmpPredicate() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
CmpPredicate getInverseCmpPredicate() const
Predicate getNonStrictCmpPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static CmpPredicate getInverseCmpPredicate(CmpPredicate Pred)
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:587
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:612
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
Metadata node.
Definition Metadata.h:1069
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2, ArrayRef< const SCEVPredicate * > ExtraPreds={}) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds and ExtraPreds.
LLVM_ABI bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've statically proved that V doesn't wrap.
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V, SmallVectorImpl< const SCEVPredicate * > *WrapPredsAdded=nullptr)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI void addPredicates(ArrayRef< const SCEVPredicate * > Preds)
Adds all predicates in Preds.
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
constexpr bool isValid() const
Definition Register.h:112
This node represents an addition of some number of SCEVs.
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a recurrence without clearing any previously set flags.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
bool isQuadratic() const
Return true if this represents an expression A + B*x + C*x^2 where A, B and C are loop invariant valu...
LLVM_ABI const SCEV * getNumIterationsInRange(const ConstantRange &Range, ScalarEvolution &SE) const
Return the number of iterations of this loop that produce values in the specified constant range.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This is the base class for unary cast operator classes.
LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
void setNoWrapFlags(NoWrapFlags Flags)
Set flags for a non-recurrence without clearing previously set flags.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents a constant integer value.
ConstantInt * getValue() const
const APInt & getAPInt() const
This is the base class for unary integral cast operator classes.
LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, SCEVUse op, Type *ty)
This node is the base class min/max selections.
static enum SCEVTypes negate(enum SCEVTypes T)
This node represents multiplication of some number of SCEVs.
This node is a base class providing common functionality for n'ary operators.
ArrayRef< SCEVUse > operands() const
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
SCEVUse getOperand(unsigned i) const
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
SCEVPredicateKind Kind
This class represents a cast from a pointer to a pointer-sized integer value, without capturing the p...
This class represents a cast from a pointer to a pointer-sized integer value.
This visitor recursively visits a SCEV expression and re-writes it.
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *Expr)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr)
const SCEV * visitSMinExpr(const SCEVSMinExpr *Expr)
const SCEV * visitUMinExpr(const SCEVUMinExpr *Expr)
This class represents a signed minimum selection.
This node is the base class for sequential/in-order min/max selections.
static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty)
This class represents a sign extension of a small integer value to a larger integer value.
Visit all nodes in the expression tree using worklist traversal.
This class represents a truncation of an integer value to a smaller integer value.
This class represents a binary unsigned division operation.
This class represents an unsigned minimum selection.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
void print(raw_ostream &OS, unsigned Depth) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
bool isAlwaysTrue() const override
Implementation of the SCEVPredicate interface.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents the value of vscale, as used when defining the length of a scalable vector or r...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Returns true if this predicate implies N.
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
void print(raw_ostream &OS, unsigned Depth=0) const override
Prints a textual representation of this predicate with an indentation of Depth.
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEVAddRecExpr * getExpr() const
Implementation of the SCEVPredicate interface.
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static SCEVWrapPredicate::IncrementWrapFlags getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Returns the set of SCEVWrapPredicate no wrap flags implied by a SCEVAddRecExpr.
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
This class represents a zero extension of a small integer value to a larger integer value.
This class represents an analyzed expression in the program.
unsigned short getExpressionSize() const
SCEVNoWrapFlags NoWrapFlags
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
static constexpr auto FlagAnyWrap
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize)
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void print(raw_ostream &OS, const Module *=nullptr) const override
print - Print out the internal state of the pass.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getZeroExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty)
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI const SCEV * getPtrToIntExpr(const SCEV *Op, Type *Ty)
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getSignExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI bool isLoopUniform(const SCEV *S, const Loop *L)
Returns true if the given SCEV is loop-uniform with respect to the specified loop L.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
@ LoopUniform
The SCEV is loop-uniform.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > &Assumptions)
Check that S is a multiple of M.
LLVM_ABI const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
LLVM_ABI void forgetAllLoops()
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:293
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
TypeSize getSizeInBits() const
Definition DataLayout.h:754
Class to represent struct types.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2279
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2284
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2289
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:2847
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2294
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:830
constexpr bool any(E Val)
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
int getMinValue(MCInstrInfo const &MCII, MCInst const &MCI)
Return the minimum value of an extendable operand.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVZeroExtendExpr, Op0_t > m_scev_ZExt(const Op0_t &Op0)
is_undef_or_poison m_scev_UndefOrPoison()
Match an SCEVUnknown wrapping undef or poison.
cst_pred_ty< is_one > m_scev_One()
Match an integer 1.
specificloop_ty m_SpecificLoop(const Loop *L)
SCEVUnaryExpr_match< SCEVSignExtendExpr, Op0_t > m_scev_SExt(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
cst_pred_ty< is_zero > m_scev_Zero()
Match an integer 0.
SCEVUnaryExpr_match< SCEVTruncateExpr, Op0_t > m_scev_Trunc(const Op0_t &Op0)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
specificscev_ty m_scev_Specific(const SCEV *S)
Match if we have a specific specified SCEV.
SCEVAffineAddRec_match< Op0_t, Op1_t, match_isa< const Loop > > m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVUnknown > m_SCEVUnknown(const SCEVUnknown *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNUW, true > m_scev_c_NUWMul(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagAnyWrap, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
SCEVBinaryExpr_match< SCEVSMaxExpr, Op0_t, Op1_t > m_scev_SMax(const Op0_t &Op0, const Op1_t &Op1)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
Definition CoroShape.h:32
constexpr double e
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
SaveAndRestore(T &) -> SaveAndRestore< T >
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
@ Dead
Unused definition.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
scope_exit(Callable) -> scope_exit< Callable >
@ BinaryOp
One of the operands is a binary op.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
void * PointerTy
LLVM_ABI bool VerifySCEV
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2111
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:94
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
iterator_range< pointee_iterator< WrappedIteratorT > > make_pointee_range(RangeT &&Range)
Definition iterator.h:341
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned short computeExpressionSize(ArrayRef< SCEVUse > Args)
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:378
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:395
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2088
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define NC
Definition regutils.h:42
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
An object of this class is returned by queries that could not be answered.
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
This class defines a simple visitor class that may be used for various SCEV analysis purposes.
A utility class that uses RAII to save and restore the value of a variable.
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.